Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4eb8d45

Browse files
committedJan 29, 2024
fixed some bugs
1 parent 2f40c6b commit 4eb8d45

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed
 

‎hanoi_tower.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,28 @@
55
from pyglet import shapes, clock
66
from pyglet.window import key
77

8-
class HanoiWondow(pyglet.window.Window):
8+
AUTO_PLAY_MOVE_TIME = 1 # in sec.
9+
10+
class HanoiWindow(pyglet.window.Window):
911

1012
def __init__(self):
1113
super().__init__(caption="Tower of Hanoi", resizable=True)
12-
self.reset_game(4)
14+
self.reset_game(2)
15+
clock.schedule(self.auto_play)
1316

1417
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)'''
1519
self.max_disk = max_disk
1620
self.position = [d for d in range(self.max_disk, -1, -1)], [], []
1721
self.plan = [(self.max_disk, 0, 1)]
1822
self.auto_play_time = None
19-
clock.schedule(self.auto_play)
2023
self.selected_rod = None
2124

2225
def auto_play(self, dt):
2326
'''Play optimal move each 1 second or do nothing if auto_play_time is None'''
2427
if self.auto_play_time is None: return
2528
self.auto_play_time += dt
26-
if self.auto_play_time > 1:
29+
if self.auto_play_time > AUTO_PLAY_MOVE_TIME:
2730
self.auto_play_time = 0
2831
self.make_optimal_move()
2932

@@ -55,6 +58,7 @@ def select(self, rod):
5558
if self.selected_rod is None:
5659
if self.position[rod]:
5760
self.selected_rod = rod
61+
self.auto_play_time = None
5862
else:
5963
if self.selected_rod == rod:
6064
self.selected_rod = None
@@ -89,10 +93,13 @@ def on_key_press(self, symbol, modifiers):
8993
if symbol == key._1: self.select(0)
9094
if symbol == key._2: self.select(1)
9195
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
93100
if symbol in (key.PLUS, key.NUM_ADD) and self.max_disk < 8: self.reset_game(self.max_disk+1)
94101
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
96103

97104
def on_mouse_press(self, x, y, button, modifiers):
98105
if y > self.height-60:
@@ -139,5 +146,5 @@ def on_draw(self):
139146
x=window.width//2, y=self.height-30,
140147
anchor_x='center', anchor_y='center').draw()
141148

142-
window = HanoiWondow()
149+
window = HanoiWindow()
143150
pyglet.app.run()

0 commit comments

Comments
 (0)
Please sign in to comment.