-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtk_2048.py
257 lines (232 loc) · 8.34 KB
/
tk_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
#!/usr/bin/env python3
"""2048 game using tkinter"""
from dataclasses import dataclass
from enum import Enum
from functools import cache
from random import choice, choices
from tkinter import Event, Misc, StringVar, Tk, messagebox, ttk
class Direction(Enum):
"""Enum to store which movement key was most recently pressed"""
DOWN = "down"
UP = "up"
LEFT = "left"
RIGHT = "right"
NONE = ""
@dataclass
class RangeData:
"""Hold data based on given directions"""
i_range: range
j_range: range
class Game:
"""2048 game"""
_BOARD_SIZE = 4
_COLORS = {
"": "#ffffff",
"2": "#eee4da",
"4": "#ede0c8",
"8": "#f2b179",
"16": "#f59563",
"32": "#f67c5f",
"64": "#f65e3b",
"128": "#edcf72",
"256": "#edcc61",
"512": "#edc850",
"1024": "#edc53f",
"2048": "#edc22e",
}
_FG_COLOR = "#000000"
def _merge(self, direction: Direction) -> None:
i_addend = int(direction == Direction.DOWN) - int(direction == Direction.UP)
j_addend = int(direction == Direction.RIGHT) - int(direction == Direction.LEFT)
range_data = {
Direction.UP: RangeData(
range(1, self._BOARD_SIZE),
range(self._BOARD_SIZE),
),
Direction.DOWN: RangeData(
range(self._BOARD_SIZE - 2, -1, -1),
range(self._BOARD_SIZE),
),
Direction.LEFT: RangeData(
range(self._BOARD_SIZE),
range(1, self._BOARD_SIZE),
),
Direction.RIGHT: RangeData(
range(self._BOARD_SIZE),
range(self._BOARD_SIZE - 2, -1, -1),
),
}[direction]
for i in range_data.i_range:
for j in range_data.j_range:
if (
self._board[i][j].get() != ""
and self._board[i + i_addend][j + j_addend].get() != ""
and self._board[i][j].get()
== self._board[i + i_addend][j + j_addend].get()
):
self._board[i][j].set(str(int(self._board[i][j].get()) * 2))
self._board[i + i_addend][j + j_addend].set("")
def _is_same_as_neighbor(self, row: int, col: int) -> bool:
item = self._board[row][col].get()
return (
(row > 0 and item == self._board[row - 1][col].get())
or (row < self._BOARD_SIZE - 1 and item == self._board[row + 1][col].get())
or (col > 0 and item == self._board[row][col - 1].get())
or (col < self._BOARD_SIZE - 1 and item == self._board[row][col + 1].get())
)
def _check_win(self) -> str:
game_over = True
for i in range(self._BOARD_SIZE):
for j in range(self._BOARD_SIZE):
if self._board[i][j].get() == "2048":
return "You win!"
if self._board[i][j].get() == "" or self._is_same_as_neighbor(i, j):
game_over = False
if game_over:
return "You lose!"
return "continue"
@cache
@staticmethod
def _replace_nones(potential_none: int | None, index: int) -> int:
"""If `potential_none` is None, return `index`, otherwise `potential_none`"""
if potential_none is None:
return index
return potential_none
@cache
@staticmethod
def _get_swappable_coordinates(
direction: Direction, swap_pair: tuple[int, int]
) -> tuple[int | None, int | None, int | None, int | None]:
"""
Return a 4-tuple of (current row, current column, check row, check column),
where `current` refers to the location of an element and `check` refers to
a potentially empty element to swap it with
"""
if direction in (Direction.LEFT, Direction.RIGHT):
return (
None,
swap_pair[direction == Direction.LEFT],
None,
swap_pair[direction == Direction.RIGHT],
)
return (
swap_pair[direction == Direction.UP],
None,
swap_pair[direction == Direction.DOWN],
None,
)
def _compress(self, direction: Direction) -> None:
for line in range(self._BOARD_SIZE):
for swap in (
(1, 2),
(0, 1),
(2, 3),
(1, 2),
(0, 1),
):
current_row, current_col, check_row, check_col = (
Game._get_swappable_coordinates(direction, swap)
)
current_elem = self._board[Game._replace_nones(current_row, line)][
Game._replace_nones(current_col, line)
]
check_elem = self._board[Game._replace_nones(check_row, line)][
Game._replace_nones(check_col, line)
]
if current_elem.get() != "" and check_elem.get() == "":
check_elem.set(current_elem.get())
current_elem.set("")
def _reset_board(self) -> None:
for i in range(self._BOARD_SIZE):
for j in range(self._BOARD_SIZE):
self._board[i][j].set("")
self._spawn_random()
self._spawn_random()
self._color_board()
def _move(self, key: Event[Misc]) -> None:
key_symbol = key.keysym
direction = Direction.NONE
if key_symbol in ("Up", "w"):
direction = Direction.UP
elif key_symbol in ("Down", "s"):
direction = Direction.DOWN
elif key_symbol in ("Left", "a"):
direction = Direction.LEFT
elif key_symbol in ("Right", "d"):
direction = Direction.RIGHT
if direction == Direction.NONE:
return
self._compress(direction)
self._merge(direction)
self._compress(direction)
self._spawn_random()
self._color_board()
message = self._check_win()
if message == "continue":
return
if messagebox.askyesno(title=message, message="Do you want to play again?"):
self._reset_board()
return
self._root.destroy()
def _init_tk(self) -> None:
self._root.title("2048")
self._root.bind("<Up>", self._move)
self._root.bind("<Down>", self._move)
self._root.bind("<Left>", self._move)
self._root.bind("<Right>", self._move)
self._root.bind("w", self._move)
self._root.bind("s", self._move)
self._root.bind("a", self._move)
self._root.bind("d", self._move)
self._root.bind("q", lambda _: self._root.destroy())
ttk.Style().configure(
"TLabel",
font=("Helvetica", 64),
width=3,
height=3,
borderwidth=1,
relief="ridge",
)
def __init__(self) -> None:
self._root = Tk()
self._init_tk()
self._board: list[list[StringVar]] = []
for i in range(self._BOARD_SIZE):
self._board.append([])
for j in range(self._BOARD_SIZE):
self._board[i].append(StringVar(self._root))
ttk.Label(
self._root,
textvariable=self._board[i][j],
padding=5,
style=f"{i}{j}.TLabel",
).grid(
row=i,
column=j,
)
def _spawn_random(self) -> None:
number = choices("24", (0.9, 0.1))[0]
empty_cells = [
(i, j)
for i in range(self._BOARD_SIZE)
for j in range(self._BOARD_SIZE)
if self._board[i][j].get() == ""
]
if len(empty_cells) == 0:
return
cell = choice(empty_cells)
self._board[cell[0]][cell[1]].set(number)
def _color_board(self) -> None:
for i in range(self._BOARD_SIZE):
for j in range(self._BOARD_SIZE):
ttk.Style().configure(
f"{i}{j}.TLabel",
background=self._COLORS[self._board[i][j].get()],
foreground=self._FG_COLOR,
)
def run(self) -> None:
"""Start 2048 game"""
self._reset_board()
self._root.mainloop()
if __name__ == "__main__":
Game().run()