-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.py
126 lines (104 loc) · 3.54 KB
/
board.py
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
from random import choice, randint, random
from cell import *
class Board():
def __init__(self, can, sample = []):
self.can = can
self.grid = []
for i in range(4):
self.grid.append([])
for j in range(4):
self.grid[i].append(0)
if not sample:
self.generateCell()
self.generateCell()
else:
for i in range(4):
for j in range(4):
if sample[i][j] == 0:
self.grid[i][j] = 0
else:
self.grid[i][j] = Cell(self, (i, j), sample[i][j])
self.moved = False
self.lost = False
def freeCells(self):
freeCells = []
for i in range(4):
for j in range(4):
if self.isFree((i, j)):
freeCells.append((i, j))
return freeCells
def generateCell(self):
cells = self.freeCells()
if cells:
(i, j) = choice(cells)
value = 2 if random() < 0.9 else 4
self.grid[i][j] = Cell(self, (i, j), value)
else:
self.lost = True
def isFree(self, position):
return self.grid[position[0]][position[1]] == 0
def inBounds(self, i, j):
return (0 <= i < 4) and (0 <= j < 4)
def update(self, direction):
if not self.freeCells:
self.lost = True
return
if direction == (-1, 0):
for i in range(4):
for j in range(4):
if not self.isFree((i, j)):
self.moveCell(self.grid[i][j], direction)
elif direction == (1, 0):
for i in range(3, -1, -1):
for j in range(4):
if not self.isFree((i, j)):
self.moveCell(self.grid[i][j], direction)
elif direction == (0, -1):
for j in range(4):
for i in range(4):
if not self.isFree((i, j)):
self.moveCell(self.grid[i][j], direction)
else:
for j in range(3, -1, -1):
for i in range(4):
if not self.isFree((i, j)):
self.moveCell(self.grid[i][j], direction)
if self.moved:
self.generateCell()
self.moved = False
return self
def moveCell(self, cell, direction):
while cell.canMove(direction, self):
i, j = cell.pos
cell.move(direction)
x, y = cell.pos
self.grid[x][y] = cell
self.grid[i][j] = 0
self.moved = True
i, j = cell.pos
x, y = (i + direction[0], j + direction[1])
if self.inBounds(x, y):
neighboor = self.grid[x][y]
if neighboor.value == cell.value:
neighboor.increase()
self.grid[i][j] = 0
self.can.delete(cell.rect_id)
self.can.delete(cell.num_id)
self.moved = True
def score(self):
score = 0
for i in range(4):
for j in range(4):
if not self.isFree((i, j)):
score += self.grid[i][j].value
return score
def getBoard(self):
m = []
for i in range(4):
m.append([])
for j in range(4):
if self.isFree((i, j)):
m[i].append(0)
else:
m[i].append(self.grid[i][j].value)
return m