-
Notifications
You must be signed in to change notification settings - Fork 11
/
game.go
155 lines (138 loc) · 2.11 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package main
import (
_ "fmt"
)
type Direction int
const (
UP Direction = iota
DOWN
LEFT
RIGHT
)
var baseTokens = []byte("#@XO* ")
var (
WALL = baseTokens[0]
GUY = baseTokens[1]
SLOT = baseTokens[2]
BOX = baseTokens[3]
BOXIN = baseTokens[4]
FLOOR = baseTokens[5]
)
type Cell struct {
base, obj byte
}
type Game struct {
level int
board [][]Cell
db *ldb
x int
y int
debug bool
}
func NewGame() *Game {
g := &Game{
level: 1,
db: &ldb{},
}
g.db.loadAll()
g.reset()
return g
}
// reset current level
func (g *Game) reset() {
g.board = g.db.getLevel(g.level)
g.whereami()
}
func (g *Game) whereami() {
for y, cels := range g.board {
for x, cel := range cels {
if cel.obj == GUY {
g.x, g.y = x, y
}
}
}
}
func (g *Game) checkMove(dx, dy int) {
var (
x, y int
k = 1
)
for {
x, y = g.x+dx*k, g.y+dy*k
cell := g.board[y][x]
switch cell.obj {
case FLOOR, SLOT:
// move obj along the way foward
for k > 0 {
xp, yp := x-dx, y-dy
g.board[y][x].obj = g.board[yp][xp].obj
x, y = xp, yp
k--
}
g.board[y][x].obj = g.board[y][x].base
g.x, g.y = x+dx, y+dy
return
case WALL:
return
case BOX:
if g.board[y+dy][x+dx].obj == BOX {
return
}
}
k++
}
}
func (g *Game) move(dir Direction) {
switch dir {
case UP:
g.checkMove(0, -1)
case DOWN:
g.checkMove(0, 1)
case LEFT:
g.checkMove(-1, 0)
case RIGHT:
g.checkMove(1, 0)
}
done := g.checkState()
if done {
g.nextLevel()
}
}
func (g *Game) checkState() bool {
for _, cells := range g.board {
for _, cell := range cells {
if cell.base == SLOT && cell.obj != BOX {
return false
}
}
}
return true
}
func (g *Game) nextLevel() {
if g.level < g.db.maxLevel {
g.level = g.level + 1
g.reset()
}
}
func (g *Game) prevLevel() {
if g.level > 1 {
g.level = g.level - 1
g.reset()
}
}
func (g *Game) toggleDebug() {
g.debug = !g.debug
}
// func main() {
// var p = func(g *Game) {
// for i, row := range g.board {
// fmt.Printf("%-2d %q\n", i, row)
// }
// fmt.Println()
// }
//
// g := NewGame()
// p(g)
// g.move(RIGHT)
// p(g)
// }