-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_display.py
243 lines (208 loc) · 8.91 KB
/
game_display.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
"""
FILE: game_display.py
DESCRIPTION: a 'GameDisplay' class used for a 'snake' game. Runs the game loop.
"""
###############################################################################
# Imports #
###############################################################################
import sys
import threading
import time
import tkinter as tki
from typing import Any, Optional, List, Tuple, Dict
import argparse
from argparse import Namespace
import game_utils
###############################################################################
# Constants #
###############################################################################
CELL_SIZE = 15
ROUND_TIME = 150
WIDTH = 50
HEIGHT = 50
NUM_OF_APPLES = 3
NUM_OF_WALLS = 2
###############################################################################
# Class & Inner Functions #
###############################################################################
class GameDisplay:
"""
The main class for the 'Snake' game.
"""
def __init__(self, width: int, height: int, delay: int, verbose: int,
args: Namespace) -> None:
"""
Creates a new game display object and initializes it
"""
# placed this import in here to solve circular import issues.
self.width, self.height, self.delay, self.verbose = width, height, delay / 1000, verbose > 1
import snake_main
self._round_num = 0
self._root = tki.Tk()
self._root.title('Snake')
self._root.bind('<KeyPress>', self._key_press)
self._score_var = tki.StringVar()
self._init_score_frame()
self._canvas = tki.Canvas(
self._root, bg="white", width=self.width * CELL_SIZE,
height=self.height * CELL_SIZE)
self._canvas.pack()
self._to_draw: Dict[Tuple[int, int], str] = dict()
self._already_drawn: Dict[Tuple[int, int, str], int] = dict()
self._root.resizable(False, False)
self.key_click: Optional[str] = None
self._key_click_round: int = 0
self._game_control_thread = threading.Thread(
target=snake_main.main_loop, args=(self, args))
self._game_control_thread.daemon = True
self._round_start_time = time.time()
def _init_score_frame(self) -> None:
"""
Initializes the score frame
"""
self._score_frame = tki.Frame(self._root)
self._score_frame.pack(side=tki.TOP)
self.show_score("Not Set")
self._score_label = tki.Label(self._score_frame,
borderwidth=2,
relief="ridge",
textvariable=self._score_var,
font=("Courier", 22))
self._score_label.grid(row=0, column=0, sticky="w", padx=10, pady=10)
self._score_frame.grid_rowconfigure(0, weight=1)
def start(self) -> None:
"""
Starts the program: calls the main method and runs the GUI
"""
self._root.after(500, self._game_control_thread.start)
self._root.after(1000, self._check_end)
self._root.mainloop()
def _check_end(self) -> None:
"""
Checks if the game has finished
"""
if not self._game_control_thread.is_alive():
self._root.after(1000, self._root.destroy)
else:
self._root.after(300, self._check_end)
def _key_press(self, e: Any) -> None:
"""
Checks which key was clicked in the event
:param e: an event
"""
if e.keysym in ["Left", "Right", "Up", "Down"]:
self.key_click = e.keysym
self._key_click_round = self._round_num
def get_key_clicked(self) -> Optional[str]:
"""
Turns off the key clicked FLAG and returns which key is clicked
:return: None, or one of 'Left', 'Right', 'Up', 'Down'
"""
result = self.key_click
self.key_click = None
return result
def draw_cell(self, x: int, y: int, color: str) -> None:
"""
Sets the cell at the given coordinates to draw in given color
:param x: coordinate at x
:param y: coordinate at y
:param color: the color we wish to draw
"""
self._to_draw[x, y] = color
def _buffer_draw_cell(self, x: int, y: int, color: str) -> None:
"""
Draws the x,y cell in color
:param x: coordinate at x
:param y: coordinate at y
:param color: the color we wish to draw
"""
if x < 0 or x >= self.width or \
y < 0 or y >= self.height:
raise ValueError(
"cell index out of bounds of the board: " + str((x, y)))
# setting the coordinates of the board correctly,
# the y axis needs to point up.
# the following line adjusts this.
y = self.height - y
return self._canvas.create_rectangle(
x * CELL_SIZE, (y - 1) * CELL_SIZE, (x + 1) * CELL_SIZE,
y * CELL_SIZE,
fill=color, outline=color)
def _update_drawing(self) -> None:
"""
Updates the drawing
"""
if self.verbose:
print(self._to_draw)
to_draw = {(x, y, color) for (x, y), color in self._to_draw.items()}
for rect in self._already_drawn:
if rect not in to_draw:
self._canvas.delete(self._already_drawn[rect])
cur_drawn: Dict[Tuple[int, int, str], int] = dict()
for (x, y), color in self._to_draw.items():
ind = self._already_drawn.get((x, y, color), None)
if ind is None:
ind = self._buffer_draw_cell(x, y, color)
cur_drawn[(x, y, color)] = ind
self._already_drawn = cur_drawn
self._to_draw = dict()
def end_round(self) -> None:
"""
Ends the current round
"""
self._update_drawing()
self._round_start_time += self.delay
now = time.time()
while now < self._round_start_time:
time.sleep(self._round_start_time - now)
now = time.time()
self._round_num += 1
def show_score(self, val: Any) -> None:
"""
Updates the currently shown score on the board
:param val: the score we wish to display
"""
if self.verbose:
print(f'Score:{val}')
self._score_var.set("Score: " + str(val))
def parse_args(argv: List[str]) -> Namespace:
parser = argparse.ArgumentParser(
prog='game_display.py',
description='Runs the "Snake" game. '
'Closes the program automatically when disqualified.',
)
parser.add_argument('-x', '--width', type=int, default=WIDTH,
help='args.width: Game board width')
parser.add_argument('-y', '--height', type=int, default=HEIGHT,
help='args.height: Game board height')
parser.add_argument('-s', '--seed', default=None,
help='Seed for random number generator (not passed to game loop)')
parser.add_argument('-a', '--apples', type=int, default=NUM_OF_APPLES,
help='args.apples: Number of apples')
parser.add_argument('-d', '--debug',
action='store_true',
help='args.debug: Debug mode with no snake')
parser.add_argument('-w', '--walls', type=int, default=NUM_OF_WALLS,
help='args.walls: Number of walls')
parser.add_argument('-r', '--rounds', type=int, default=-1,
help='args.rounds: Number of rounds')
parser.add_argument('-t', '--delay', type=int, default=ROUND_TIME,
help='Delay between rounds in milliseconds (not passed to game loop)')
parser.add_argument('-v', '--verbose',
action='count', default=0,
help='Print helpful debugging information (not passed to game loop, can be used multiple times)')
return parser.parse_args(argv)
def setup_game(args: Namespace) -> GameDisplay:
game_utils.set_random_seed(args.__dict__.pop('seed'))
game_utils.set_verbose(args.verbose)
game_utils.set_size(width=args.width,
height=args.height)
return GameDisplay(width=args.width,
height=args.height,
delay=args.__dict__.pop('delay'),
verbose=args.__dict__.pop('verbose'),
args=args)
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
gd = setup_game(args)
gd.start()