forked from jjinux/gotetris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
74 lines (63 loc) · 1.47 KB
/
controller.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
/*
Package main contains a console-based implementation of Tetris.
See the README for more details.
I'm using MVC to structure the application. However, I haven't yet
needed to make actual types for the view or the controller; I can
get away with just a simple function for each.
I don't have any tests. It's just a simple video game ;)
*/
package main
import (
"math/rand"
"time"
"github.com/nsf/termbox-go"
)
const animationSpeed = 10 * time.Millisecond
// Function main initializes termbox, renders the view, and starts
// handling events.
func main() {
rand.Seed(time.Now().UnixNano())
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
g := NewGame()
render(g)
for {
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
switch {
case ev.Key == termbox.KeyArrowLeft:
g.moveLeft()
case ev.Key == termbox.KeyArrowRight:
g.moveRight()
case ev.Key == termbox.KeyArrowUp:
g.rotate()
case ev.Key == termbox.KeyArrowDown:
g.moveDown()
case ev.Key == termbox.KeySpace:
g.fall()
case ev.Ch == 's':
g.start()
case ev.Ch == 'p':
g.pause()
case ev.Ch == 'q' || ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC || ev.Key == termbox.KeyCtrlD:
return
}
}
case <-g.fallingTimer.C:
g.play()
default:
render(g)
time.Sleep(animationSpeed)
}
}
}