-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaveSystem.py
More file actions
253 lines (217 loc) · 9.42 KB
/
SaveSystem.py
File metadata and controls
253 lines (217 loc) · 9.42 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
import json
import os
from PyQt5.QtGui import QColor
from Items import Items
def save_game(game, filename="SavedGame.json"):
"""
保存当前游戏状态到 JSON 文件。
参数:
game: QLinkGame 实例,包含当前游戏的所有状态(地图、玩家、道具等)。
filename: 保存文件名,默认为 "SavedGame.json"。
功能:
- 序列化游戏地图、玩家、所有方块、道具、提示等信息为字典。
- 将字典以 JSON 格式写入指定文件。
返回值:
无(直接写文件)。
"""
game_map = game.gameMap # QLinkGame.gameMap
data = {}
# 1. 地图与游戏数据
data['game_type'] = game.gameType
data['box_row'] = game_map.boxRow
data['box_col'] = game_map.boxCol
data['box_width'] = game_map.boxWidth
data['box_height'] = game_map.boxHeight
data['end_of_game'] = game_map.endOfGame
data['seconds'] = game_map.seconds
data['hint_status'] = game_map.hintStatus
data['game_pause'] = game_map.gamePause
data['hint_seconds'] = game_map.hintSeconds
# 2. 玩家数据
def serialize_player(player):
if player is None:
return None
return {
'player_type': player.playerType,
'x': player.playerX,
'y': player.playerY,
'width': player.playerWidth,
'height': player.playerHeight,
'speed': player.playerSpeed,
'box_select_pass': player.boxSelectPass,
'print_text_status': player.printTextStatus,
'remove_two_box': player.removeTwoBox,
'score': player.score,
'current_selected': [tuple(sel) for sel in player.currentSelected],
'line_path': [tuple(p) for p in player.linePath],
}
data['player1'] = serialize_player(game.player1)
if data['game_type'] == 2:
data['player2'] = serialize_player(game.player2)
# 3. 所有箱子
data['boxes'] = []
for i in range(game_map.boxRow):
for j in range(game_map.boxCol):
box = game_map.boxMap[i][j]
box_data = {
'box_type': getattr(box, "boxType", 0),
'left_top_x': getattr(box, "leftTopX", 0),
'left_top_y': getattr(box, "leftTopY", 0),
'box_width': getattr(box, "boxWidth", 0),
'box_height': getattr(box, "boxHeight", 0),
'edge_len': getattr(box, "edgeLen", 0),
'box_color': box.boxColor.name() if isinstance(box.boxColor, QColor) else str(box.boxColor),
'is_selected': getattr(box, "isSelected", False),
'is_removed': getattr(box, "isRemoved", False),
'hint_status': getattr(box, "isHinted", False),
'paint_removed' : getattr(box, "paintRemoved", False),
'box_row': getattr(box, "boxRow", i),
'box_col': getattr(box, "boxCol", j),
}
data['boxes'].append(box_data)
# 4. hintBox —— 适配为元组列表
data['hint_box'] = []
if game_map.hintBox is not None:
for pos in game_map.hintBox:
if isinstance(pos, tuple) and len(pos) == 2:
data['hint_box'].append(tuple(pos))
elif hasattr(pos, "boxRow") and hasattr(pos, "boxCol"):
data['hint_box'].append((pos.boxRow, pos.boxCol))
else:
# 跳过或raise
pass
# 5. 道具数目
data['type_item_num'] = list(game_map.typeItemNum)
# 6. 道具容器
data['items'] = []
for item in game_map.items:
item_data = {
'item_type': getattr(item, "itemtype", 0),
'item_width': getattr(item, "width", 0),
'item_height': getattr(item, "height", 0),
'item_x': getattr(item, "leftTopX", 0),
'item_y': getattr(item, "leftTopY", 0),
'item_row': getattr(item, "itemRow", 0),
'item_col': getattr(item, "itemCol", 0),
'item_color': item.itemColor.name() if isinstance(item.itemColor, QColor) else str(item.itemColor),
'is_removed': getattr(item, "isRemoved", False)
}
data['items'].append(item_data)
# 保存为JSON
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def load_game(parent, filename="SavedGame.json"):
"""
从 JSON 文件加载游戏状态,恢复为 QLinkGame 实例。
参数:
parent: 父级 QWidget,一般为主窗口或页面。
filename: 存档文件名,默认为 "SavedGame.json"。
功能:
- 检查存档文件是否存在。
- 读取 JSON 文件,反序列化为字典。
- 创建新的 QLinkGame 实例,并恢复地图、玩家、方块、道具等所有状态。
返回值:
QLinkGame 实例(恢复后的游戏对象),若失败返回 None。
"""
if not is_save_exist(filename):
print("not exist")
return None
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
from QLinkGame import QLinkGame
print("start loading")
# 1. 新建 QLinkGame 实例,参数来自存档
row = data['box_row']
col = data['box_col']
game_type = data['game_type']
game = QLinkGame(row, col, game_type, parent)
game_map = game.gameMap
print("create original gameMap done")
# 2. 恢复 GameMap 基础属性
game_map.boxWidth = data['box_width']
game_map.boxHeight = data['box_height']
game_map.endOfGame = data['end_of_game']
game_map.seconds = data['seconds']
game_map.hintStatus = data['hint_status']
game_map.gamePause = data['game_pause']
game_map.gameType = data['game_type']
game_map.hintSeconds = data['hint_seconds']
print("load gameMap basic done")
# 3. 恢复 Player 属性
def deserialize_player(player, pdata):
if player is None or pdata is None:
return
player.playerType = pdata['player_type']
player.playerX = pdata['x']
player.playerY = pdata['y']
player.playerWidth = pdata['width']
player.playerHeight = pdata['height']
player.playerSpeed = pdata['speed']
player.boxSelectPass = pdata['box_select_pass']
player.printTextStatus = pdata['print_text_status']
player.removeTwoBox = pdata['remove_two_box']
player.score = pdata['score']
player.currentSelected = [tuple(rc) for rc in pdata['current_selected']]
player.linePath = [tuple(xy) for xy in pdata['line_path']]
deserialize_player(game.player1, data['player1'])
if game_type == 2 and 'player2' in data:
deserialize_player(game.player2, data['player2'])
print("load player done")
# 4. 恢复所有 Box
boxes = data['boxes']
idx = 0
for i in range(game_map.boxRow):
for j in range(game_map.boxCol):
box_data = boxes[idx]
box = game_map.boxMap[i][j]
box.boxType = box_data['box_type']
box.leftTopX = box_data['left_top_x']
box.leftTopY = box_data['left_top_y']
box.boxWidth = box_data['box_width']
box.boxHeight = box_data['box_height']
box.edgeLen = box_data['edge_len']
box.boxColor = QColor(box_data['box_color'])
box.isSelected = box_data['is_selected']
box.isRemoved = box_data['is_removed']
box.isHinted = box_data['hint_status']
box.paintRemoved = box_data['paint_removed']
box.boxRow = box_data['box_row']
box.boxCol = box_data['box_col']
box.updateBox()
idx += 1
#print("load boxes done")
# 5. 恢复 hintBox
game_map.hintBox = []
for row_col in data['hint_box']:
game_map.hintBox.append(tuple(row_col))
#print("load hintbox done")
# 6. 恢复 typeItemNum
game_map.typeItemNum = list(data['type_item_num'])
#print("load typeItemNum done")
# 7. 恢复 items
game_map.items = []
for item_data in data['items']:
item = Items(
item_data['item_type'],
item_data['item_row'], item_data['item_col'],
item_data['item_x'], item_data['item_y'],
item_data['item_width'], item_data['item_height'],
)
item.itemColor = QColor(item_data['item_color'])
item.isRemoved = item_data['is_removed']
game_map.items.append(item)
#print("load items done")
return game
except Exception as e:
print("Load failed:", e)
return None
def is_save_exist(filename="SavedGame.json"):
"""
检查指定存档文件是否存在且非空。
参数:
filename: 存档文件名,默认为 "SavedGame.json"。
返回值:
bool,存在且非空返回 True,否则返回 False。
"""
return os.path.isfile(filename) and os.path.getsize(filename) > 0