-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
136 lines (107 loc) · 2.93 KB
/
main.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
from random import randint
from msvcrt import getch
import move
from os import system as command
from platform import system as os
table = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
table_copy = []
score = 0
color_dict = {
2: (0, 41),
4: (0, 42),
8: (0, 43),
16: (0, 44),
32: (0, 45),
64: (0, 46),
128: (4, 41),
256: (4, 42),
512: (4, 43),
1024: (4, 44),
2048: (4, 45),
4096: (4, 46),
8192: (7, 41),
16384: (7, 42),
32768: (7, 43),
65536: (7, 44),
131072: (7, 45)
# This is the largest possible number in a 4*4 table
}
def add_new_2(arr):
for i in range(len(arr)):
if 0 in arr[i]:
row = randint(0, 3)
column = randint(0, 3)
while 0 not in arr[row]:
row = randint(0, 3)
while arr[row][column] != 0:
column = randint(0, 3)
arr[row][column] = 2
break
def game_over(arr):
for i in range(0, 4):
for j in range(0, 4):
if arr[i][j] == 0:
return False
for i in range(0, 4):
for j in range(1, 4):
if arr[i][j - 1] == arr[i][j]:
return False
for i in range(1, 4):
for j in range(0, 4):
if arr[i - 1][j] == arr[i][j]:
return False
return True
def user():
input_list = ['A', 'S', 'D', 'W', 'Q', 'a', 's', 'd', 'w', 'q']
user_input = str(getch())[2]
while user_input not in input_list:
print("\033[1;31;40mYou can only select 'A', 'S', 'D' or 'W': \nPress 'Q' to exit: ")
user_input = str(getch())[2]
return user_input.lower()
def copy(arr):
new_arr = []
for i in range(len(arr)):
temp = []
for j in range(len(arr)):
temp.append(arr[i][j])
new_arr.append(temp)
return new_arr
while not game_over(table):
if table != table_copy:
add_new_2(table)
if os() == "Windows":
command("cls")
else:
command("clear")
print("""\033[0;32;40m
Press 'A', 'S', 'D' or 'W' to move
Press 'Q' to exit
""")
print(f"\033[1;34;40mScore: {score}")
for i in table:
print("\033[0;37;40m\n--------------------------------")
for j in i:
if j:
print(f"\033[{color_dict[j][0]};37;{color_dict[j][1]}m{j}", "\033[0;37;40m\t", end="")
else:
print("", "\t", end="")
print("\033[1;35;40m\n================================\n")
# Making a copy of the table to know if it was changed in the next iteration
table_copy = copy(table)
match user():
case "a":
score += move.left(table)
case "s":
score += move.down(table)
case "d":
score += move.right(table)
case "w":
score += move.up(table)
case "q":
break
print(f"\033[0;33;40mGame over!\nScore: {score}")