-
Notifications
You must be signed in to change notification settings - Fork 0
/
pygame2048.py
440 lines (376 loc) · 12.3 KB
/
pygame2048.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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import random
import pygame
from pygame.time import Clock
from math import log
if __name__ == '__main__':
pygame.init()
clock = Clock()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("2048")
bg = pygame.image.load(r'images\background.png')
tiles = [pygame.image.load(r'images\2.png'), pygame.image.load(r'images\4.png'), pygame.image.load(r'images\8.png'),
pygame.image.load(r'images\16.png'), pygame.image.load(r'images\32.png'),
pygame.image.load(r'images\64.png'), pygame.image.load(r'images\128.png'),
pygame.image.load(r'images\256.png'), pygame.image.load(r'images\512.png'),
pygame.image.load(r'images\1024.png'), pygame.image.load(r'images\2048.png'),
pygame.image.load(r'images\4096.png')]
# initialise the grid
grid = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
score = 0
coordinates = [[(14, 14), (136, 14), (258, 14), (380, 14)],
[(14, 136), (136, 136), (258, 136), (380, 136)],
[(14, 258), (136, 258), (258, 258), (380, 258)],
[(14, 380), (136, 380), (258, 380), (380, 380)]]
tiles_ = []
class Tile:
def __init__(self, x, y, value):
self.x = x
self.y = y
self.value = value
self.rect = pygame.Rect(self.x, self.y, 107, 107)
def draw(self):
win.blit(tiles[self.value], (self.x, self.y))
# initial spawn of 2 random tiles
def init_spawn_tiles(grid_):
for i in range(2):
x = random.randint(0, 3)
y = random.randint(0, 3)
value = random.random()
if value < 0.9:
value = 2
else:
value = 4
while is_occupied(y, x, grid_):
x = random.randint(0, 3)
y = random.randint(0, 3)
grid_[y][x] = value
# check if a particular position is occupied
def is_occupied(y, x, grid_):
if grid_[y][x] == 0:
return False
return True
# check if all spaces are occupied
def is_all_occupied(grid_):
list_ = []
for y in range(len(grid_)):
for x in range(len(grid_)):
list_.append(is_occupied(y, x, grid_))
if False in list_:
return False
else:
return True
def spawn_tile(grid_):
if grid_ == up(grid_) and grid_ == down(grid_) and grid_ == left(grid_) and grid_ == right(grid_):
return
x = random.randint(0, 3)
y = random.randint(0, 3)
value = random.random()
if value < 0.9:
value = 2
else:
value = 4
if is_all_occupied(grid_):
return
while is_occupied(y, x, grid_):
x = random.randint(0, 3)
y = random.randint(0, 3)
grid_[y][x] = value
# move the values left and adds them up into one value if they are the same
def move_left(column, scoring=False):
global score
returned_column = [0, 0, 0, 0]
j = 0
previous_value = None
for i in range(4):
# skip if the number is zero
if column[i] != 0:
# if its the first value in the list, set it to previous
if previous_value is None:
previous_value = column[i]
else:
# if the next value is equals to the previous, add them together and add it to the new column
# increment the index of the new column
if previous_value == column[i]:
returned_column[j] = 2 * column[i]
if scoring:
score += returned_column[j]
j += 1
previous_value = None
# if not, set the current index of the new column to the previous value and increment the index of
# the new column, and set the previous value to the current iteration of the column
else:
returned_column[j] = previous_value
j += 1
previous_value = column[i]
# add the last previous value (if any) into the new_column
if previous_value is not None:
returned_column[j] = previous_value
return returned_column
def transpose_array(grid_):
for i in range(len(grid_) - 1):
for j in range(len(grid_)):
if j >= i:
temp = grid_[i][j]
grid_[i][j] = grid_[j][i]
grid_[j][i] = temp
return grid_
def switch_sides(grid_):
i = 1
for _ in range(len(grid_) // 2):
for j in range(len(grid_)):
temp = grid_[j][_]
grid_[j][_] = grid_[j][len(grid_) - i]
grid_[j][len(grid_) - i] = temp
i += 1
def rotate_90(grid_):
switch_sides(transpose_array(grid_))
return grid_
def rotate_180(grid_):
return rotate_90(rotate_90(grid_))
def rotate_270(grid_):
return rotate_90(rotate_90(rotate_90(grid_)))
def left(grid_, scoring=False):
new_grid = []
for _ in grid_:
new_column = move_left(_, scoring)
new_grid.append(new_column)
return new_grid
def down(grid_, scoring=False):
new_grid = []
grid_ = rotate_90(grid_)
for _ in grid_:
new_grid.append(move_left(_, scoring))
new_grid = rotate_270(new_grid)
grid_ = rotate_270(grid_)
return new_grid
def right(grid_, scoring=False):
new_grid = []
grid_ = rotate_180(grid_)
for _ in grid_:
new_grid.append(move_left(_, scoring))
new_grid = rotate_180(new_grid)
grid_ = rotate_180(grid_)
return new_grid
def up(grid_, scoring=False):
new_grid = []
grid_ = rotate_270(grid_)
for _ in grid_:
new_grid.append(move_left(_, scoring))
new_grid = rotate_90(new_grid)
grid_ = rotate_90(grid_)
return new_grid
def check_game_over(grid_):
if is_all_occupied(grid_):
if grid_ == up(grid_) and grid_ == down(grid_) and grid_ == left(grid_) and grid_ == right(grid_):
return True
else:
return False
else:
return False
def check_max(grid_):
highest = 0
for y in range(len(grid)):
for x in range(len(grid)):
if grid_[y][x] > highest:
highest = grid_[y][x]
return highest
# main loop for terminal
def main_terminal():
global grid
init_spawn_tiles(grid)
print(grid[0], "\n")
print(grid[1], "\n")
print(grid[2], "\n")
print(grid[3], "\n")
while True:
if check_game_over(grid):
print("game_over")
return print(score)
user_input = input("enter the direction to move in:")
if user_input == '1':
grid = up(grid)
spawn_tile(grid)
print(grid[0], "\n")
print(grid[1], "\n")
print(grid[2], "\n")
print(grid[3], "\n")
elif user_input == '2':
grid = down(grid)
spawn_tile(grid)
print(grid[0], "\n")
print(grid[1], "\n")
print(grid[2], "\n")
print(grid[3], "\n")
elif user_input == '3':
grid = left(grid)
spawn_tile(grid)
print(grid[0], "\n")
print(grid[1], "\n")
print(grid[2], "\n")
print(grid[3], "\n")
elif user_input == '4':
grid = right(grid)
spawn_tile(grid)
print(grid[0], "\n")
print(grid[1], "\n")
print(grid[2], "\n")
print(grid[3], "\n")
else:
print("INVALID INPUT!")
def redraw_screen():
global tiles_
win.blit(bg, (0, 0))
for _ in tiles_:
_.draw()
pygame.display.update()
# based on the grid generate tile objects
def generate_tiles():
global grid
global tiles_
tiles_ = []
for y in range(len(grid)):
for x in range(len(grid)):
if grid[y][x] != 0:
tiles_.append(Tile(coordinates[y][x][0], coordinates[y][x][1], int(log((grid[y][x]), 2) - 1)))
def main():
run = True
global grid
global tiles_
global score
clock.tick(15)
init_spawn_tiles(grid)
generate_tiles()
redraw_screen()
while run:
clock.tick(30)
if check_game_over(grid):
print("GAME OVER")
return print(score)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
grid = up(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif event.key == pygame.K_DOWN:
grid = down(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif event.key == pygame.K_LEFT:
grid = left(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif event.key == pygame.K_RIGHT:
grid = right(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
import evaluation_functions
class AI:
def __init__(self):
self.monotonicity_weight = 50
self.empty_weight = 400
self.merges_weight = 500
self.total_weight = 100
def evaluate_board(self, grid_):
utility = 0
monotonicity = evaluation_functions.monotonicity(grid_)
empty_merges_total = evaluation_functions.total_empty_and_merges(grid_)
utility += monotonicity * self.monotonicity_weight
utility += empty_merges_total[0] * self.empty_weight
utility += empty_merges_total[1] * self.merges_weight
utility += empty_merges_total[2] * self.total_weight
return utility
def maximise(self, grid_, depth=0):
utilities = []
grids = [left(grid_), right(grid_), up(grid_), down(grid_)]
for _ in grids:
utilities.append(self.chance(_, depth + 1))
if depth == 0:
return utilities
else:
return max(utilities)
def chance(self, grid_, depth):
average_utility = 0
probabilities = evaluation_functions.probabilities(grid_)
if probabilities:
if depth >= 3:
for _ in probabilities:
average_utility += self.evaluate_board(_[0]) * _[1]
return average_utility
for _ in probabilities:
average_utility += _[1] * self.maximise(_[0], depth + 1)
return average_utility
else:
return self.evaluate_board(grid_)
def get_best_move(self, grid_):
moves = ['LEFT', 'RIGHT', 'UP', 'DOWN']
array_ = self.maximise(grid_)
if evaluation_functions.total_empty_and_merges(grid_)[0] == 0:
if grid_ == left(grid_):
array_[0] = 0
if grid_ == right(grid_):
array_[1] = 0
if grid_ == up(grid_):
array_[2] = 0
if grid_ == down(grid_):
array_[3] = 0
index = array_.index(max(array_))
return moves[index]
ai = AI()
def main_ai():
run = True
global grid
global tiles_
global score
clock.tick(15)
init_spawn_tiles(grid)
generate_tiles()
redraw_screen()
while run:
if check_game_over(grid):
print("GAME OVER")
return print(score, check_max(grid))
move = ai.get_best_move(grid)
print(move)
if move == 'UP':
grid = up(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif move == 'DOWN':
grid = down(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif move == 'LEFT':
grid = left(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
elif move == 'RIGHT':
grid = right(grid, True)
spawn_tile(grid)
generate_tiles()
redraw_screen()
print(score)
# if __name__ == '__main__':
# main()
# pygame.quit()
main_ai()
pygame.quit()