-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathgame_2048.py
More file actions
271 lines (232 loc) · 8.62 KB
/
game_2048.py
File metadata and controls
271 lines (232 loc) · 8.62 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import pygame
import numpy as np
import copy
import os
from pygame.locals import *
# Colors for different tile values
COLORS = {
0: (205, 193, 180),
2: (238, 228, 218),
4: (237, 224, 200),
8: (242, 177, 121),
16: (245, 149, 99),
32: (246, 124, 95),
64: (246, 94, 59),
128: (237, 207, 114),
256: (237, 204, 97),
512: (237, 200, 80),
1024: (237, 197, 63),
2048: (237, 194, 46),
}
TEXT_COLORS = {
2: (119, 110, 101),
4: (119, 110, 101),
8: (255, 255, 255),
16: (255, 255, 255),
32: (255, 255, 255),
64: (255, 255, 255),
128: (255, 255, 255),
256: (255, 255, 255),
512: (255, 255, 255),
1024: (255, 255, 255),
2048: (255, 255, 255),
}
BG_COLOR = (187, 173, 160)
GRID_COLOR = (187, 173, 160)
FILENAME = 'out.npy'
class Game2048:
def __init__(self, screen=None, standalone=True):
self.score = 0
self.win = 0
self.board = self.init_board()
self.rscore = self.load_score()
self.standalone = standalone
self.screen = screen
self.font = None
self.tile_font = None
self.game_over_flag = False
self.cell_size = 100
self.padding = 10
self.board_size = 4 * self.cell_size + 5 * self.padding
if standalone and screen is None:
pygame.init()
self.screen = pygame.display.set_mode((self.board_size, self.board_size + 100))
pygame.display.set_caption('2048 Game')
self.font = pygame.font.SysFont('Arial', 30)
self.tile_font = pygame.font.SysFont('Arial', 40, bold=True)
def init_board(self):
if FILENAME not in os.listdir():
np.save(FILENAME, 0)
board = self.choice(np.zeros((4, 4), dtype=int))
return board
def choice(self, board):
udict = {}
count = 0
for i in range(4):
for j in range(4):
if not board[i, j]:
udict[count] = (i, j)
count += 1
if count == 0:
return board
random_number = np.random.randint(0, count)
two_or_four = np.random.choice([2, 2, 2, 4])
board[udict[random_number]] = two_or_four
return board
def basic(self, board):
for i in range(4):
flag = 1
while flag:
flag = 0
j = 2
while j >= 0:
if board[i, j] != 0:
if board[i, j + 1] == board[i, j]:
board[i, j + 1] = 2 * board[i, j]
if board[i, j + 1] == 2048:
self.win = 1
board[i, j] = 0
self.score += 100
flag = 1
elif board[i, j + 1] == 0:
temp = board[i, j]
board[i, j] = board[i, j + 1]
board[i, j + 1] = temp
flag = 1
j -= 1
return board
def move_right(self, board):
return self.basic(board)
def move_up(self, board):
board = board[::-1, ::-1].T
board = self.basic(board)
board = board[::-1, ::-1].T
return board
def move_left(self, board):
board = board[::-1, ::-1]
board = self.basic(board)
board = board[::-1, ::-1]
return board
def move_down(self, board):
board = board.T
board = self.basic(board)
board = board.T
return board
def move(self, order):
change = 1
tempboard = copy.deepcopy(self.board)
if order == ord('r') or order == K_r:
self.reset_game()
return
elif order == ord('q') or order == K_q:
self.save_score()
return 'quit'
elif self.win and (order in [ord('w'), ord('a'), ord('s'), ord('d'), K_UP, K_LEFT, K_DOWN, K_RIGHT]):
change = 0
return
elif order == ord('w') or order == K_UP or order == K_w:
self.board = self.move_up(self.board)
elif order == ord('s') or order == K_DOWN or order == K_s:
self.board = self.move_down(self.board)
elif order == ord('a') or order == K_LEFT or order == K_a:
self.board = self.move_left(self.board)
elif order == ord('d') or order == K_RIGHT or order == K_d:
self.board = self.move_right(self.board)
else:
newboard = self.board
if (self.board == tempboard).all():
change = 0
if change:
self.board = self.choice(self.board)
self.check_fail()
self.rscore = max(self.rscore, self.score)
def check_fail(self):
if (self.board != 0).all():
diff1 = self.board[:, 1:] - self.board[:, :-1]
diff2 = self.board[1:, :] - self.board[:-1, :]
inter = (diff1 != 0).all() and (diff2 != 0).all()
if inter:
self.game_over_flag = True
self.save_score()
def load_score(self):
try:
rank_score = np.load(FILENAME)
return int(rank_score)
except:
return 0
def save_score(self):
if self.score > self.rscore:
np.save(FILENAME, self.score)
def reset_game(self):
self.save_score()
self.score = 0
self.win = 0
self.game_over_flag = False
self.board = self.init_board()
self.rscore = self.load_score()
def draw_board(self):
if self.screen is None:
return
self.screen.fill(BG_COLOR)
# Draw score
if self.font:
score_text = self.font.render(f'Score: {self.score}', True, (255, 255, 255))
self.screen.blit(score_text, (10, 10))
high_score_text = self.font.render(f'Best: {max(self.rscore, self.score)}', True, (255, 255, 255))
self.screen.blit(high_score_text, (self.board_size - 150, 10))
# Draw grid
for i in range(4):
for j in range(4):
value = self.board[i, j]
x = self.padding + j * (self.cell_size + self.padding)
y = 60 + self.padding + i * (self.cell_size + self.padding)
color = COLORS.get(int(value), (60, 58, 50))
pygame.draw.rect(self.screen, color, (x, y, self.cell_size, self.cell_size), border_radius=8)
if value != 0:
text_color = TEXT_COLORS.get(int(value), (255, 255, 255))
if self.tile_font:
text = self.tile_font.render(str(int(value)), True, text_color)
text_rect = text.get_rect(center=(x + self.cell_size // 2, y + self.cell_size // 2))
self.screen.blit(text, text_rect)
# Draw win message
if self.win:
if self.font:
win_text = self.font.render('You Win! Press R to restart', True, (0, 255, 0))
text_rect = win_text.get_rect(center=(self.board_size // 2, self.board_size // 2 + 30))
self.screen.blit(win_text, text_rect)
# Draw game over message
if self.game_over_flag:
if self.font:
over_text = self.font.render('Game Over! Press R to restart', True, (255, 0, 0))
text_rect = over_text.get_rect(center=(self.board_size // 2, self.board_size // 2 + 30))
self.screen.blit(over_text, text_rect)
def handle_event(self, event):
if event.type == KEYDOWN:
if event.key in [K_UP, K_DOWN, K_LEFT, K_RIGHT, K_w, K_s, K_a, K_d, K_r, K_q]:
result = self.move(event.key)
if result == 'quit':
return 'quit'
return None
def update(self):
self.draw_board()
pygame.display.update()
def run(self):
if not self.standalone:
return
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
else:
result = self.handle_event(event)
if result == 'quit':
running = False
self.update()
clock.tick(30)
self.save_score()
pygame.quit()
if __name__ == '__main__':
game = Game2048()
game.run()