Skip to content

Instantly share code, notes, and snippets.

@200sc
Created June 15, 2017 20:29
Show Gist options
  • Save 200sc/6c8e9c1c79f0157bbe6c183164065d22 to your computer and use it in GitHub Desktop.
Save 200sc/6c8e9c1c79f0157bbe6c183164065d22 to your computer and use it in GitHub Desktop.
package main
import (
"bitbucket.org/oakmoundstudio/plasticpiston/plastic"
"bitbucket.org/oakmoundstudio/plasticpiston/plastic/collision"
"bitbucket.org/oakmoundstudio/plasticpiston/plastic/entities"
"bitbucket.org/oakmoundstudio/plasticpiston/plastic/event"
"bitbucket.org/oakmoundstudio/plasticpiston/plastic/render"
"image/color"
"math/rand"
)
var (
score1 = 0
score2 = 0
)
func main() {
plastic.AddScene("pong",
func(prevScene string, data interface{}) {
NewPaddle(20, 200, 1)
NewPaddle(590, 200, 2)
NewBall(320, 240)
render.Draw(render.NewIntText(&score2, 200, 20), 3)
render.Draw(render.NewIntText(&score1, 400, 20), 3)
}, func() bool { return true }, func() (string, interface{}) { return "pong", nil })
plastic.Init("pong")
}
func NewBall(x, y float64) {
b := new(entities.Moving)
b.Init()
b.W = 10
b.H = 10
b.R = render.NewColorBox(int(b.W), int(b.H), color.RGBA{0, 255, 0, 255})
render.Draw(b.R, 2)
b.Space = collision.NewUnassignedSpace(0, 0, b.W, b.H)
b.CID.Bind(func(id int, nothing interface{}) int {
if b.DX == 0 && b.DY == 0 {
b.DY = (rand.Float64() - 0.5) * 4
b.DX = (rand.Float64() - 0.5) * 16
if b.DX == 0 {
b.DX = 8
}
}
b.ShiftPos(b.DX, b.DY)
if collision.HitLabel(b.Space, 1) {
b.DX *= -1.1
b.DY += (rand.Float64() - 0.5) * 8
}
if b.X < 0 || b.X > 640 {
if b.X < 0 {
score1++
} else {
score2++
}
b.DX = 0
b.DY = 0
b.SetPos(320, 240)
} else if b.Y < 0 || b.Y > 440-b.H {
b.DY *= -1
}
return 0
}, "EnterFrame")
b.SetPos(x, y)
}
func NewPaddle(x, y float64, player int) {
p := new(entities.Moving)
p.Init()
p.SpeedY = 4
p.W = 20
p.H = 100
p.R = render.NewColorBox(int(p.W), int(p.H), color.RGBA{255, 0, 0, 255})
render.Draw(p.R, 1)
p.Space = collision.NewLabeledSpace(0, 0, p.W, p.H, 1)
if player == 1 {
p.CID.Bind(enterPaddle("UpArrow", "DownArrow"), "EnterFrame")
} else {
p.CID.Bind(enterPaddle("W", "S"), "EnterFrame")
}
p.SetPos(x, y)
}
func enterPaddle(up, down string) func(int, interface{}) int {
return func(id int, nothing interface{}) int {
p := event.GetEntity(id).(*entities.Moving)
p.DY = 0
if plastic.IsDown(up) {
p.DY = -p.SpeedY
} else if plastic.IsDown(down) {
p.DY = p.SpeedY
}
p.ShiftY(p.DY)
if p.Y < 0 || p.Y > (440-p.H) {
p.ShiftY(-p.DY)
}
return 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment