-
Notifications
You must be signed in to change notification settings - Fork 0
/
logics.py
136 lines (103 loc) · 2.81 KB
/
logics.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
import random
def pretty_print(mas):
print('-'*10)
for row in mas:
print(*row)
print('-' * 10)
def get_number_from_index(i, j):
return i*4+j+1
def get_index_from_number(num):
num -= 1
x, y = num // 4, num % 4
return x, y
def insert_2_or_4(mas, x, y):
if random.random() <= 0.75:
mas[x][y] = 2
else:
mas[x][y] = 4
return mas
def get_empty_list(mas):
empty = []
for i in range(4):
for j in range(4):
if mas[i][j] == 0:
num = get_number_from_index(i, j)
empty.append(num)
return empty
def is_zero_in_mas(mas):
for row in mas:
if 0 in row:
return True
return False
def move_left(mas):
delta = 0
for row in mas:
while 0 in row:
row.remove(0)
while len(row) != 4:
row.append(0)
for i in range(4):
for j in range(3):
if mas[i][j] == mas[i][j+1] and mas[i][j] != 0:
mas[i][j] *= 2
delta += mas[i][j]
mas[i].pop(j+1)
mas[i].append(0)
return mas, delta
def move_right(mas):
delta = 0
for row in mas:
while 0 in row:
row.remove(0)
while len(row) != 4:
row.insert(0, 0)
for i in range(4):
for j in range(3, 0, -1):
if mas[i][j] == mas[i][j-1] and mas[i][j] != 0:
mas[i][j] *= 2
delta += mas[i][j]
mas[i].pop(j-1)
mas[i].insert(0, 0)
return mas, delta
def move_up(mas):
delta = 0
for j in range(4):
column = []
for i in range(4):
if mas[i][j] != 0:
column.append(mas[i][j])
while len(column) != 4:
column.append(0)
for i in range(3):
if column[i] == column[i+1] and column[i] != 0:
column[i] *= 2
delta += mas[i][j]
column.pop(i+1)
column.append(0)
for i in range(4):
mas[i][j] = column[i]
return mas, delta
def move_down(mas):
delta = 0
for j in range(4):
column = []
for i in range(4):
if mas[i][j] != 0:
column.append(mas[i][j])
while len(column) != 4:
column.insert(0, 0)
for i in range(3, 0, -1):
if column[i] == column[i-1] and column[i] != 0:
column[i] *= 2
delta = mas[i][j]
column.pop(i-1)
column.insert(0, 0)
for i in range(4):
mas[i][j] = column[i]
return mas, delta
def can_move(mas):
for i in range(3):
for j in range(3):
if mas[i][j] == mas[i][j+1] or mas[i][j] == mas[i+1][j]:
return True
return False