-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoc_2048_gui.py
88 lines (75 loc) · 2.27 KB
/
poc_2048_gui.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
"""
2048 GUI
"""
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import math
# Tile Images
IMAGENAME = "assets_2048.png"
IMAGEURL = "http://codeskulptor-assets.commondatastorage.googleapis.com/assets_2048.png"
TILE_SIZE = 100
HALF_TILE_SIZE = TILE_SIZE / 2
BORDER_SIZE = 45
# Directions
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
class GUI:
"""
Class to run game GUI.
"""
def __init__(self, game):
self._rows = game.get_grid_height()
self._cols = game.get_grid_width()
self._game = game
url = IMAGEURL
self._tiles = simplegui.load_image(url)
self._directions = {"up": UP, "down": DOWN,
"left": LEFT, "right": RIGHT}
self._frame = simplegui.create_frame('2048',
self._cols * TILE_SIZE + 2 * BORDER_SIZE,
self._rows * TILE_SIZE + 2 * BORDER_SIZE)
self._frame.add_button('New Game', self.start)
self._frame.set_keydown_handler(self.keydown)
self._frame.set_draw_handler(self.draw)
self._frame.set_canvas_background("#BCADA1")
self._frame.start()
def keydown(self, key):
"""
Keydown handler
"""
for dirstr, dirval in self._directions.items():
if key == simplegui.KEY_MAP[dirstr]:
self._game.move(dirval)
break
def draw(self, canvas):
"""
Draw handler
"""
for row in range(self._rows):
for col in range(self._cols):
tile = self._game.get_tile(row, col)
if tile == 0:
val = 0
else:
val = int(math.log(tile, 2))
canvas.draw_image(self._tiles,
[HALF_TILE_SIZE + val * TILE_SIZE, HALF_TILE_SIZE],
[TILE_SIZE, TILE_SIZE],
[col * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE,
row * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE],
[TILE_SIZE, TILE_SIZE])
def start(self):
"""
Start the game.
"""
self._game.reset()
def run_gui(game):
"""
Instantiate and run the GUI.
"""
gui = GUI(game)
gui.start()