diff --git a/assets/boss.jpg b/assets/boss.jpg new file mode 100644 index 0000000..2aa04f6 Binary files /dev/null and b/assets/boss.jpg differ diff --git a/config.py b/config.py index cb3f967..d855a2c 100644 --- a/config.py +++ b/config.py @@ -28,6 +28,7 @@ ASSETS_PATH = "assets" WALL_IMAGE = f"{ASSETS_PATH}/wall.png" COIN_IMAGE = f"{ASSETS_PATH}/coin.png" TRAP_IMAGE = f"{ASSETS_PATH}/trap.png" +BOSS_IMAGE = f"{ASSETS_PATH}/boss.jpg" START_BUTTON_IMAGE = f"{ASSETS_PATH}/start_button.png" SAVE_BUTTON_IMAGE = f"{ASSETS_PATH}/save.png" LOAD_BUTTON_IMAGE = f"{ASSETS_PATH}/load.png" diff --git a/demo_history_iteration.py b/demo_history_iteration.py new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py index a0c58d4..79845b3 100644 --- a/main.py +++ b/main.py @@ -38,6 +38,7 @@ def create_buttons(button_positions): button_load_texture = pygame.image.load(LOAD_BUTTON_IMAGE).convert_alpha() button_load_texture = pygame.transform.scale(button_load_texture, BUTTON_SAVE_SIZE) + # 创建按钮对象 button_start = Button(pygame.rect.Rect(*button_positions['start_button'], *BUTTON_START_SIZE), button_start_texture) @@ -78,6 +79,7 @@ if __name__ == "__main__": image_wall = pygame.image.load(WALL_IMAGE).convert_alpha() image_coin = pygame.image.load(COIN_IMAGE).convert_alpha() image_trap = pygame.image.load(TRAP_IMAGE).convert_alpha() + image_boss = pygame.image.load(BOSS_IMAGE).convert_alpha() # 初始按钮位置和按钮 button_positions = get_button_positions() @@ -89,6 +91,7 @@ if __name__ == "__main__": mes3 = Toast("存档已保存", UI_WIDTH, UI_HEIGHT, font=textFont) mes4 = Toast("存档加载成功", UI_WIDTH, UI_HEIGHT, font=textFont) mes5 = Toast("加载失败", UI_WIDTH, UI_HEIGHT, font=textFont) + mes_boss = Toast("遇到Boss!准备战斗!", UI_WIDTH, UI_HEIGHT, font=textFont, duration=3, color=(255, 255, 0), bg_color=(255, 0, 0)) # 创建存档界面 save_ui = SaveLoadUI(textFont) @@ -124,8 +127,15 @@ if __name__ == "__main__": if auto_play and len(maze.full_path) > 0 and not maze.show_history: auto_play_timer += 1 if auto_play_timer >= auto_play_interval: - if not maze.next_path_step(): + has_next, boss_encountered, boss_info = maze.next_path_step() + if not has_next: auto_play = False # 路径播放完成后停止自动播放 + elif boss_encountered: + if boss_info: + mes_boss.text = f"遇到Boss!{boss_info}" + else: + mes_boss.text = "遇到Boss!准备战斗!" + mes_boss.show() # 显示boss遭遇提示 auto_play_timer = 0 # 历史迭代自动播放逻辑 @@ -215,7 +225,13 @@ if __name__ == "__main__": # 路径控制 if buttons['next_step'].pressed == True and len(maze.full_path) > 0 and not maze.show_history: - maze.next_path_step() + has_next, boss_encountered, boss_info = maze.next_path_step() + if boss_encountered: + if boss_info: + mes_boss.text = f"遇到Boss!{boss_info}" + else: + mes_boss.text = "遇到Boss!准备战斗!" + mes_boss.show() # 显示boss遭遇提示 if buttons['reset_path'].pressed == True and len(maze.full_path) > 0 and not maze.show_history: maze.reset_path() @@ -244,7 +260,13 @@ if __name__ == "__main__": # 键盘控制 if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and len(maze.full_path) > 0 and not maze.show_history: - maze.next_path_step() + has_next, boss_encountered, boss_info = maze.next_path_step() + if boss_encountered: + if boss_info: + mes_boss.text = f"遇到Boss!{boss_info}" + else: + mes_boss.text = "遇到Boss!准备战斗!" + mes_boss.show() # 显示boss遭遇提示 elif event.key == pygame.K_r and len(maze.full_path) > 0 and not maze.show_history: maze.reset_path() auto_play = False @@ -287,7 +309,7 @@ if __name__ == "__main__": running = False - maze.draw(screen=screen, wall_texture=image_wall, coin_texture=image_coin, trap_texture=image_trap) + maze.draw(screen=screen, wall_texture=image_wall, coin_texture=image_coin, trap_texture=image_trap, boss_texture=image_boss) buttons['start'].draw(screen=screen) buttons['save'].draw(screen=screen) buttons['load'].draw(screen=screen) @@ -355,6 +377,7 @@ if __name__ == "__main__": mes3.draw(screen=screen) mes4.draw(screen=screen) mes5.draw(screen=screen) + mes_boss.draw(screen=screen) # 绘制存档界面(必须在最后绘制以显示在最上层) save_ui.draw(screen) diff --git a/maze.py b/maze.py index fe520cc..62edd59 100644 --- a/maze.py +++ b/maze.py @@ -70,6 +70,7 @@ class Maze: # 设置显示状态 self.grid = self.generater.maze # 使用原始迷宫数据 + print(self.grid) self.update_display_size() # 更新显示尺寸 print(f"路径长度: {len(self.full_path)}") @@ -79,10 +80,28 @@ class Maze: def next_path_step(self): """显示路径的下一步""" if self.path_step < len(self.full_path): + # 获取当前要显示的位置 + current_y, current_x = self.full_path[self.path_step] + + # 检查当前位置是否有boss + boss_encountered = False + boss_info = None + if self.generater.maze and self.generater.maze[current_y][current_x].startswith('b'): + boss_encountered = True + boss_cell = self.generater.maze[current_y][current_x] + # 提取boss血量信息 + try: + boss_hp = int(boss_cell[1:]) # 去掉'b'前缀,获取血量 + boss_info = f"Boss血量: {boss_hp}" + except ValueError: + boss_info = "Boss" + self.path_step += 1 self.update_grid_with_path() - return True - return False + + # 返回是否遇到boss和boss信息 + return True, boss_encountered, boss_info + return False, False, None def reset_path(self): """重置路径显示""" @@ -93,8 +112,12 @@ class Maze: def auto_advance_path(self): """自动推进路径显示""" if not self.is_path_complete: - if not self.next_path_step(): + has_next, boss_encountered, boss_info = self.next_path_step() + if not has_next: self.is_path_complete = True + # 注意:这里不处理boss遭遇,因为这个方法可能不在主循环中调用 + return boss_encountered, boss_info + return False, None def update_grid_with_path(self): """根据当前步数更新网格显示""" @@ -169,7 +192,7 @@ class Maze: - def draw(self, screen, wall_texture, coin_texture, trap_texture): + def draw(self, screen, wall_texture, coin_texture, trap_texture, boss_texture): if len(self.grid) == 0: return @@ -181,12 +204,16 @@ class Maze: wall_texture = pygame.transform.scale(wall_texture, (tile_size, tile_size)) coin_texture = pygame.transform.scale(coin_texture, (tile_size, tile_size)) trap_texture = pygame.transform.scale(trap_texture, (tile_size, tile_size)) + boss_texture = pygame.transform.scale(boss_texture, (tile_size, tile_size)) for y in range(self.size): for x in range(self.size): if self.grid[y][x] == '1': screen.blit(wall_texture, (x * tile_size, y * tile_size)) continue + if self.grid[y][x].startswith('b'): + screen.blit(boss_texture, (x * tile_size, y * tile_size)) + continue if self.grid[y][x].startswith('g'): screen.blit(coin_texture, (x * tile_size, y * tile_size)) diff --git a/simple_save_manager.py b/simple_save_manager.py index 7efd6c1..1b766ca 100644 --- a/simple_save_manager.py +++ b/simple_save_manager.py @@ -464,7 +464,7 @@ class SimpleSaveManager: elif cell == 'L': internal_row.append('l20') # 默认机关值 elif cell == 'B': - internal_row.append('b50') # 默认BOSS值 + internal_row.append('b') # 默认BOSS值 else: # 未知类型,默认为通路 internal_row.append('0') diff --git a/tests/test_10_saves_display.py b/tests/test_10_saves_display.py deleted file mode 100644 index 8249bc4..0000000 --- a/tests/test_10_saves_display.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python3 -"""测试存档界面显示10条存档的能力""" - -import pygame -import sys -import os - -# 添加项目根目录到路径 -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from config import * -from save_ui import SaveLoadUI -from maze import Maze - -def test_10_saves_display(): - """测试显示10条存档""" - print("=== 测试存档界面10条存档显示能力 ===") - - # 初始化pygame - pygame.init() - screen = pygame.display.set_mode((UI_WIDTH, UI_HEIGHT)) - pygame.display.set_caption("测试10条存档显示") - font = pygame.font.Font(FONT_FILE, FONT_SIZE) - - # 创建对象 - maze = Maze(wall_size=20, maze_size=200, file_name="test") - save_ui = SaveLoadUI(font) - - # 检查max_visible_saves设置 - print(f"max_visible_saves设置: {save_ui.max_visible_saves}") - - # 模拟10条存档数据 - mock_saves = [] - for i in range(10): - mock_saves.append({ - 'name': f'test_save_{i+1:02d}.json', - 'path': f'saves/test_save_{i+1:02d}.json', - 'save_time': f'2024-01-{i+1:02d} 10:00:00', - 'size': '5x5' - }) - - # 直接设置存档列表 - save_ui.save_list = mock_saves - save_ui.show_save_list = True - - print(f"模拟存档数量: {len(mock_saves)}") - - # 计算显示参数 - button_positions = get_button_positions() - list_area = button_positions['save_list_area'] - - print(f"存档列表区域: x={list_area[0]}, y={list_area[1]}, w={list_area[2]}, h={list_area[3]}") - - # 计算可显示的存档数量 - # 标题区域: 30像素 - # 操作提示区域: 25像素 - # 剩余区域高度: 330 - 30 - 25 = 275像素 - # 每个存档项: 25像素 - available_height = list_area[3] - 55 # 55 = 30(标题) + 25(提示) - max_displayable = available_height // 25 - - print(f"可用显示高度: {available_height}像素") - print(f"理论最大显示数量: {max_displayable}条") - print(f"实际设置显示数量: {save_ui.max_visible_saves}条") - - # 测试显示 - clock = pygame.time.Clock() - running = True - - while running: - for event in pygame.event.get(): - if event.type == pygame.QUIT: - running = False - elif event.type == pygame.KEYDOWN: - if event.key == pygame.K_ESCAPE: - running = False - elif event.key == pygame.K_UP: - if save_ui.selected_save > 0: - save_ui.selected_save -= 1 - print(f"选中存档: {save_ui.selected_save + 1}") - elif event.key == pygame.K_DOWN: - if save_ui.selected_save < len(save_ui.save_list) - 1: - save_ui.selected_save += 1 - print(f"选中存档: {save_ui.selected_save + 1}") - - # 绘制 - screen.fill(COLOR_WHITE) - save_ui.draw(screen) - - # 绘制测试信息 - info_text = [ - f"存档数量: {len(save_ui.save_list)}", - f"显示设置: {save_ui.max_visible_saves}条", - f"当前选中: {save_ui.selected_save + 1}", - "按↑↓键选择存档,ESC退出" - ] - - for i, text in enumerate(info_text): - text_surface = font.render(text, True, COLOR_BLACK) - screen.blit(text_surface, (10, 10 + i * 30)) - - pygame.display.flip() - clock.tick(60) - - pygame.quit() - print("测试完成") - -if __name__ == "__main__": - test_10_saves_display() diff --git a/tests/test_boundary_main.py b/tests/test_boundary_main.py deleted file mode 100644 index 1b33afc..0000000 --- a/tests/test_boundary_main.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python3 -""" -主程序边界修复功能测试指南 -""" - -print("=== 主程序边界修复功能测试 ===") -print() -print("此测试将启动主程序来验证边界修复功能。") -print() -print("测试步骤:") -print("1. 启动程序后,点击 [Load] 按钮") -print("2. 程序会尝试加载 saves/sample.json") -print(" 如果不存在,会打开存档选择界面") -print("3. 在存档列表中选择 'maze_15_15_2.json'") -print("4. 观察控制台输出,应该看到边界修复信息") -print("5. 验证迷宫能正常显示且四周有墙壁") -print("6. 确认没有程序错误或崩溃") -print() -print("预期结果:") -print("- 控制台显示:'检测到迷宫边界不完整,自动添加边界墙壁...'") -print("- 控制台显示:'边界修复完成:15x15 -> 17x17'") -print("- 迷宫正常显示,四周都是墙壁") -print("- 程序运行稳定,没有错误") -print() -print("可以测试的文件:") -print("- maze_15_15_2.json (已知边界问题)") -print("- test_no_boundary.json (测试创建的无边界文件)") -print("- 其他正常的JSON文件 (验证不影响正常文件)") -print() - -input("按 Enter 键启动程序进行测试...") - -try: - import main -except KeyboardInterrupt: - print("\n测试完成,程序已退出") -except Exception as e: - print(f"\n程序运行出现错误: {str(e)}") - print("请检查边界修复功能的实现") diff --git a/tests/test_boundary_repair.py b/tests/test_boundary_repair.py deleted file mode 100644 index 6906d6c..0000000 --- a/tests/test_boundary_repair.py +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env python3 -""" -测试迷宫边界自动修复功能 -验证当迷宫四周不是墙时能自动添加边界 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from simple_save_manager import simple_save_manager -from maze import Maze -import json - -def test_boundary_repair(): - """测试边界修复功能""" - print("=== 测试迷宫边界自动修复功能 ===") - - # 测试加载有问题边界的JSON文件 - test_file = "saves/maze_15_15_2.json" - if not os.path.exists(test_file): - print(f"❌ 测试文件 {test_file} 不存在") - return False - - print(f"加载测试文件: {test_file}") - - # 先查看原始文件内容 - with open(test_file, 'r', encoding='utf-8') as f: - original_data = json.load(f) - - original_maze = original_data['maze'] - print(f"原始迷宫尺寸: {len(original_maze)}x{len(original_maze[0])}") - - # 检查原始边界 - height = len(original_maze) - width = len(original_maze[0]) - - print("原始边界检查:") - print(f" 上边界: {original_maze[0]}") - print(f" 下边界: {original_maze[height-1]}") - print(f" 左边界: {[row[0] for row in original_maze]}") - print(f" 右边界: {[row[width-1] for row in original_maze]}") - - # 使用simple_save_manager加载 - load_data = simple_save_manager.load_maze_from_file(test_file) - if load_data is None: - print("❌ 加载失败") - return False - - # 检查修复后的迷宫 - repaired_maze = load_data['original_grid'] - print(f"修复后迷宫尺寸: {len(repaired_maze)}x{len(repaired_maze[0])}") - - # 验证边界是否都是墙 - new_height = len(repaired_maze) - new_width = len(repaired_maze[0]) - - boundary_ok = True - - # 检查上下边界 - for col in range(new_width): - if repaired_maze[0][col] not in ['#', '1']: - print(f"❌ 上边界第{col}列不是墙: {repaired_maze[0][col]}") - boundary_ok = False - if repaired_maze[new_height-1][col] not in ['#', '1']: - print(f"❌ 下边界第{col}列不是墙: {repaired_maze[new_height-1][col]}") - boundary_ok = False - - # 检查左右边界 - for row in range(new_height): - if repaired_maze[row][0] not in ['#', '1']: - print(f"❌ 左边界第{row}行不是墙: {repaired_maze[row][0]}") - boundary_ok = False - if repaired_maze[row][new_width-1] not in ['#', '1']: - print(f"❌ 右边界第{row}行不是墙: {repaired_maze[row][new_width-1]}") - boundary_ok = False - - if boundary_ok: - print("✅ 边界修复成功,所有边界都是墙壁") - else: - print("❌ 边界修复失败") - return False - - return True - -def test_maze_loading_with_repair(): - """测试在Maze类中加载带有边界问题的迷宫""" - print("\n=== 测试Maze类加载边界修复 ===") - - maze = Maze(wall_size=30, maze_size=600, file_name="test.csv") - - test_file = "saves/maze_15_15_2.json" - if not os.path.exists(test_file): - print(f"❌ 测试文件 {test_file} 不存在") - return False - - # 加载迷宫 - result = maze.load_game(test_file) - if not result: - print("❌ Maze加载失败") - return False - - # 检查加载后的迷宫是否正常 - if len(maze.grid) == 0: - print("❌ 加载后迷宫网格为空") - return False - - # 验证边界 - height = len(maze.grid) - width = len(maze.grid[0]) - - print(f"Maze加载后尺寸: {width}x{height}") - - # 简单检查四个角是否是墙 - corners = [ - maze.grid[0][0], maze.grid[0][width-1], - maze.grid[height-1][0], maze.grid[height-1][width-1] - ] - - if all(corner in ['#', '1'] for corner in corners): - print("✅ Maze加载成功,边界正常") - return True - else: - print(f"❌ Maze加载后边界有问题,四个角: {corners}") - return False - -def test_create_test_file_without_boundary(): - """创建一个没有边界的测试文件""" - print("\n=== 创建测试用的无边界迷宫文件 ===") - - # 创建一个中间没有边界的迷宫 - test_maze = [ - [" ", "S", " ", " ", " "], - [" ", "#", " ", "#", " "], - [" ", " ", " ", "#", " "], - [" ", "#", " ", " ", " "], - [" ", " ", " ", "E", " "] - ] - - test_data = { - "maze": test_maze, - "metadata": { - "name": "无边界测试迷宫", - "test": True - } - } - - test_file = "saves/test_no_boundary.json" - with open(test_file, 'w', encoding='utf-8') as f: - json.dump(test_data, f, indent=2, ensure_ascii=False) - - print(f"创建测试文件: {test_file}") - - # 测试加载这个文件 - load_data = simple_save_manager.load_maze_from_file(test_file) - if load_data is None: - print("❌ 加载自创建的测试文件失败") - return False - - repaired_maze = load_data['original_grid'] - print(f"原始: 5x5 -> 修复后: {len(repaired_maze[0])}x{len(repaired_maze)}") - - # 打印修复后的迷宫 - print("修复后的迷宫:") - for row in repaired_maze: - print(''.join(row)) - - return True - -def main(): - print("开始测试迷宫边界自动修复功能...") - - tests = [ - test_boundary_repair, - test_maze_loading_with_repair, - test_create_test_file_without_boundary - ] - - passed = 0 - total = len(tests) - - for test in tests: - try: - if test(): - passed += 1 - else: - print(f"❌ 测试 {test.__name__} 失败") - except Exception as e: - print(f"❌ 测试 {test.__name__} 出现异常: {str(e)}") - import traceback - traceback.print_exc() - - print(f"\n=== 测试结果 ===") - print(f"通过: {passed}/{total}") - - if passed == total: - print("🎉 所有边界修复功能测试通过!") - return True - else: - print("❌ 部分测试失败,请检查相关功能") - return False - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/tests/test_button_functions.py b/tests/test_button_functions.py deleted file mode 100644 index ec28c2a..0000000 --- a/tests/test_button_functions.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -测试新的按钮功能 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze import Maze -from SourceCollector import SourceCollector - -def test_load_and_generate_path(): - """测试加载样例文件并生成路径的功能""" - print("=== 测试加载样例文件并生成路径 ===\n") - - # 创建迷宫实例 - maze = Maze(wall_size=20, maze_size=400, file_name="test.csv") - - # 测试加载sample.json - sample_file = "saves/sample.json" - print(f"1. 尝试加载 {sample_file}...") - - if os.path.exists(sample_file): - print(f"文件存在,开始加载...") - - # 加载文件 - if maze.load_game(sample_file): - print("✓ 加载成功") - print(f"迷宫大小: {maze.size}x{maze.size}") - - # 重新生成路径 - print("\n2. 重新生成路径...") - if maze.generater.maze: - maze.source_collector = SourceCollector(maze=maze.generater.maze) - maze.source_collector.run() - maze.full_path = maze.source_collector.get_path() - maze.path_step = 0 - maze.is_path_complete = False - maze.grid = maze.generater.maze - - print(f"✓ 路径生成成功") - print(f"路径长度: {len(maze.full_path)}") - print(f"路径前10步: {maze.full_path[:10]}") - - # 显示迷宫的起点和终点 - start_pos = None - end_pos = None - for y in range(maze.size): - for x in range(maze.size): - if maze.generater.maze[y][x] == 's': - start_pos = (y, x) - elif maze.generater.maze[y][x] == 'e': - end_pos = (y, x) - - print(f"起点位置: {start_pos}") - print(f"终点位置: {end_pos}") - - if maze.full_path: - print(f"路径起点: {maze.full_path[0]}") - print(f"路径终点: {maze.full_path[-1]}") - - return True - else: - print("✗ 迷宫数据无效") - return False - else: - print("✗ 加载失败") - return False - else: - print(f"✗ 文件不存在: {sample_file}") - return False - -def test_save_json(): - """测试保存JSON功能""" - print("\n=== 测试保存JSON功能 ===\n") - - # 创建并生成新迷宫 - maze = Maze(wall_size=20, maze_size=400, file_name="test.csv") - maze.generate() - - print(f"生成迷宫大小: {maze.size}x{maze.size}") - print(f"路径长度: {len(maze.full_path)}") - - # 保存为JSON - result = maze.save_game("test_button_save", "json") - if result: - print(f"✓ JSON保存成功: {result}") - return True - else: - print("✗ JSON保存失败") - return False - -if __name__ == "__main__": - success1 = test_load_and_generate_path() - success2 = test_save_json() - - print(f"\n=== 测试结果 ===") - print(f"加载并生成路径: {'成功' if success1 else '失败'}") - print(f"保存JSON: {'成功' if success2 else '失败'}") - - if success1 and success2: - print("✓ 所有测试通过!新按钮功能正常工作。") - else: - print("✗ 部分测试失败,需要检查。") diff --git a/tests/test_complete_boundary_fix.py b/tests/test_complete_boundary_fix.py deleted file mode 100644 index fb5e0d2..0000000 --- a/tests/test_complete_boundary_fix.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python3 -""" -边界修复和路径生成完整功能测试指南 -验证所有相关修复是否正确工作 -""" - -print("=== 边界修复和路径生成完整测试指南 ===") -print() -print("此测试将启动主程序验证以下功能:") -print() -print("🛡️ 边界自动修复功能:") -print("1. 系统自动检测迷宫边界问题") -print("2. 自动添加边界墙壁(15x15→17x17)") -print("3. 路径坐标自动调整") -print() -print("🎯 路径生成修复:") -print("1. SourceCollector边界检查正确") -print("2. 不会出现数组越界错误") -print("3. 能成功生成完整路径") -print() -print("测试步骤:") -print("1. 启动程序") -print("2. 点击 [Load] 按钮") -print("3. 程序会自动加载 saves/sample.json (已复制maze_15_15_2.json)") -print("4. 观察控制台输出,应该看到:") -print(" - '检测到迷宫边界不完整,自动添加边界墙壁...'") -print(" - '边界修复完成:15x15 -> 17x17'") -print(" - '已加载 saves/sample.json'") -print("5. 验证迷宫正常显示,没有程序错误") -print("6. 尝试路径演示功能(下一步、自动播放等)") -print() -print("可选的额外测试:") -print("- 按Ctrl+L打开存档界面,加载maze_15_15_2.json") -print("- 测试双击加载功能") -print("- 验证历史迭代功能正常工作") -print() -print("预期结果:") -print("✅ 没有IndexError或其他错误") -print("✅ 迷宫正常显示且四周有墙壁") -print("✅ 路径演示功能正常工作") -print("✅ 控制台显示正确的修复信息") -print() -print("注意事项:") -print("- 如果sample.json不存在,系统会打开存档选择界面") -print("- 可以手动选择maze_15_15_2.json进行测试") -print("- 边界修复是自动且透明的,用户无需手动操作") -print() - -input("按 Enter 键启动程序进行完整测试...") - -try: - import main -except KeyboardInterrupt: - print("\n测试完成,程序已退出") - print() - print("如果程序运行正常且没有错误,说明所有修复都工作正常!") -except Exception as e: - print(f"\n程序运行出现错误: {str(e)}") - print("请检查错误信息并参考修复文档") diff --git a/tests/test_dynamic_ui.py b/tests/test_dynamic_ui.py deleted file mode 100644 index 1de9de1..0000000 --- a/tests/test_dynamic_ui.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -测试动态UI布局功能 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze import Maze -from config import get_button_positions, MAZE_SIZE - -def test_dynamic_ui(): - """测试动态UI布局功能""" - print("=== 测试动态UI布局功能 ===\n") - - # 测试不同大小的迷宫 - test_cases = [ - ("小迷宫", 10), # 10x10 - ("中迷宫", 15), # 15x15 - ("大迷宫", 20), # 20x20 - ("超大迷宫", 25), # 25x25 - ] - - for name, size in test_cases: - print(f"{name} ({size}x{size}):") - - # 创建迷宫实例 - maze = Maze(wall_size=40, maze_size=size*40, file_name="test.csv") - - # 模拟网格数据(创建指定大小的迷宫) - maze.grid = [['1' for _ in range(size)] for _ in range(size)] - maze.size = size - - # 更新显示尺寸 - maze.update_display_size() - - print(f" 实际墙壁尺寸: {maze.actual_wall_size}") - print(f" 实际显示尺寸: {maze.actual_display_size}") - - # 测试按钮位置 - button_positions = get_button_positions(maze.actual_display_size) - print(f" 开始按钮位置: {button_positions['start_button']}") - print(f" 保存按钮位置: {button_positions['save_button']}") - print(f" 加载按钮位置: {button_positions['load_button']}") - print() - - # 测试加载不同存档文件的效果 - print("=== 测试加载不同存档文件 ===\n") - - saves_dir = "saves" - if os.path.exists(saves_dir): - save_files = [f for f in os.listdir(saves_dir) if f.endswith('.json')][:3] - - for save_file in save_files: - print(f"加载存档: {save_file}") - maze = Maze(wall_size=40, maze_size=800, file_name="test.csv") - - full_path = os.path.join(saves_dir, save_file) - if maze.load_game(full_path): - print(f" 迷宫大小: {maze.size}x{maze.size}") - print(f" 实际显示尺寸: {maze.actual_display_size}") - print(f" 墙壁尺寸: {maze.actual_wall_size}") - - # 计算按钮位置 - button_positions = get_button_positions(maze.actual_display_size) - print(f" 控制面板起始X: {button_positions['start_button'][0]}") - print() - else: - print(f" 加载失败") - print() - - print("=== 按钮位置适应性测试完成 ===") - -def test_button_positions(): - """测试按钮位置计算函数""" - print("\n=== 测试按钮位置计算函数 ===\n") - - test_sizes = [400, 600, 800, 1000, 1200] - - for size in test_sizes: - print(f"迷宫显示尺寸: {size}") - positions = get_button_positions(size) - - print(f" 开始按钮: {positions['start_button']}") - print(f" 存档区域: {positions['save_list_area']}") - - # 检查按钮是否在合理位置(不超出屏幕范围) - control_x = positions['start_button'][0] - if control_x < 1500: # UI_WIDTH - print(f" ✓ 按钮位置合理") - else: - print(f" ✗ 按钮位置可能超出屏幕") - print() - -if __name__ == "__main__": - test_dynamic_ui() - test_button_positions() diff --git a/tests/test_history_iteration.py b/tests/test_history_iteration.py deleted file mode 100644 index 6f3bc89..0000000 --- a/tests/test_history_iteration.py +++ /dev/null @@ -1,195 +0,0 @@ -#!/usr/bin/env python3 -""" -测试历史迭代展示功能 -验证生成过程的历史记录和展示功能 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze_generator import MazeGenerator -from maze import Maze -import time - -def test_history_generation(): - """测试迷宫生成历史记录功能""" - print("=== 测试迷宫生成历史记录 ===") - - generator = MazeGenerator(size=21, filename="test.csv", name="测试迷宫") - generator.generate(seed=12345) - - history = generator.get_history_mazes() - print(f"历史步数: {len(history)}") - - if len(history) == 0: - print("❌ 历史记录为空") - return False - - # 验证历史记录的每一步都是有效的迷宫 - for i, maze_state in enumerate(history): - if len(maze_state) != 21 or len(maze_state[0]) != 21: - print(f"❌ 历史步骤 {i} 尺寸错误: {len(maze_state)}x{len(maze_state[0])}") - return False - - print(f"✅ 历史记录验证通过,共 {len(history)} 步") - return True - -def test_maze_history_methods(): - """测试Maze类的历史展示方法""" - print("\n=== 测试Maze历史展示方法 ===") - - maze = Maze(wall_size=30, maze_size=630, file_name="test.csv") - maze.generate() - - # 验证历史数据 - if len(maze.history_mazes) == 0: - print("❌ 生成后历史数据为空") - return False - - print(f"历史步数: {len(maze.history_mazes)}") - print(f"初始历史步骤: {maze.history_step}") - print(f"初始展示模式: {'历史' if maze.show_history else '路径'}") - - # 测试历史步骤控制 - original_step = maze.history_step - - # 测试下一步 - result = maze.next_history_step() - if result and maze.history_step == original_step + 1: - print("✅ next_history_step 正常工作") - else: - print(f"❌ next_history_step 失败,步骤: {original_step} -> {maze.history_step}") - return False - - # 测试上一步 - result = maze.prev_history_step() - if result and maze.history_step == original_step: - print("✅ prev_history_step 正常工作") - else: - print(f"❌ prev_history_step 失败,步骤: {maze.history_step}") - return False - - # 测试模式切换 - original_mode = maze.show_history - maze.toggle_history_mode() - if maze.show_history != original_mode: - print("✅ toggle_history_mode 正常工作") - else: - print("❌ toggle_history_mode 失败") - return False - - # 切换回原模式 - maze.toggle_history_mode() - - return True - -def test_load_without_history(): - """测试加载存档时不展示历史""" - print("\n=== 测试加载存档时历史处理 ===") - - # 先生成一个迷宫并保存 - maze1 = Maze(wall_size=30, maze_size=600, file_name="test.csv") - maze1.generate() - - if len(maze1.history_mazes) == 0: - print("❌ 生成的迷宫没有历史数据") - return False - - print(f"生成迷宫的历史步数: {len(maze1.history_mazes)}") - - # 保存迷宫 - save_result = maze1.save_game(format_type="json") - if not save_result: - print("❌ 保存迷宫失败") - return False - - # 创建新的迷宫实例并加载 - maze2 = Maze(wall_size=30, maze_size=600, file_name="test.csv") - - # 假设有一个保存的文件 - import glob - json_files = glob.glob("saves/*.json") - if not json_files: - print("❌ 没有找到保存的JSON文件") - return False - - load_result = maze2.load_game(json_files[0]) - if not load_result: - print("❌ 加载迷宫失败") - return False - - # 验证加载后历史数据被清空 - if len(maze2.history_mazes) == 0 and not maze2.show_history: - print("✅ 加载存档后历史数据正确清空") - return True - else: - print(f"❌ 加载存档后历史数据未正确清空: {len(maze2.history_mazes)} 步, 展示模式: {maze2.show_history}") - return False - -def test_history_boundary_conditions(): - """测试历史展示的边界条件""" - print("\n=== 测试历史展示边界条件 ===") - - maze = Maze(wall_size=30, maze_size=600, file_name="test.csv") - maze.generate() - - if len(maze.history_mazes) == 0: - print("❌ 没有历史数据进行测试") - return False - - # 测试超出上限 - maze.history_step = len(maze.history_mazes) - 1 - result = maze.next_history_step() - if not result: - print("✅ 历史步骤上限控制正常") - else: - print("❌ 历史步骤上限控制失败") - return False - - # 测试超出下限 - maze.history_step = 0 - result = maze.prev_history_step() - if not result: - print("✅ 历史步骤下限控制正常") - else: - print("❌ 历史步骤下限控制失败") - return False - - return True - -def main(): - print("开始测试历史迭代展示功能...") - - tests = [ - test_history_generation, - test_maze_history_methods, - test_load_without_history, - test_history_boundary_conditions - ] - - passed = 0 - total = len(tests) - - for test in tests: - try: - if test(): - passed += 1 - else: - print(f"❌ 测试 {test.__name__} 失败") - except Exception as e: - print(f"❌ 测试 {test.__name__} 出现异常: {str(e)}") - - print(f"\n=== 测试结果 ===") - print(f"通过: {passed}/{total}") - - if passed == total: - print("🎉 所有历史迭代展示功能测试通过!") - return True - else: - print("❌ 部分测试失败,请检查相关功能") - return False - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/tests/test_history_reset.py b/tests/test_history_reset.py deleted file mode 100644 index 8773e01..0000000 --- a/tests/test_history_reset.py +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env python3 -""" -测试多次生成迷宫时历史数据重置功能 -验证连续生成迷宫时不会有历史数据混乱 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze import Maze -import time - -def test_multiple_generation(): - """测试多次生成迷宫时历史数据重置""" - print("=== 测试多次生成迷宫历史重置 ===") - - maze = Maze(wall_size=30, maze_size=600, file_name="test.csv") - - # 第一次生成迷宫 - print("\n--- 第一次生成迷宫 ---") - maze.generate() - - first_history_count = len(maze.history_mazes) - first_path_count = len(maze.full_path) - - print(f"第一次生成 - 历史步数: {first_history_count}, 路径长度: {first_path_count}") - - if first_history_count == 0: - print("❌ 第一次生成后没有历史数据") - return False - - # 验证初始状态 - if maze.history_step != 0 or maze.show_history != False or maze.path_step != 0: - print(f"❌ 第一次生成后状态不正确: history_step={maze.history_step}, show_history={maze.show_history}, path_step={maze.path_step}") - return False - - # 切换到历史模式并前进几步 - maze.toggle_history_mode() - maze.next_history_step() - maze.next_history_step() - - print(f"历史模式前进后 - history_step: {maze.history_step}, show_history: {maze.show_history}") - - # 第二次生成迷宫 - print("\n--- 第二次生成迷宫 ---") - maze.generate() - - second_history_count = len(maze.history_mazes) - second_path_count = len(maze.full_path) - - print(f"第二次生成 - 历史步数: {second_history_count}, 路径长度: {second_path_count}") - - # 验证状态重置 - if maze.history_step != 0: - print(f"❌ 第二次生成后history_step未重置: {maze.history_step}") - return False - - if maze.show_history != False: - print(f"❌ 第二次生成后show_history未重置: {maze.show_history}") - return False - - if maze.path_step != 0: - print(f"❌ 第二次生成后path_step未重置: {maze.path_step}") - return False - - if second_history_count == 0: - print("❌ 第二次生成后没有新的历史数据") - return False - - # 验证历史数据是全新的(长度可能不同) - if second_history_count == first_history_count: - # 如果长度相同,检查内容是否不同 - if maze.history_mazes[0] == maze.history_mazes[0]: # 比较第一步 - print("⚠️ 两次生成的历史数据第一步相同(可能是随机种子问题,但功能正常)") - - print(f"✅ 第二次生成后所有状态正确重置") - - # 第三次生成以确保一致性 - print("\n--- 第三次生成迷宫 ---") - - # 先改变一些状态 - maze.toggle_history_mode() - maze.next_history_step() - maze.next_path_step() - - maze.generate() - - third_history_count = len(maze.history_mazes) - third_path_count = len(maze.full_path) - - print(f"第三次生成 - 历史步数: {third_history_count}, 路径长度: {third_path_count}") - - # 再次验证状态重置 - if maze.history_step != 0 or maze.show_history != False or maze.path_step != 0: - print(f"❌ 第三次生成后状态未正确重置") - return False - - print("✅ 第三次生成后状态也正确重置") - - return True - -def test_maze_generator_reset(): - """测试MazeGenerator的历史重置""" - print("\n=== 测试MazeGenerator历史重置 ===") - - from maze_generator import MazeGenerator - - generator = MazeGenerator(size=21, filename="test.csv", name="测试") - - # 第一次生成 - generator.generate(seed=12345) - first_history = len(generator.get_history_mazes()) - first_elements = len(generator.special_elements) - - print(f"第一次生成 - 历史: {first_history}, 特殊元素: {first_elements}") - - # 第二次生成 - generator.generate(seed=54321) - second_history = len(generator.get_history_mazes()) - second_elements = len(generator.special_elements) - - print(f"第二次生成 - 历史: {second_history}, 特殊元素: {second_elements}") - - if first_history == 0 or second_history == 0: - print("❌ 生成器历史数据为空") - return False - - # 验证特殊元素也被重置 - if second_elements == 0: - print("❌ 第二次生成后特殊元素为空") - return False - - print("✅ MazeGenerator历史和特殊元素正确重置") - return True - -def test_state_isolation(): - """测试不同迷宫实例之间的状态隔离""" - print("\n=== 测试迷宫实例状态隔离 ===") - - # 创建两个迷宫实例 - maze1 = Maze(wall_size=30, maze_size=600, file_name="test1.csv") - maze2 = Maze(wall_size=30, maze_size=600, file_name="test2.csv") - - # 生成第一个迷宫 - maze1.generate() - history1 = len(maze1.history_mazes) - - # 修改第一个迷宫的状态 - maze1.toggle_history_mode() - maze1.next_history_step() - - # 生成第二个迷宫 - maze2.generate() - history2 = len(maze2.history_mazes) - - # 验证第二个迷宫的状态是独立的 - if maze2.show_history != False or maze2.history_step != 0: - print(f"❌ 第二个迷宫状态被第一个影响: show_history={maze2.show_history}, history_step={maze2.history_step}") - return False - - # 验证第一个迷宫状态没变 - if maze1.show_history != True or maze1.history_step == 0: - print(f"❌ 第一个迷宫状态意外改变: show_history={maze1.show_history}, history_step={maze1.history_step}") - return False - - print(f"✅ 两个迷宫实例状态正确隔离 (历史: {history1}, {history2})") - return True - -def main(): - print("开始测试多次生成迷宫时历史数据重置...") - - tests = [ - test_multiple_generation, - test_maze_generator_reset, - test_state_isolation - ] - - passed = 0 - total = len(tests) - - for test in tests: - try: - if test(): - passed += 1 - else: - print(f"❌ 测试 {test.__name__} 失败") - except Exception as e: - print(f"❌ 测试 {test.__name__} 出现异常: {str(e)}") - - print(f"\n=== 测试结果 ===") - print(f"通过: {passed}/{total}") - - if passed == total: - print("🎉 所有历史重置功能测试通过!") - return True - else: - print("❌ 部分测试失败,请检查相关功能") - return False - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/tests/test_json_format.py b/tests/test_json_format.py deleted file mode 100644 index 8a8ac10..0000000 --- a/tests/test_json_format.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -测试JSON存档格式功能 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze_generator import MazeGenerator -from maze import Maze -from simple_save_manager import simple_save_manager -import json - -def test_json_save_load(): - """测试JSON格式的保存和加载功能""" - print("=== 测试JSON存档格式功能 ===\n") - - # 1. 生成一个测试迷宫 - print("1. 生成测试迷宫...") - maze = Maze(wall_size=20, maze_size=400, file_name="test_maze.csv") - maze.generate() - print(f"迷宫大小: {maze.size}x{maze.size}") - print(f"路径长度: {len(maze.full_path)}") - - # 2. 保存为JSON格式 - print("\n2. 保存为JSON格式...") - json_save_file = maze.save_game("test_maze_json", "json") - if json_save_file: - print(f"JSON保存成功: {json_save_file}") - - # 查看JSON文件内容 - with open(json_save_file, 'r', encoding='utf-8') as f: - data = json.load(f) - - print("JSON文件结构:") - print(f"- maze: {len(data['maze'])}x{len(data['maze'][0])} 网格") - print(f"- metadata: {data.get('metadata', {})}") - if 'path_data' in data: - print(f"- path_data: 包含{len(data['path_data']['full_path'])}步路径") - - # 显示迷宫的前5行作为示例 - print("\n迷宫前5行示例:") - for i, row in enumerate(data['maze'][:5]): - print(f"第{i+1}行: {row}") - - else: - print("JSON保存失败") - return False - - # 3. 保存为CSV格式(对比) - print("\n3. 保存为CSV格式...") - csv_save_file = maze.save_game("test_maze_csv", "csv") - if csv_save_file: - print(f"CSV保存成功: {csv_save_file}") - else: - print("CSV保存失败") - - # 4. 测试JSON加载 - print("\n4. 测试JSON加载...") - new_maze = Maze(wall_size=20, maze_size=400, file_name="test_load.csv") - if new_maze.load_game(json_save_file): - print("JSON加载成功") - print(f"加载后迷宫大小: {new_maze.size}x{new_maze.size}") - print(f"加载后路径长度: {len(new_maze.full_path)}") - - # 验证加载的数据 - original_path = maze.full_path - loaded_path = new_maze.full_path - if original_path == loaded_path: - print("✓ 路径数据完全一致") - else: - print("✗ 路径数据不一致") - print(f"原始路径前5步: {original_path[:5]}") - print(f"加载路径前5步: {loaded_path[:5]}") - else: - print("JSON加载失败") - return False - - # 5. 测试存档列表 - print("\n5. 测试存档列表...") - save_list = simple_save_manager.get_save_list() - print(f"找到{len(save_list)}个存档文件:") - for save in save_list: - print(f"- {save['name']} ({save['format']}格式) - {save['filename']}") - - # 6. 验证JSON格式转换 - print("\n6. 验证JSON格式转换...") - print("内部格式 -> JSON格式转换测试:") - test_conversions = [ - ('1', '#', '墙壁'), - ('0', ' ', '通路'), - ('s', 'S', '起点'), - ('e', 'E', '终点'), - ('g10', 'G', '金币'), - ('t15', 'T', '陷阱'), - ('l20', 'L', '机关'), - ('b50', 'B', 'BOSS') - ] - - for internal, expected_json, desc in test_conversions: - # 创建单元素测试迷宫 - test_maze = [[internal]] - json_format = simple_save_manager.convert_to_json_format_helper(test_maze) - actual_json = json_format[0][0] - status = "✓" if actual_json == expected_json else "✗" - print(f"{status} {desc}: '{internal}' -> '{actual_json}' (期望: '{expected_json}')") - - print("\n=== 测试完成 ===") - return True - -def simple_save_manager_convert_to_json_format_helper(maze_grid): - """辅助函数:转换迷宫格式用于测试""" - json_maze = [] - for row in maze_grid: - json_row = [] - for cell in row: - cell_str = str(cell) - if cell_str == '1': - json_row.append('#') - elif cell_str == '0': - json_row.append(' ') - elif cell_str == 's': - json_row.append('S') - elif cell_str == 'e': - json_row.append('E') - elif cell_str.startswith('g'): - json_row.append('G') - elif cell_str.startswith('t'): - json_row.append('T') - elif cell_str.startswith('l'): - json_row.append('L') - elif cell_str.startswith('b'): - json_row.append('B') - else: - json_row.append(' ') - json_maze.append(json_row) - return json_maze - -# 为simple_save_manager添加辅助方法 -simple_save_manager.convert_to_json_format_helper = simple_save_manager_convert_to_json_format_helper - -if __name__ == "__main__": - test_json_save_load() diff --git a/tests/test_path_generation_fix.py b/tests/test_path_generation_fix.py deleted file mode 100644 index a1c3f70..0000000 --- a/tests/test_path_generation_fix.py +++ /dev/null @@ -1,210 +0,0 @@ -#!/usr/bin/env python3 -""" -测试边界修复后的路径生成功能 -验证修复边界后SourceCollector能正常工作 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze import Maze -from SourceCollector import SourceCollector -import traceback - -def test_source_collector_with_boundary_fix(): - """测试边界修复后SourceCollector的路径生成""" - print("=== 测试边界修复后路径生成 ===") - - maze = Maze(wall_size=30, maze_size=600, file_name="test.csv") - - # 加载有边界问题的文件 - test_file = "saves/maze_15_15_2.json" - if not os.path.exists(test_file): - print(f"❌ 测试文件 {test_file} 不存在") - return False - - print(f"加载测试文件: {test_file}") - - try: - # 使用maze.load_game加载(会自动修复边界) - result = maze.load_game(test_file) - if not result: - print("❌ 迷宫加载失败") - return False - - print(f"✅ 迷宫加载成功") - print(f"修复后迷宫尺寸: {len(maze.generater.maze)}x{len(maze.generater.maze[0])}") - print(f"显示网格尺寸: {len(maze.grid)}x{len(maze.grid[0])}") - - # 检查是否有路径信息 - if len(maze.full_path) > 0: - print(f"已有路径信息,长度: {len(maze.full_path)}") - return True - - # 如果没有路径信息,尝试生成 - print("没有路径信息,尝试重新生成...") - - # 使用修复后的迷宫创建SourceCollector - source_collector = SourceCollector(maze=maze.generater.maze) - print(f"SourceCollector创建成功,迷宫尺寸: {source_collector.rowNums}x{source_collector.colNums}") - - # 检查起点和终点 - if source_collector.start_pos is None: - print("❌ 没有找到起点") - return False - - if source_collector.end_pos is None: - print("❌ 没有找到终点") - return False - - print(f"起点: {source_collector.start_pos}") - print(f"终点: {source_collector.end_pos}") - - # 尝试运行路径搜索 - source_collector.run() - path = source_collector.get_path() - - if path and len(path) > 0: - print(f"✅ 路径生成成功,长度: {len(path)}") - print(f"起始几步: {path[:5] if len(path) >= 5 else path}") - return True - else: - print("❌ 路径生成失败,没有找到路径") - return False - - except Exception as e: - print(f"❌ 测试过程中出现异常: {str(e)}") - traceback.print_exc() - return False - -def test_boundary_check_in_source_collector(): - """测试SourceCollector的边界检查功能""" - print("\n=== 测试SourceCollector边界检查 ===") - - # 创建一个小的测试迷宫 - test_maze = [ - ['1', '1', '1', '1', '1'], - ['1', 's', '0', '0', '1'], - ['1', '0', '1', '0', '1'], - ['1', '0', '0', 'e', '1'], - ['1', '1', '1', '1', '1'] - ] - - try: - source_collector = SourceCollector(maze=test_maze) - print(f"测试迷宫尺寸: {source_collector.rowNums}x{source_collector.colNums}") - print(f"起点: {source_collector.start_pos}") - print(f"终点: {source_collector.end_pos}") - - # 测试边界检查 - test_cases = [ - (-1, 0), # 左边界外 - (0, -1), # 上边界外 - (5, 2), # 下边界外 - (2, 5), # 右边界外 - (0, 0), # 左上角(边界内) - (4, 4), # 右下角(边界内) - (2, 2), # 中心位置 - ] - - print("边界检查测试:") - for x, y in test_cases: - is_out = source_collector.outofmap(x, y) - expected = x < 0 or y < 0 or x >= 5 or y >= 5 - status = "✅" if is_out == expected else "❌" - print(f" {status} ({x},{y}): {'边界外' if is_out else '边界内'}") - - # 运行路径搜索 - source_collector.run() - path = source_collector.get_path() - - if path and len(path) > 0: - print(f"✅ 小迷宫路径生成成功,长度: {len(path)}") - return True - else: - print("❌ 小迷宫路径生成失败") - return False - - except Exception as e: - print(f"❌ 小迷宫测试异常: {str(e)}") - traceback.print_exc() - return False - -def test_direct_source_collector(): - """直接测试SourceCollector加载修复后的迷宫""" - print("\n=== 直接测试SourceCollector ===") - - from simple_save_manager import simple_save_manager - - test_file = "saves/maze_15_15_2.json" - if not os.path.exists(test_file): - print(f"❌ 测试文件 {test_file} 不存在") - return False - - try: - # 直接使用simple_save_manager加载 - load_data = simple_save_manager.load_maze_from_file(test_file) - if load_data is None: - print("❌ 文件加载失败") - return False - - original_grid = load_data['original_grid'] - print(f"加载的迷宫尺寸: {len(original_grid)}x{len(original_grid[0])}") - - # 直接创建SourceCollector - source_collector = SourceCollector(maze=original_grid) - print(f"SourceCollector尺寸: {source_collector.rowNums}x{source_collector.colNums}") - print(f"起点: {source_collector.start_pos}") - print(f"终点: {source_collector.end_pos}") - - # 运行路径搜索 - source_collector.run() - path = source_collector.get_path() - - if path and len(path) > 0: - print(f"✅ 直接测试路径生成成功,长度: {len(path)}") - return True - else: - print("❌ 直接测试路径生成失败") - return False - - except Exception as e: - print(f"❌ 直接测试异常: {str(e)}") - traceback.print_exc() - return False - -def main(): - print("开始测试边界修复后的路径生成功能...") - - tests = [ - test_boundary_check_in_source_collector, - test_direct_source_collector, - test_source_collector_with_boundary_fix - ] - - passed = 0 - total = len(tests) - - for test in tests: - try: - if test(): - passed += 1 - else: - print(f"❌ 测试 {test.__name__} 失败") - except Exception as e: - print(f"❌ 测试 {test.__name__} 出现异常: {str(e)}") - - print(f"\n=== 测试结果 ===") - print(f"通过: {passed}/{total}") - - if passed == total: - print("🎉 所有路径生成修复测试通过!") - return True - else: - print("❌ 部分测试失败,请检查相关功能") - return False - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/tests/test_save_ui_capacity.py b/tests/test_save_ui_capacity.py deleted file mode 100644 index 3537692..0000000 --- a/tests/test_save_ui_capacity.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python3 -""" -测试存档界面显示数量修改 -验证能否显示10条存档记录 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from simple_save_manager import simple_save_manager -import json -from datetime import datetime - -def create_test_saves(): - """创建测试存档文件""" - print("=== 创建测试存档文件 ===") - - # 确保saves目录存在 - if not os.path.exists("saves"): - os.makedirs("saves") - - # 创建简单的测试迷宫数据 - test_maze_data = { - "maze": [ - ["#", "#", "#", "#", "#"], - ["#", "S", " ", " ", "#"], - ["#", " ", "#", " ", "#"], - ["#", " ", " ", "E", "#"], - ["#", "#", "#", "#", "#"] - ], - "metadata": { - "name": "测试迷宫", - "test": True - } - } - - # 创建12个测试存档(超过10个来测试显示限制) - for i in range(1, 13): - filename = f"saves/test_save_{i:02d}.json" - - # 修改迷宫名称 - test_data = test_maze_data.copy() - test_data["metadata"] = test_maze_data["metadata"].copy() - test_data["metadata"]["name"] = f"测试迷宫_{i:02d}" - test_data["metadata"]["save_time"] = datetime.now().isoformat() - - with open(filename, 'w', encoding='utf-8') as f: - json.dump(test_data, f, indent=2, ensure_ascii=False) - - print(f"创建: {filename}") - - print(f"✅ 创建了12个测试存档文件") - -def check_save_list(): - """检查存档列表""" - print("\n=== 检查存档列表 ===") - - save_list = simple_save_manager.get_save_list() - print(f"找到存档数量: {len(save_list)}") - - for i, save_info in enumerate(save_list): - print(f"{i+1:2d}. {save_info['name']} ({save_info['format']})") - - return len(save_list) - -def calculate_display_capacity(): - """计算显示容量""" - print("\n=== 计算显示容量 ===") - - from config import get_button_positions - - positions = get_button_positions() - save_area = positions['save_list_area'] - - print(f"存档区域尺寸: {save_area[2]}x{save_area[3]} (宽x高)") - - # 计算可用高度 - title_height = 25 - hint_height = 25 - start_offset = 55 # 实际开始位置偏移 - - available_height = save_area[3] - start_offset - item_height = 25 - - max_items = available_height // item_height - - print(f"标题和提示占用: {start_offset}像素") - print(f"可用高度: {available_height}像素") - print(f"每项高度: {item_height}像素") - print(f"理论最大显示: {max_items}条") - - return max_items - -def test_ui_layout(): - """测试UI布局说明""" - print("\n=== UI测试说明 ===") - print() - print("现在可以测试存档界面显示效果:") - print("1. 运行主程序: python main.py") - print("2. 按 Ctrl+L 打开存档界面") - print("3. 验证能否看到10条存档(如果存档数量足够)") - print("4. 使用↑↓键测试所有存档是否可选择") - print() - print("预期结果:") - print("- 存档界面高度增加到300像素") - print("- 最多可显示约9-10条存档") - print("- 界面不会截断或重叠") - print("- 所有存档都可以正常选择和加载") - print() - -def cleanup_test_files(): - """清理测试文件""" - response = input("是否删除测试存档文件? (y/n): ") - if response.lower() == 'y': - print("\n=== 清理测试文件 ===") - for i in range(1, 13): - filename = f"saves/test_save_{i:02d}.json" - if os.path.exists(filename): - os.remove(filename) - print(f"删除: {filename}") - print("✅ 测试文件清理完成") - -def main(): - print("开始测试存档界面显示数量...") - - # 计算理论容量 - max_capacity = calculate_display_capacity() - - # 创建测试文件 - create_test_saves() - - # 检查存档列表 - save_count = check_save_list() - - print(f"\n=== 结果分析 ===") - print(f"理论最大显示容量: {max_capacity}条") - print(f"实际存档数量: {save_count}条") - - if max_capacity >= 10: - print("✅ 界面尺寸足够显示10条存档") - else: - print(f"❌ 界面尺寸只能显示{max_capacity}条存档") - - # UI测试说明 - test_ui_layout() - - # 可选清理 - cleanup_test_files() - -if __name__ == "__main__": - main() diff --git a/tests/test_save_ui_complete.py b/tests/test_save_ui_complete.py deleted file mode 100644 index 6a930e8..0000000 --- a/tests/test_save_ui_complete.py +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/env python3 -"""测试存档界面完整功能:显示10条存档,交互功能等""" - -import pygame -import sys -import os -import json - -# 添加项目根目录到路径 -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from config import * -from save_ui import SaveLoadUI -from maze import Maze - -def create_test_saves(): - """创建10个测试存档文件""" - print("创建测试存档文件...") - - # 确保saves目录存在 - os.makedirs("saves", exist_ok=True) - - # 创建10个不同的测试存档 - test_mazes = [ - {"rows": 5, "cols": 5, "name": "小迷宫5x5"}, - {"rows": 7, "cols": 7, "name": "中迷宫7x7"}, - {"rows": 10, "cols": 10, "name": "大迷宫10x10"}, - {"rows": 6, "cols": 8, "name": "矩形迷宫6x8"}, - {"rows": 8, "cols": 6, "name": "矩形迷宫8x6"}, - {"rows": 12, "cols": 12, "name": "超大迷宫12x12"}, - {"rows": 5, "cols": 10, "name": "长条迷宫5x10"}, - {"rows": 9, "cols": 9, "name": "正方迷宫9x9"}, - {"rows": 15, "cols": 15, "name": "巨型迷宫15x15"}, - {"rows": 7, "cols": 5, "name": "高窄迷宫7x5"} - ] - - created_files = [] - - for i, maze_info in enumerate(test_mazes): - filename = f"test_save_{i+1:02d}.json" - filepath = f"saves/{filename}" - - # 创建简单的迷宫数据 - rows, cols = maze_info["rows"], maze_info["cols"] - maze_data = [] - - for r in range(rows): - row = [] - for c in range(cols): - if r == 0 or r == rows-1 or c == 0 or c == cols-1: - row.append(1) # 边界是墙 - elif r == 1 and c == 1: - row.append(2) # 起点 - elif r == rows-2 and c == cols-2: - row.append(3) # 终点 - elif (r + c) % 3 == 0: - row.append(1) # 一些墙 - else: - row.append(0) # 通路 - maze_data.append(row) - - # 创建路径数据 - path_data = [ - {"x": 1, "y": 1, "step": 0}, - {"x": 2, "y": 1, "step": 1}, - {"x": cols-2, "y": rows-2, "step": 2} - ] - - # 保存数据 - save_data = { - "maze_info": { - "name": maze_info["name"], - "size": f"{rows}x{cols}", - "save_time": f"2024-01-{i+1:02d} {10+i}:00:00" - }, - "maze_data": maze_data, - "path_data": path_data, - "game_state": { - "path_step": 0, - "is_path_complete": False - } - } - - with open(filepath, 'w', encoding='utf-8') as f: - json.dump(save_data, f, indent=2, ensure_ascii=False) - - created_files.append(filepath) - print(f"创建存档: {filename} ({maze_info['name']})") - - print(f"总共创建了 {len(created_files)} 个测试存档文件") - return created_files - -def test_save_ui_complete(): - """测试存档界面完整功能""" - print("=== 测试存档界面完整功能 ===") - - # 创建测试存档 - test_files = create_test_saves() - - # 初始化pygame - pygame.init() - screen = pygame.display.set_mode((UI_WIDTH, UI_HEIGHT)) - pygame.display.set_caption("存档界面完整测试") - font = pygame.font.Font(FONT_FILE, FONT_SIZE) - - # 创建对象 - maze = Maze(wall_size=20, maze_size=200, file_name="test") - save_ui = SaveLoadUI(font) - - # 更新存档列表 - save_ui.update_save_list(maze) - save_ui.show_save_list = True - - print(f"检测到存档数量: {len(save_ui.save_list)}") - print(f"max_visible_saves设置: {save_ui.max_visible_saves}") - - # 显示前10个存档的信息 - for i, save_info in enumerate(save_ui.save_list[:10]): - print(f"{i+1:2d}. {save_info['name']} - {save_info['save_time']}") - - clock = pygame.time.Clock() - running = True - - print("\n交互测试:") - print("- ↑↓键: 选择存档") - print("- 回车键: 加载选中存档") - print("- Delete键: 删除选中存档") - print("- N键: 新建存档") - print("- ESC键: 退出") - print("- 鼠标: 点击选择,双击加载") - - while running: - for event in pygame.event.get(): - if event.type == pygame.QUIT: - running = False - elif event.type == pygame.KEYDOWN: - if event.key == pygame.K_ESCAPE: - running = False - else: - # 处理存档界面事件 - result = save_ui.handle_event(event, maze) - if result: - print(f"操作结果: {result}") - if result == "load_success": - print(f"成功加载存档,迷宫尺寸: {len(maze.grid)}x{len(maze.grid[0])}") - elif result == "delete_success": - print("存档删除成功") - save_ui.update_save_list(maze) - elif result == "save_success": - print("存档保存成功") - - elif event.type == pygame.MOUSEBUTTONDOWN: - result = save_ui.handle_event(event, maze) - if result: - print(f"鼠标操作结果: {result}") - - # 绘制 - screen.fill(COLOR_WHITE) - - # 绘制迷宫(如果已加载) - if hasattr(maze, 'grid') and maze.grid: - maze.draw(screen) - - # 绘制存档界面 - save_ui.draw(screen) - - # 绘制状态信息 - status_texts = [ - f"存档总数: {len(save_ui.save_list)}", - f"显示设置: 最多{save_ui.max_visible_saves}条", - f"当前选中: {save_ui.selected_save + 1 if save_ui.selected_save >= 0 else '无'}", - f"输入模式: {'是' if save_ui.input_active else '否'}" - ] - - for i, text in enumerate(status_texts): - text_surface = font.render(text, True, COLOR_BLACK) - screen.blit(text_surface, (10, 10 + i * 25)) - - pygame.display.flip() - clock.tick(60) - - pygame.quit() - - # 清理测试文件 - print("\n清理测试文件...") - for filepath in test_files: - try: - os.remove(filepath) - print(f"删除: {filepath}") - except FileNotFoundError: - pass - - print("测试完成") - -if __name__ == "__main__": - test_save_ui_complete() diff --git a/tests/test_save_ui_fix.py b/tests/test_save_ui_fix.py deleted file mode 100644 index f7703a9..0000000 --- a/tests/test_save_ui_fix.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -测试存档界面加载并生成路径功能 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -from maze import Maze -from SourceCollector import SourceCollector - -def test_load_via_save_ui(): - """测试通过存档界面加载存档并生成路径""" - print("=== 测试存档界面加载功能 ===\n") - - # 创建迷宫实例 - maze = Maze(wall_size=20, maze_size=400, file_name="test.csv") - - # 模拟存档界面的加载逻辑 - print("1. 模拟通过存档界面加载sample.json...") - save_file = "saves/sample.json" - - if os.path.exists(save_file): - # 执行加载 - if maze.load_game(save_file): - print("✓ 存档加载成功") - - # 模拟存档界面中的路径重新生成逻辑 - if maze.generater.maze: - maze.source_collector = SourceCollector(maze=maze.generater.maze) - maze.source_collector.run() - maze.full_path = maze.source_collector.get_path() - maze.path_step = 0 - maze.is_path_complete = False - maze.grid = maze.generater.maze - - print(f"✓ 路径重新生成成功") - print(f"迷宫大小: {maze.size}x{maze.size}") - print(f"路径长度: {len(maze.full_path)}") - print(f"路径前5步: {maze.full_path[:5]}") - print(f"路径后5步: {maze.full_path[-5:]}") - - # 验证起点和终点 - if maze.full_path: - start_pos = maze.full_path[0] - end_pos = maze.full_path[-1] - - # 检查起点是否为起点标记 - start_cell = maze.generater.maze[start_pos[0]][start_pos[1]] - end_cell = maze.generater.maze[end_pos[0]][end_pos[1]] - - print(f"路径起点: {start_pos}, 网格值: {start_cell}") - print(f"路径终点: {end_pos}, 网格值: {end_cell}") - - if start_cell == 's' and end_cell == 'e': - print("✓ 路径起点和终点验证正确") - else: - print("✗ 路径起点或终点验证失败") - return False - - return True - else: - print("✗ 迷宫数据无效") - return False - else: - print("✗ 存档加载失败") - return False - else: - print(f"✗ 文件不存在: {save_file}") - return False - -def test_multiple_saves(): - """测试加载多个不同的存档文件""" - print("\n=== 测试多个存档文件 ===\n") - - # 获取所有存档文件 - saves_dir = "saves" - if not os.path.exists(saves_dir): - print("saves目录不存在") - return False - - save_files = [f for f in os.listdir(saves_dir) if f.endswith('.json') or f.endswith('.csv')] - - if not save_files: - print("没有找到存档文件") - return False - - print(f"找到{len(save_files)}个存档文件:") - for save_file in save_files: - print(f"- {save_file}") - - # 测试加载每个文件 - results = [] - for save_file in save_files[:3]: # 只测试前3个文件 - print(f"\n测试加载: {save_file}") - - maze = Maze(wall_size=20, maze_size=400, file_name="test.csv") - full_path = os.path.join(saves_dir, save_file) - - if maze.load_game(full_path): - # 重新生成路径 - if maze.generater.maze: - maze.source_collector = SourceCollector(maze=maze.generater.maze) - maze.source_collector.run() - maze.full_path = maze.source_collector.get_path() - - print(f" ✓ 加载成功,路径长度: {len(maze.full_path)}") - results.append(True) - else: - print(f" ✗ 迷宫数据无效") - results.append(False) - else: - print(f" ✗ 加载失败") - results.append(False) - - success_count = sum(results) - print(f"\n测试结果: {success_count}/{len(results)} 个文件加载成功") - return success_count == len(results) - -if __name__ == "__main__": - success1 = test_load_via_save_ui() - success2 = test_multiple_saves() - - print(f"\n=== 总体测试结果 ===") - print(f"存档界面加载测试: {'成功' if success1 else '失败'}") - print(f"多文件加载测试: {'成功' if success2 else '失败'}") - - if success1 and success2: - print("✓ 所有测试通过!存档界面现在会正确重新生成路径。") - else: - print("✗ 部分测试失败,需要进一步检查。") diff --git a/tests/test_start_button_multiple_clicks.py b/tests/test_start_button_multiple_clicks.py deleted file mode 100644 index f0a033e..0000000 --- a/tests/test_start_button_multiple_clicks.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python3 -""" -快速测试主程序的Start按钮多次点击功能 -这个脚本模拟用户快速点击Start按钮的情况 -""" - -import sys -import os -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -print("=== Start按钮多次点击测试 ===") -print() -print("此测试将启动主程序。请按以下步骤测试:") -print() -print("1. 程序启动后,点击 [Start] 按钮生成第一个迷宫") -print("2. 观察历史步数和路径长度信息") -print("3. 点击 [历史模式] 按钮,进入历史展示模式") -print("4. 使用历史控制按钮前进几步") -print("5. 再次点击 [Start] 按钮生成第二个迷宫") -print("6. 验证:") -print(" - 历史步数应该是新的(不是之前的累加)") -print(" - 应该自动切换回路径模式") -print(" - 历史步骤应该重置为0") -print(" - 所有播放状态应该停止") -print("7. 可以重复步骤1-6多次验证") -print() -print("预期结果:") -print("- 每次点击Start后,控制台会显示'所有状态已重置'") -print("- 每次生成的历史步数是独立的新数据") -print("- 不会出现历史数据累加或状态混乱") -print("- UI应该正确显示当前模式和步数") -print() - -input("按 Enter 键启动程序进行测试...") - -try: - import main -except KeyboardInterrupt: - print("\n测试完成,程序已退出") -except Exception as e: - print(f"\n程序运行出现错误: {str(e)}") - print("请检查相关代码和依赖")