|
5 | 5 | from pyglet import shapes, clock
|
6 | 6 | from pyglet.window import key
|
7 | 7 |
|
8 |
| -class HanoiWondow(pyglet.window.Window): |
| 8 | +AUTO_PLAY_MOVE_TIME = 1 # in sec. |
| 9 | + |
| 10 | +class HanoiWindow(pyglet.window.Window): |
9 | 11 |
|
10 | 12 | def __init__(self):
|
11 | 13 | super().__init__(caption="Tower of Hanoi", resizable=True)
|
12 |
| - self.reset_game(4) |
| 14 | + self.reset_game(2) |
| 15 | + clock.schedule(self.auto_play) |
13 | 16 |
|
14 | 17 | def reset_game(self, max_disk):
|
| 18 | + '''Set the game state to the initial position with the largest disk of the given size (counting from 0)''' |
15 | 19 | self.max_disk = max_disk
|
16 | 20 | self.position = [d for d in range(self.max_disk, -1, -1)], [], []
|
17 | 21 | self.plan = [(self.max_disk, 0, 1)]
|
18 | 22 | self.auto_play_time = None
|
19 |
| - clock.schedule(self.auto_play) |
20 | 23 | self.selected_rod = None
|
21 | 24 |
|
22 | 25 | def auto_play(self, dt):
|
23 | 26 | '''Play optimal move each 1 second or do nothing if auto_play_time is None'''
|
24 | 27 | if self.auto_play_time is None: return
|
25 | 28 | self.auto_play_time += dt
|
26 |
| - if self.auto_play_time > 1: |
| 29 | + if self.auto_play_time > AUTO_PLAY_MOVE_TIME: |
27 | 30 | self.auto_play_time = 0
|
28 | 31 | self.make_optimal_move()
|
29 | 32 |
|
@@ -55,6 +58,7 @@ def select(self, rod):
|
55 | 58 | if self.selected_rod is None:
|
56 | 59 | if self.position[rod]:
|
57 | 60 | self.selected_rod = rod
|
| 61 | + self.auto_play_time = None |
58 | 62 | else:
|
59 | 63 | if self.selected_rod == rod:
|
60 | 64 | self.selected_rod = None
|
@@ -89,10 +93,13 @@ def on_key_press(self, symbol, modifiers):
|
89 | 93 | if symbol == key._1: self.select(0)
|
90 | 94 | if symbol == key._2: self.select(1)
|
91 | 95 | if symbol == key._3: self.select(2)
|
92 |
| - if symbol in (key.ENTER, key.NUM_ENTER, key.SPACE): self.make_optimal_move() |
| 96 | + if symbol in (key.ENTER, key.NUM_ENTER): |
| 97 | + self.make_optimal_move() |
| 98 | + self.auto_play_time = None |
| 99 | + self.selected_rod = None |
93 | 100 | if symbol in (key.PLUS, key.NUM_ADD) and self.max_disk < 8: self.reset_game(self.max_disk+1)
|
94 | 101 | if symbol in (key.MINUS, key.NUM_SUBTRACT) and self.max_disk > 1: self.reset_game(self.max_disk-1)
|
95 |
| - if symbol == key.P: self.auto_play_time = 0 if self.auto_play_time is None else None |
| 102 | + if symbol in (key.P, key.SPACE): self.auto_play_time = AUTO_PLAY_MOVE_TIME if self.auto_play_time is None else None |
96 | 103 |
|
97 | 104 | def on_mouse_press(self, x, y, button, modifiers):
|
98 | 105 | if y > self.height-60:
|
@@ -139,5 +146,5 @@ def on_draw(self):
|
139 | 146 | x=window.width//2, y=self.height-30,
|
140 | 147 | anchor_x='center', anchor_y='center').draw()
|
141 | 148 |
|
142 |
| -window = HanoiWondow() |
| 149 | +window = HanoiWindow() |
143 | 150 | pyglet.app.run()
|
0 commit comments