forked from varda-s/git-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hog_gui.py
376 lines (317 loc) · 11.5 KB
/
hog_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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""A graphical user interface (GUI) for the game of Hog.
This file uses many features of Python not yet covered in the course. A lab
later in the semester will review its implementation and let you extend it.
"""
import hog
import dice
from ucb import main
import tkinter as tk
from tkinter import *
import argparse
#############
# Utilities #
#############
class BetterWidget(object):
"""A BetterWidget returns itself on pack and config for call chaining."""
def pack(self, **kwargs):
super().pack(**kwargs)
return self
def config(self, **kwargs):
super().config(**kwargs)
return self
class TextWidget(BetterWidget):
"""A TextWidget contains a mutable line of text."""
def __init__(self, **kwargs):
self.textvar = kwargs.get('textvariable', tk.StringVar())
self.config(textvariable=self.textvar)
if 'text' in kwargs:
self.textvar.set(kwargs['text'])
@property
def text(self):
return self.textvar.get()
@text.setter
def text(self, value):
return self.textvar.set(str(value))
class Label(TextWidget, tk.Label):
"""A Label is a text label."""
def __init__(self, parent, **kwargs):
kwargs.update(label_theme)
tk.Label.__init__(self, parent, **kwargs)
TextWidget.__init__(self, **kwargs)
class Button(BetterWidget, tk.Button):
"""A Button is an interactive button."""
def __init__(self, *args, **kwargs):
kwargs.update(button_theme)
tk.Button.__init__(self, *args, **kwargs)
class Entry(TextWidget, tk.Entry):
"""An Entry widget accepts text entry."""
def __init__(self, parent, **kwargs):
kwargs.update(entry_theme)
tk.Entry.__init__(self, parent, **kwargs)
TextWidget.__init__(self, **kwargs)
class Frame(BetterWidget, tk.Frame):
"""A Frame contains other widgets."""
def __init__(self, *args, **kwargs):
kwargs.update(frame_theme)
tk.Frame.__init__(self, *args, **kwargs)
def name(who):
"""Return the name of a player."""
return "Player {0}".format(who)
#######
# GUI #
#######
class HogGUIException(BaseException):
"""HogGUI-specific Exception. Used to exit a game prematurely."""
pass
class HogGUI(Frame):
"""Tkinter GUI for Hog."""
KILL = -9 # kill signal to stop a game
#########################
# Widget Initialization #
#########################
def __init__(self, parent, computer=False):
"""Replace hog module's dice with hooks to GUI and start a game.
parent -- parent widget (should be root)
computer -- True if playing against a computer
"""
super().__init__(parent)
self.pack(fill=BOTH)
self.parent = parent
self.who = 0
self.init_scores()
self.init_rolls()
self.init_dice()
self.init_status()
self.init_restart()
hog.six_sided = self.make_dice(6)
hog.four_sided = self.make_dice(4)
self.computer, self.turn = computer, 0
self.play()
def init_scores(self):
"""Creates child widgets associated with scoring.
Each player has a score Label that is updated each turn. Scores can be
accessed and modified through Tkinter variables in self.score_vars.
"""
self.score_frame = Frame(self).pack()
self.p_frames = [None, None]
self.p_labels = [None, None]
self.s_labels = [None, None]
for i in (0, 1):
self.p_frames[i] = Frame(self.score_frame, padx=25).pack(side=LEFT)
self.p_labels[i] = Label(self.p_frames[i],
text=name(i) + ':').pack()
self.s_labels[i] = Label(self.p_frames[i]).pack()
def init_rolls(self):
"""Creates child widgets associated with the number of rolls.
The primary widget is an Entry that accepts user input. An intermediate
Tkinter variable, self.roll_verified, is set to the final number of
rolls. Once it is updated, the player immediately takes a turn based on
its value.
"""
self.roll_frame = Frame(self).pack()
self.roll_label = Label(self.roll_frame).pack()
self.roll_entry = Entry(self.roll_frame,
justify=CENTER).pack()
self.roll_entry.bind('<Return>',
lambda event: self.roll_button.invoke())
self.roll_verified = IntVar()
self.roll_button = Button(self.roll_frame,
text='Roll!',
command=self.roll).pack()
def init_dice(self):
"""Creates child widgets associated with dice. Each dice is stored in a
Label. Dice Labels will be packed or unpacked depending on how many dice
are rolled.
"""
self.dice_frames = [
Frame(self).pack(),
Frame(self).pack(),
Frame(self).pack(),
Frame(self).pack()
]
self.dice = {
i: Label(self.dice_frames[i//5]).
config(image=HogGUI.IMAGES[6]).
pack(side=LEFT)
for i in range(20)
}
def init_status(self):
"""Creates child widgets associated with the game status. For example,
Hog Wild is displayed here."""
self.status_label = Label(self).pack()
def init_restart(self):
"""Creates child widgets associated with restarting the game."""
self.restart_button = Button(self, text='Restart',
command=self.restart).pack()
##############
# Game Logic #
##############
def make_dice(self, sides):
"""Creates a dice function that hooks to the GUI and wraps
dice.make_fair_dice.
sides -- number of sides for the die
"""
fair_dice = dice.make_fair_dice(sides)
def gui_dice():
"""Roll fair_dice and add a corresponding image to self.dice."""
result = fair_dice()
img = HogGUI.IMAGES[result]
self.dice[self.dice_count].config(image=img).pack(side=LEFT)
self.dice_count += 1
return result
return gui_dice
def clear_dice(self):
"""Unpacks (hides) all dice Labels."""
for i in range(20):
self.dice[i].pack_forget()
def roll(self):
"""Verify and set the number of rolls based on user input. As
per game rules, a valid number of rolls must be an integer
greater than or equal to -1.
"""
result = self.roll_entry.text
try:
rolls = 10 >= int(result) >= -1
assert rolls, 'Rolls must be between -1 and 10, inclusive'
self.roll_verified.set(int(result))
except (ValueError, AssertionError) as e:
print(e)
def switch(self, who=None):
"""Switches players. self.who is either 0 or 1."""
self.p_frames[self.who].config(bg=bg)
self.p_labels[self.who].config(bg=bg)
self.s_labels[self.who].config(bg=bg)
self.who = 1 - self.who if who is None else who
self.p_frames[self.who].config(bg=select_bg)
self.p_labels[self.who].config(bg=select_bg)
self.s_labels[self.who].config(bg=select_bg)
def strategy(self, score, opp_score):
"""A strategy with a hook to the GUI. This strategy gets
passed into the PLAY function from the HOG module. At its
core, the strategy waits until a number of rolls has been
verified, then returns that number. Game information is
updated as well.
score -- player's score
opp_score -- opponent's score
"""
s0 = score if self.who == 0 else opp_score
s1 = opp_score if self.who == 0 else score
self.s_labels[0].text = s0
self.s_labels[1].text = s1
self.roll_label.text = name(self.who) +' will roll:'
status = self.status_label.text
self.status_label.text = status
if self.computer and self.who == self.turn:
self.update()
self.after(DELAY)
result = hog.final_strategy(score, opp_score)
else:
self.roll_entry.focus_set()
self.wait_variable(self.roll_verified)
result = self.roll_verified.get()
self.roll_entry.text = ''
if result == HogGUI.KILL:
raise HogGUIException
self.clear_dice()
self.dice_count = 0
self.status_label.text = '{} chose to roll {}.'.format(name(self.who),
result)
self.switch()
return result
def play(self):
"""Simulates a game of Hog by calling hog.play with the GUI strategies.
If the player destroys the window prematurely (i.e. in the
middle of a game), a HogGUIException is raised to exit out
of play's loop. Otherwise, the widget will be destroyed,
but the strategy will continue waiting.
"""
self.turn = 1 - self.turn
self.switch(0)
self.s_labels[0].text = '0'
self.s_labels[1].text = '0'
self.status_label.text = ''
try:
score, opponent_score = hog.play(self.strategy,
self.strategy)
except HogGUIException:
pass
else:
self.s_labels[0].text = score
self.s_labels[1].text = opponent_score
winner = 0 if score > opponent_score else 1
self.status_label.text = 'Game over! {} wins!'.format(
name(winner))
def restart(self):
"""Kills the current game and begins another game."""
self.roll_verified.set(HogGUI.KILL)
self.status_label.text = ''
self.clear_dice()
self.play()
def destroy(self):
"""Overrides the destroy method to end the current game."""
self.roll_verified.set(HogGUI.KILL)
super().destroy()
def run_GUI(computer=False):
"""Start the GUI.
computer -- True if playing against computer
"""
root = Tk()
root.title('The Game of Hog')
root.minsize(520, 400)
root.geometry("520x600")
# Tkinter only works with GIFs
HogGUI.IMAGES = {
1: PhotoImage(file='images/die1.gif'),
2: PhotoImage(file='images/die2.gif'),
3: PhotoImage(file='images/die3.gif'),
4: PhotoImage(file='images/die4.gif'),
5: PhotoImage(file='images/die5.gif'),
6: PhotoImage(file='images/die6.gif'),
}
app = HogGUI(root, computer)
root.mainloop()
##########
# THEMES #
##########
select_bg = '#a6d785'
bg='#ffffff'
fg='#000000'
font=('Arial', 14)
frame_theme = {
'bg': bg,
}
label_theme = {
'font': font,
'bg': bg,
'fg': fg,
}
button_theme = {
'font': font,
'activebackground': select_bg,
'bg': bg,
'fg': fg,
}
entry_theme = {
'fg': fg,
'bg': bg,
'font': font,
'insertbackground': fg,
}
##########################
# Command Line Interface #
##########################
DELAY=2000
@main
def run(*args):
parser = argparse.ArgumentParser(description='Hog GUI')
parser.add_argument('-f', '--final',
help='play against the final strategy in hog.py. '
'Computer alternates playing as player 0 and 1.',
action='store_true')
parser.add_argument('-d', '--delay',
help='time delay for computer, in seconds', type=int,
default=2)
args = parser.parse_args()
global DELAY
DELAY = args.delay * 1000
run_GUI(computer=args.final)