-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path2048.py
545 lines (418 loc) · 18.8 KB
/
2048.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#Importing required modules
import pygame
import random
#Initializing pygame modules
pygame.init()
#Initializing font module
pygame.font.init()
#Creating fonts
myfont = pygame.font.SysFont('Comic Sans MS', 50)
myfont_win=pygame.font.SysFont('Times New Roman', 80)
#Defining RGB values for colours
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
GOLD=( 230, 215, 0)
screen = pygame.display.set_mode((800,600)) #Initialzing a screen for display
pygame.display.set_caption('2048')
clock = pygame.time.Clock()
#Lists to store game matrices
A=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
A1=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
#Initializing variables
points=0
uscore=0
c=0
try:
a=open("highscore.txt","r")#Opening file
x=a.readlines()#Reading file
hscore=int(x[0])#Storing high score
a.close()#Closing file
except:
hscore=0
#Initialzing variables
w=x=y=z=1
#To set initial state of game matrix and score.
def initial():
#Initializing variables
a=[2,2,2,4]
global points,hscore,uscore
uscore=0
points=0
#Choosing elements from list a at random
m=random.choice(a)
n=random.choice(a)
x=[0,1,2,3]
y=[0,1,2,3]
#Choosing elements from lists x and y at random
#To be used as coordinates
inx1=random.choice(x)
iny1=random.choice(y)
inx2=random.choice(x)
iny2=random.choice(y)
while inx1==inx2 and iny1==iny2:
#Ensuring no two x and y coordinates are the same
inx1=random.choice(x)
inx2=random.choice(x)
iny1=random.choice(y)
iny2=random.choice(y)
#Setting initial elements of matrix at random
A[inx1][iny1]=m
A[inx2][iny2]=n
#To draw the game matrix, scores and required buttons
def draw():
mouse=pygame.mouse.get_pos()#To get the mouse cursor position
click=pygame.mouse.get_pressed()#To get the state of the mouse buttons
#Drawing the game matrix
for i in range (0,5):
pygame.draw.line(screen, BLUE, (200,100*(i+1) ), (600, 100*(i+1)))
pygame.draw.line(screen, BLUE, (200+100*i,100 ), (200+100*i,500 ))
#Displaying the name of game, 'Score' and 'High Score'
textsurface = myfont.render('2048', False, WHITE)
screen.blit(textsurface,(50,50))
textsurface = myfont.render('Score', False, GREEN)
screen.blit(textsurface,(660,50))
textsurface = myfont.render('HighScore', False, RED)
screen.blit(textsurface,(630,150))
if mouse[0]<175 and mouse[0]>50 and mouse[1]<250 and mouse[1]>200:#If mouse hovers over button
pygame.draw.rect(screen, GREEN,(50,200,125,50))#Change button colour to green
if click[0]==1: #If button is clicked
reset() # Reset the matrix by calling reset() function
else:#Display colour of button as red
pygame.draw.rect(screen,RED,(50,200,125,50))
#Display 'RESET' on the button
textsurface = myfont.render('RESET', False, WHITE)
screen.blit(textsurface,(55,210))
if mouse[0]<175 and mouse[0]>50 and mouse[1]<350 and mouse[1]>300:#If mouse hovers over button
pygame.draw.rect(screen, GREEN,(50,300,125,50)) #Change button colour to green
if click[0]==1:#If button is clicked
undo() #Undo the prevoius move by calling undo() function
else:#Display colour of button as blue.
pygame.draw.rect(screen,BLUE,(50,300,125,50))
#Display 'UNDO' on the button
textsurface = myfont.render('UNDO', False, WHITE)
screen.blit(textsurface,(60,310))
global hscore,points
for i in range (0,4):
for j in range (0,4):
if not A[i][j] == 0:
if A[i][j]<1000:
textsurface = myfont.render(str(A[i][j]), False, WHITE)
screen.blit(textsurface,((j*100)+200+35,(i+1)*100+35))
else:
textsurface = myfont.render(str(A[i][j]), False, WHITE)
screen.blit(textsurface,((j*100)+200+15,(i+1)*100+35))
#Displaying score
textsurface = myfont.render(str(points), False, WHITE)
screen.blit(textsurface,(680,100))
#Displaying high score
textsurface = myfont.render(str(hscore), False, WHITE)
screen.blit(textsurface,(680,200))
a=open("highscore.txt","w")#Opening file
a.writelines(str(hscore))#Writing high score to file
a.close()#Closing file
#Initialzing variable
m=n=o=0
#If two adjacent horizontal elements are equal
for i in range(0,4):
for j in range(0,3):
if A[i][j]==A[i][j+1]:
m=1
#If two adjacent vertical elements are equal
for i in range(0,4):
for j in range(0,3):
if A[j][i]==A[j+1][i]:
n=1
#If game matrix is empty (game has just started)
for i in range(0,4):
for j in range(0,4):
if A[i][j]==0:
o=1
if m==0 and n==0 and o==0:#If no adjacent elements are equal nor has game just started
#That is, there are no further moves
#Display "Game Over!!!' on screen
textsurface = myfont.render("Game Over !!!", False, RED)
screen.blit(textsurface,(300,50))
#To undo the previous move
def undo():
global A,points,uscore
points=uscore #Restoring the score to the prevoius score
A=[[i for i in x] for x in A1] #Restoring game matrix to its state one move prior
#To move elements of game matrix right when right arrow is clicked
def right():
#Initialzing variables
global w,points,hscore,uscore
w=0
uscore=points
for i in range (0,4):
for j in range (0,4):
if A[i][j] != 0:#If element is non-zero
for k in range(j+1,4):
if A[i][k] == 0:#If there is empty space right of non-zero element
w=1
break
else:
try:#If horizonatally adjacent elements are equal
if A[i][j] == A[i][j+1]:
w=1
break
except:
w=0
if w==1: #If horizonatally adjacent elements are equal/there is empty space to the right
global A1
A1=[[i for i in x] for x in A] #Storing current game matrix in another list
for r in range(0,4):
for c in range(0,3):
if(A[r][c]!=0 and A[r][c+1]==0):#If there empty space to the right of a non-zero element
A[r][c+1]=A[r][c]#Shifting element rightward
A[r][c]=0 #Creating empty space at previous position of element
for i in reversed(range(1,c+1)):#Shift if tere empty spaces
A[r][i]=A[r][i-1]
A[r][i-1]=0
for c in reversed(range(1,4)):
if(A[r][c]!=0 and A[r][c]==A[r][c-1]):#If element is non-zero and adjacent elements are equal
A[r][c]=A[r][c]*2 #Adding them
points=points+A[r][c]#Increase the score as required
A[r][c-1]=0 #Changing leftward element to zero
for k in reversed(range(0,c)):
for i in reversed(range(1,k+1)):
if A[r][i]==0:#If there is a zero element
A[r][i]=A[r][i-1]#Shifting it
A[r][i-1]=0
if hscore<points:#If score exceeds high score
hscore=points
add()#Add new element by calling add() function
#To move elements of game matrix left when left arrow is clicked
def left():
#Initialzing variables
global x,points,hscore,uscore
x=0
uscore=points
for i in range (0,4):
for j in range (0,4):
if A[i][j] != 0:#If element is non-zero
for k in range(0,j):
if A[i][k] == 0:#If there is empty space left of non-zero element
x=1
break
else:
try:#If horizonatally adjacent elements are equal
if A[i][j] == A[i][j-1]:
x=1
break
except:
x=0
if x==1:#If horizonatally adjacent elements are equal/there is empty space to the left
global A1
A1=[[i for i in x] for x in A]#Storing current game matrix in another list
for r in range(0,4):
for c in reversed(range(1,4)):
if(A[r][c]!=0 and A[r][c-1]==0):#If there empty space to the left of a non-zero element
A[r][c-1]=A[r][c]#Shifting element leftward
A[r][c]=0 #Creating empty space at previous position of element
for i in range(c,3):#Shift if tere empty space
A[r][i]=A[r][i+1]
A[r][i+1]=0
for c in range(0,3):
if(A[r][c]!=0 and A[r][c]==A[r][c+1]):#If element is non-zero and adjacent elements are equal
A[r][c]=A[r][c]*2#Adding them
points=points+A[r][c]#Increase the score as required
A[r][c+1]=0#Changing rightward element to zero
for k in range(c+1,4):
for i in range(k,3):
if A[r][i]==0:#If there is a zero element
A[r][i]=A[r][i+1]#Shifting it
A[r][i+1]=0
if hscore<points:#If score exceeds high score
hscore=points
add()#Add new element by calling add() function
#To move elements of game matrix up when up arrow is clicked
def up():
#Initialzing variables
global y,points,hscore,uscore
y=0
uscore=points
for i in range (0,4):
for j in range (0,4):
if A[j][i] != 0:#If element is non-zero
for k in range(0,j):
if A[k][i] == 0:#If there is empty space above non-zero element
y=1
break
else:
try:
if A[j][i] == A[j-1][i]:#If vertically adjacent elements are equal
y=1
break
except:
y=0
if y==1:#If vertically adjacent elements are equal/there is empty space above
global A1
A1=[[i for i in x] for x in A]#Storing current game matrix in another list
for c in range(0,4):
for r in reversed(range(1,4)):
if(A[r][c]!=0 and A[r-1][c]==0):#If there empty space above of a non-zero element
A[r-1][c]=A[r][c]#Shifting element upward
A[r][c]=0 #Creating empty space at previous position of element
for i in range(r,3):#Shift if tere empty space
A[i][c]=A[i+1][c]
A[i+1][c]=0
for r in range(0,3):
if(A[r][c]!=0 and A[r][c]==A[r+1][c]):#If element is non-zero and adjacent elements are equal
A[r][c]=A[r][c]*2#Adding them
A[r+1][c]=0 #Change downward element to zero
points=points+A[r][c]#Increase the score as required
for k in range(r+1,4):
for i in range(k,3):
if A[i][c]==0:#If there is a zero element
A[i][c]=A[i+1][c]#Shifting it
A[i+1][c]=0
if hscore<points:#If score exceeds high score
hscore=points
add()#Add new element by calling add() function
#To move elements of game matrix down when down arrow is clicked
def down():
#Initialzing variables
global z,points,hscore,uscore
z=0
uscore=points
for i in range (0,4):
for j in range (0,4):
if A[j][i] != 0:#If element is non-zero
for k in range(j+1,4):
if A[k][i] == 0:#If there is empty space below non-zero element
z=1
break
else:
try:
if A[j][i] == A[j+1][i]:#If vertically adjacent elements are equal
z=1
break
except:
z=0
if z==1:#If vertically adjacent elements are equal/there is empty space above
global A1
A1=[[i for i in x] for x in A]#Storing current game matrix in another list
for c in range(0,4):
for r in range(0,3):
if(A[r][c]!=0 and A[r+1][c]==0):#If there empty space below a non-zero element
A[r+1][c]=A[r][c]#Shifting element downward
A[r][c]=0 #Creating empty space at previous position of element
for i in reversed(range(1,r+1)):#Shift if tere empty space
A[i][c]=A[i-1][c]
A[i-1][c]=0
for r in reversed(range(1,4)):
if(A[r][c]!=0 and A[r-1][c]==A[r][c]):#If element is non-zero and adjacent elements are equal
A[r][c]=A[r][c]*2#Adding them
A[r-1][c]=0#Change upward element to zero
points=points+A[r][c]#Increase the score as required
for k in reversed(range(0,r)):
for i in reversed(range(1,k+1)):
if A[i][c]==0:#If there is a zero element
A[i][c]=A[i-1][c]#Shifting it
A[i-1][c]=0
if hscore<points:#If score exceeds high score
hscore=points
add()#Add new element by calling add() function
#To add element to game matrix
def add():
a=[2,2,2,4]
m=random.choice(a)#Choosing element from list a at random
while 1:#Inerting element at ranom
i=int(random.uniform(0,4))
j=int(random.uniform(0,4))
if(A[i][j]==0):#As long as space in matrix is empty
A[i][j]=m
break
#To reset the game matrix to initial state
def reset():
#Setting all game matrix elements back to zero
for i in range (0,4):
for j in range (0,4):
A[i][j]=0
initial()#Calling initial() function to restart the game
#To display a welcome message at the start of the game
def welcome_message():
global quit, d
mouse=pygame.mouse.get_pos()#To get the mouse cursor position
click=pygame.mouse.get_pressed()#To get the state of the mouse buttons
#Fill the screen black
screen.fill(BLACK)
#Display '2048'
textsurface=myfont_win.render('2048', False, GOLD)
screen.blit(textsurface, (300, 200))
if mouse[0]<450 and mouse[0]>330 and mouse[1]<450 and mouse[1]>400:#If mouse hovers over button
pygame.draw.rect(screen, GREEN,(310,400,130,50))#Change button colour to green
if click[0]==1:#If button is clicked
d+=1
draw() #Draw the game matrix, thereby startng the game
else:#Display colour of button as blue
pygame.draw.rect(screen,BLUE,(310,400,130,50))
#Display 'PLAY' on the button
textsurface = myfont.render('PLAY', False, WHITE)
screen.blit(textsurface,(330,410))
#To display a victory message when 2048 is achieved
def win_message():
global quit, c
mouse=pygame.mouse.get_pos()#To get the mouse cursor position
click=pygame.mouse.get_pressed()#To get the state of the mouse buttons
#Fill the screen to black
screen.fill(BLACK)
#Display 'You won!' on screen
textsurface=myfont_win.render('You Won!', False, GOLD)
screen.blit(textsurface, (250, 200))
if mouse[0]<375 and mouse[0]>200 and mouse[1]<450 and mouse[1]>400:#If mouse hovers over button
pygame.draw.rect(screen, GREEN,(200, 400,125,50))#Change button colour to green
if click[0]==1:#If button is clicked
quit=True #Change quit to true, thereby quitting the game
else:#Display colour of button as red
pygame.draw.rect(screen,RED,(200,400,125,50))
#Display 'QUIT' on the button
textsurface = myfont.render('QUIT', False, WHITE)
screen.blit(textsurface,(220,410))
if mouse[0]<650 and mouse[0]>430 and mouse[1]<450 and mouse[1]>400:#If mouse hovers over button
pygame.draw.rect(screen, GREEN,(410,400,220,50))#Change button colour to green
if click[0]==1:#If button is clicked
c=1
draw()#Draw the game matrix, therby continuing the game
else:#Display colour of button as blue
pygame.draw.rect(screen,BLUE,(410,400,220,50))
#Display 'CONTINUE' on the button
textsurface = myfont.render('CONTINUE', False, WHITE)
screen.blit(textsurface,(430,410))
initial() #Calling initial() function, thereby beginning the game
welcome_message() #Dispaying welcome message
quit = False #Initialzing variable
d=0
while not quit: #While game is running
global c,d
screen.fill((50, 50, 50)) #Fill screen to grey
for event in pygame.event.get():
if event.type == pygame.QUIT:#If user quits game
quit = True
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_RIGHT:#If user presses right arrow key
right()
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:#If user presses left arrow key
left()
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_UP:#If user presses up arrow key
up()
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_DOWN:#If user presses down arrow key
down()
if d==0:#If game has just begun
welcome_message()#Display welcome message
if d>0:#If game has already begun
draw()#Draw game matrix
#If user achieves 2048
if c==0:
for i in range(0,4):
for j in range(0,4):
if A[i][j]==2048: #Checking if any element in game matrix is equal to 2048
win_message()#Displaying victory message by calling win_message() function
pygame.display.update() #Update portions of the screen for software displays
pygame.quit() #Uninitialize all pygame modules