-
Notifications
You must be signed in to change notification settings - Fork 37
/
gophermark.go
131 lines (113 loc) · 2.5 KB
/
gophermark.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"fmt"
"image"
"math"
"math/rand"
"os"
"time"
_ "image/png"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
)
type gopher struct {
pos pixel.Vec
vel pixel.Vec
// angle float32
}
// newGopher creates a gopher with given position and random velocity.
func newGopher(p pixel.Vec) gopher {
g := gopher{
pos: p,
}
v := pixel.V(1, 0)
v = v.Rotated(rand.Float64() * 2 * math.Pi)
g.vel = v.Scaled(rand.Float64()*100 + 50)
return g
}
// update updates the gophers position and ensures he stays on screen.
func (g *gopher) update(dt float64) {
g.pos = g.pos.Add(g.vel.Scaled(dt))
if g.pos.X <= pic.Bounds().W()/2 {
g.vel.X *= -1
} else if g.pos.X > win.Bounds().Max.X-pic.Bounds().W()/2 {
g.vel.X *= -1
}
if g.pos.Y <= pic.Bounds().H()/2 {
g.vel.Y *= -1
} else if g.pos.Y > win.Bounds().Max.Y-pic.Bounds().H()/2 {
g.vel.Y *= -1
}
}
var (
win *pixelgl.Window
pic pixel.Picture
sprite *pixel.Sprite
gophers []gopher
frames = 0
second = time.Tick(time.Second)
)
func loadPicture(path string) (pixel.Picture, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return pixel.PictureDataFromImage(img), nil
}
func run() {
rand.Seed(time.Now().UnixNano())
cfg := pixelgl.WindowConfig{
Title: "Gophermark",
Bounds: pixel.R(0, 0, 1000, 800),
}
w, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
win = w
p, err := loadPicture("gopher.png")
if err != nil {
panic(err)
}
pic = p
batch := pixel.NewBatch(&pixel.TrianglesData{}, pic)
sprite = pixel.NewSprite(pic, pic.Bounds())
for i := 0; i < 1000; i++ {
gophers = append(gophers, newGopher(pixel.V(win.Bounds().W()/2, win.Bounds().H()/2)))
}
last := time.Now()
for !win.Closed() && !win.JustPressed(pixelgl.KeyEscape) {
dt := time.Since(last).Seconds()
last = time.Now()
if win.Pressed(pixelgl.MouseButtonLeft) {
mouse := win.MousePosition()
for i := 0; i < 10; i++ {
gophers = append(gophers, newGopher(mouse))
}
}
batch.Clear()
for i := 0; i < len(gophers); i++ {
gophers[i].update(dt)
sprite.Draw(batch, pixel.IM.Moved(gophers[i].pos))
}
win.Clear(colornames.Black)
batch.Draw(win)
win.Update()
frames++
select {
case <-second:
win.SetTitle(fmt.Sprintf("%s | Gophers: %d | FPS: %d", cfg.Title, len(gophers), frames))
frames = 0
default:
}
}
}
func main() {
pixelgl.Run(run)
}