-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_path_visualizer.py
More file actions
397 lines (320 loc) · 14.4 KB
/
run_path_visualizer.py
File metadata and controls
397 lines (320 loc) · 14.4 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import os
from time import perf_counter_ns
from typing import Optional
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "True"
import pygame
from bot.bot_action import BotAction
from bot.pathfinder import Pathfinder
from client.gui import GUI
from client.input_handler import InputHandler
from client.keymap import PYGAME_KEYMAP
from core.action import Action
from core.board import Board
from core.game_state import GameState
from core.piece import Piece
from core.piece_state import PieceState
from core.placement import Placement
from core.settings import (BOARD_HEIGHT, BOARD_WIDTH, VISIBLE_BOARD_HEIGHT,
get_setting)
from core.simulator import Simulator
class PathVisualizerGame:
"""Main Tetris game class that combines simulator, GUI, and pathfinding visualization."""
def __init__(self):
"""Initialize the Tetris game."""
# Initialize pygame
pygame.init()
# DAS/ARR/SDD settings (in milliseconds)
self.handling_settings = get_setting('handling')
# Initialize game state
self.game_state = self._create_initial_game_state()
# Initialize GUI
self.gui = GUI(self.game_state, {
"title": "Tetris Path Visualizer",
"window_size": (550, 650),
})
# Initialize input handler
self.input_handler = InputHandler()
self.input_handler.setup(self.handling_settings, self._perform_action)
# Game state
self.running = True
# Drawing state
self.drawing = False
self.drawing_mode = None
# Pathfinding state
self.target_placement: Optional[Placement] = None
self.pathfinding_in_progress: bool = False
self.current_path: Optional[list[BotAction]] = None
self.path_step: int = 0
# Key mappings
keybinds = get_setting('keybinds')
self.keybind_settings = {
PYGAME_KEYMAP[keybinds['left']]: Action.MOVE_LEFT,
PYGAME_KEYMAP[keybinds['right']]: Action.MOVE_RIGHT,
PYGAME_KEYMAP[keybinds['down']]: Action.MOVE_DOWN,
PYGAME_KEYMAP[keybinds['rotate_clockwise']]: Action.ROTATE_CW,
PYGAME_KEYMAP[keybinds['rotate_counterclockwise']]: Action.ROTATE_CCW,
PYGAME_KEYMAP[keybinds['rotate_180']]: Action.ROTATE_180,
PYGAME_KEYMAP[keybinds['hard_drop']]: 'set_target', # Set target instead of dropping
PYGAME_KEYMAP[keybinds['hold']]: 'cycle_piece', # Cycle current piece
PYGAME_KEYMAP[keybinds['reset']]: 'reset'
}
def _create_initial_game_state(self) -> GameState:
"""Create the initial game state without queue/bag; start with a default piece."""
board = Board()
# Start with a default piece (T). You can cycle with the hold key.
current_piece = Piece.T
next_piece = Piece.I
current_piece_state = PieceState.get_spawn_state(current_piece)
return GameState(
sequence_number=0,
board=board,
current_piece=current_piece,
current_piece_state=current_piece_state,
held_piece=next_piece,
bag=[],
combo=0,
back_to_back=0
)
# Queue/bag is not used in the visualizer; there is no next queue.
def _perform_action(self, action: Action) -> bool:
"""Perform a game action using the simulator."""
# Simulate the action
new_state, _ = Simulator.simulate(self.game_state, action)
# Update game state
self.game_state = new_state
return True
def _set_target_and_pathfind(self) -> None:
"""Set the current piece position as target and attempt to pathfind to it."""
if not self.game_state.current_piece_state:
print("No current piece to set as target")
return
# We need to simulate a hard drop to get the actual placement
try:
_, test_placement = Simulator.simulate(self.game_state, Action.HARD_DROP)
if test_placement:
self.target_placement = test_placement
spin_str = f"{test_placement.spin.piece} {'Mini ' if test_placement.spin.mini else ''}" if test_placement.spin else "None"
print(f"Set target at ({test_placement.piece_state.x}, {test_placement.piece_state.y}, orientation={test_placement.piece_state.orientation}, spin={spin_str})")
else:
print("Could not determine target placement")
return
except Exception as e:
print(f"Error determining target placement: {e}")
return
# Attempt to pathfind to the target
initial_state = GameState(
sequence_number=0,
board=self.game_state.board,
current_piece=self.game_state.current_piece,
current_piece_state=PieceState.get_spawn_state(self.game_state.current_piece),
held_piece=self.game_state.held_piece,
bag=self.game_state.bag,
combo=self.game_state.combo,
back_to_back=self.game_state.back_to_back
)
start_time = perf_counter_ns()
path = Pathfinder.find_path(initial_state, self.target_placement)
end_time = perf_counter_ns()
duration = (end_time - start_time) / 1000000 # Convert to milliseconds
if path:
# Reset piece to spawn position
self._reset_piece_to_spawn()
self.current_path = path
self.path_step = 0
self.pathfinding_in_progress = True
print(f"Found path with {len(path)} actions in {duration:.2f}ms:")
for bot_action in path:
print(f" {bot_action}")
else:
print("Could not find path to target")
self.current_path = None
self.pathfinding_in_progress = False
def _reset_piece_to_spawn(self) -> None:
"""Reset the current piece to spawn position."""
if self.game_state.current_piece:
self.game_state.current_piece_state = PieceState.get_spawn_state(self.game_state.current_piece)
def _execute_next_path_step(self) -> None:
"""Execute the next step in the current path."""
if not self.pathfinding_in_progress or not self.current_path or self.path_step >= len(self.current_path):
self.pathfinding_in_progress = False
return
bot_action = self.current_path[self.path_step]
# For the last action (hard drop), execute sonic drop instead
if self.path_step == len(self.current_path) - 1 and bot_action.action == Action.HARD_DROP:
self._perform_action(Action.SONIC_DROP)
else:
# Perform the action normally
self._perform_action(bot_action.action)
self.path_step += 1
# Check if we've completed the path
if self.path_step >= len(self.current_path):
self.pathfinding_in_progress = False
def _handle_events(self) -> None:
"""Handle pygame events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
self._handle_keydown(event.key)
elif event.type == pygame.KEYUP:
self._handle_keyup(event.key)
elif event.type == pygame.MOUSEBUTTONDOWN:
self._handle_mouse_down(event)
elif event.type == pygame.MOUSEBUTTONUP:
self._handle_mouse_up(event)
elif event.type == pygame.MOUSEMOTION:
self._handle_mouse_motion(event)
def _handle_keydown(self, key: int) -> None:
"""Handle key press events."""
# Block all inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
if key in self.keybind_settings:
action = self.keybind_settings[key]
if action == 'reset':
self._reset_game()
return
elif action == 'set_target':
self._set_target_and_pathfind()
return
elif action == 'cycle_piece':
self._cycle_piece()
return
elif isinstance(action, Action):
# Let input handler deal with all actions
self.input_handler.handle_action(action)
def _cycle_piece(self) -> None:
"""Cycle the current piece through all seven tetrominoes and reset to spawn."""
if not self.game_state:
return
piece_order = [Piece.T, Piece.I, Piece.O, Piece.S, Piece.Z, Piece.L, Piece.J]
current = self.game_state.current_piece or Piece.T
try:
idx = piece_order.index(current)
except ValueError:
idx = piece_order.index(Piece.T)
next_piece = piece_order[(idx + 1) % len(piece_order)]
next_next_piece = piece_order[(idx + 2) % len(piece_order)]
self.game_state.current_piece = next_piece
self.game_state.current_piece_state = PieceState.get_spawn_state(next_piece)
self.game_state.held_piece = next_next_piece
def _handle_keyup(self, key: int) -> None:
"""Handle key release events."""
# Block all inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
if key in self.keybind_settings:
action = self.keybind_settings[key]
if isinstance(action, Action) and action in [Action.MOVE_LEFT, Action.MOVE_RIGHT, Action.MOVE_DOWN]:
self.input_handler.stop_input(action)
def _handle_mouse_down(self, event: pygame.event.Event) -> None:
"""Handle mouse button press events."""
# Block all mouse inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
if event.button == 1: # Left click
self.drawing = True
self.drawing_mode = 'add'
elif event.button == 3: # Right click
self.drawing = True
self.drawing_mode = 'remove'
# Handle the initial click
self._handle_mouse_click(event.pos)
def _handle_mouse_up(self, event: pygame.event.Event) -> None:
"""Handle mouse button release events."""
# Block all mouse inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
if event.button in [1, 3]: # Left or right click
self.drawing = False
self.drawing_mode = None
def _handle_mouse_motion(self, event: pygame.event.Event) -> None:
"""Handle mouse motion events."""
# Block all mouse inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
if self.drawing:
# Check if mouse is still over the board
board_pos = self._screen_to_board_pos(event.pos)
if board_pos:
self._handle_mouse_click(event.pos)
else:
# Mouse left the board area, stop drawing
self.drawing = False
self.drawing_mode = None
def _handle_mouse_click(self, pos: tuple[int, int]) -> None:
"""Handle mouse click at the given position."""
# Block all mouse inputs when pathfinding is in progress
if self.pathfinding_in_progress:
return
# Convert screen position to board coordinates
board_pos = self._screen_to_board_pos(pos)
if board_pos:
x, y = board_pos
if self.drawing_mode == 'add':
self._create_cell_at(x, y)
elif self.drawing_mode == 'remove':
self._remove_cell_at(x, y)
def _screen_to_board_pos(self, screen_pos: tuple[int, int]) -> Optional[tuple[int, int]]:
"""Convert screen position to board coordinates."""
# Get the board rectangle from the GUI
board_rect = self.gui.board_rect
# Check if the click is within the board area
if not board_rect.collidepoint(screen_pos):
return None
# Calculate relative position within the board
rel_x = screen_pos[0] - board_rect.left
rel_y = screen_pos[1] - board_rect.top
# Convert to board coordinates
board_x = rel_x // self.gui.cell_size
# Convert Y coordinate - GUI flips Y-axis for display
# The GUI uses: screen_y = board_rect.top + (VISIBLE_BOARD_HEIGHT - 1 - y) * cell_size
# So we need to reverse this: y = VISIBLE_BOARD_HEIGHT - 1 - (rel_y // cell_size)
board_y = VISIBLE_BOARD_HEIGHT - 1 - (rel_y // self.gui.cell_size)
# Check bounds
if 0 <= board_x < BOARD_WIDTH and 0 <= board_y < BOARD_HEIGHT:
return (board_x, board_y)
return None
def _create_cell_at(self, x: int, y: int) -> None:
"""Add a piece at the given board coordinates."""
if 0 <= x < BOARD_WIDTH and 0 <= y < BOARD_HEIGHT:
# Use the current piece type or default to a filled cell
self.game_state.board.set_cell(x, y, True)
def _remove_cell_at(self, x: int, y: int) -> None:
"""Remove a piece at the given board coordinates."""
if 0 <= x < BOARD_WIDTH and 0 <= y < BOARD_HEIGHT:
self.game_state.board.set_cell(x, y, False)
def _reset_game(self) -> None:
"""Reset the game to initial state."""
self.game_state = self._create_initial_game_state()
self.input_handler.reset()
self.target_placement = None
self.pathfinding_in_progress = False
self.current_path = None
self.path_step = 0
def run(self) -> None:
"""Main game loop."""
clock = pygame.time.Clock()
path_step_timer = 0
path_step_delay = 200 # milliseconds between path steps
while self.running:
# Handle events
self._handle_events()
# Update input handler (only when not pathfinding)
if not self.pathfinding_in_progress:
self.input_handler.update()
# Handle pathfinding execution
if self.pathfinding_in_progress:
current_time = pygame.time.get_ticks()
if current_time - path_step_timer > path_step_delay:
self._execute_next_path_step()
path_step_timer = current_time
# Update display
self.gui.update_display(self.game_state)
# Cap frame rate
clock.tick(60)
def main() -> None:
game = PathVisualizerGame()
game.run()
if __name__ == "__main__":
main()