maze_python/tests/test_save_ui_complete.py

197 lines
6.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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()