-
Notifications
You must be signed in to change notification settings - Fork 43
/
2048_Game_CommandLine.py
103 lines (90 loc) · 2.41 KB
/
2048_Game_CommandLine.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
import random
def start_game():
mat = []
for i in range(4):
mat.append([0]*4)
return mat
def add_new_2(mat):
r=random.randint(0,3)
c=random.randint(0,3)
while mat[r][c]!=0:
r=random.randint(0,3)
c=random.randint(0,3)
mat[r][c]=2
def compress(mat):
new_mat=[]
for i in range(4):
new_mat.append([0]*4)
for i in range(4):
pos=0
for j in range(4):
if mat[i][j]!=0:
new_mat[i][pos]=mat[i][j]
pos=pos+1
return new_mat
def merge(mat):
for i in range(4):
for j in range(3):
if mat[i][j]==mat[i][j+1] and mat[i][j]!=0 :
mat[i][j]=mat[i][j]*2
mat[i][j+1]=0
return mat
def reverse(mat):
new_mat=[]
for i in range(4):
new_mat.append([])
for j in range(4):
new_mat[i].append(mat[i][4-j-1])
return new_mat
def transpose(mat):
new_mat=[]
for i in range(4):
new_mat.append([])
for j in range(4):
new_mat[i].append(mat[j][i])
return new_mat
def move_up(grid):
transposed_grid=transpose(grid)
new_grid=compress(transposed_grid)
new_grid=merge(new_grid)
new_grid=compress(new_grid)
final_new_grid=transpose(new_grid)
return final_new_grid
def move_down(grid):
transposed_grid=transpose(grid)
reversed_grid=reverse(transposed_grid)
new_grid=compress(reversed_grid)
new_grid=merge(new_grid)
new_grid=compress(new_grid)
final_reversed_grid=reverse(new_grid)
final_new_grid=transpose(final_reversed_grid)
return final_new_grid
def move_right(grid):
reversed_grid=reverse(grid)
new_grid=compress(reversed_grid)
new_grid=merge(new_grid)
new_grid=compress(new_grid)
final_new_grid=reverse(new_grid)
return final_new_grid
def move_left(grid):
new_grid=compress(grid)
new_grid=merge(new_grid)
new_grid=compress(new_grid)
return new_grid
mat = start_game()
mat[1][3] = 2
mat[2][2] = 2
mat[3][0] = 4
mat[3][1] = 8
mat[2][1] = 4
inputs = [int(ele) for ele in input().split()]
for ele in inputs:
if ele == 1:
mat = move_up(mat)
elif ele == 2:
mat = move_down(mat)
elif ele == 3:
mat = move_left(mat)
else:
mat = move_right(mat)
print(mat)