-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.go
104 lines (90 loc) · 1.88 KB
/
game.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
package main
import (
"github.com/nsf/termbox-go"
)
type Game struct {
boardWidth int
boardHeight int
board *Board
boardView *BoardView
model *GameModel
frameCount int
}
const (
w = 10
h = 20
)
func NewGame() *Game {
game := Game{
boardWidth: w,
boardHeight: h,
}
game.board = NewBoard(w, h)
game.model = &GameModel{targetNumberOfLinesToLevelUp: linesPerLevel}
game.boardView = &BoardView{game.board, 1, 1}
return &game
}
func (game *Game) Restart() {
game.board = NewBoard(w, h)
game.model = &GameModel{}
game.boardView = &BoardView{game.board, 1, 1}
}
func (game *Game) Render() {
RenderCell(0, 0, game.boardWidth+2, game.boardHeight+2, BORDER_COLOR)
RenderCell(1, 1, game.boardWidth, game.boardHeight, BOARD_BG_COLOR)
game.boardView.Render()
RenderScoreboard(game.boardWidth*2+5, 8, game.model)
RenderNextTetrimino(game.boardWidth+2, 0, game.board.nextTetrimino)
if game.model.IsGameOver {
RenderGameOver()
}
}
func (game *Game) Update() {
game.frameCount++
if game.frameCount >= framesPerBlock(game) {
game.frameCount = 0
if !game.model.IsGameOver {
game.MoveDown()
}
}
}
func framesPerBlock(game *Game) int {
frames := 15 - (game.model.Level * 2)
if frames < 1 {
frames = 1
}
return frames
}
func (game *Game) OnKeyPress(key termbox.Key) {
if game.model.IsGameOver {
game.Restart()
return
}
switch key {
case termbox.KeyArrowDown:
game.MoveDown()
break
case termbox.KeyArrowUp:
game.board.Rotate()
break
case termbox.KeyArrowRight:
game.board.MoveRight()
break
case termbox.KeyArrowLeft:
game.board.MoveLeft()
break
case termbox.KeySpace:
game.board.FallDown()
break
}
}
func (game *Game) MoveDown() {
moved := game.board.MoveDown()
if !moved {
clearedLines := game.board.StartNewTurn()
game.model.updateGameModel(clearedLines)
if game.board.isGameOver() {
game.model.IsGameOver = true
}
}
}