-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveHistoryUpdatedVersion.py
More file actions
323 lines (251 loc) · 10.2 KB
/
MoveHistoryUpdatedVersion.py
File metadata and controls
323 lines (251 loc) · 10.2 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
import tkinter as tk
from tkinter import messagebox
import random
# ====================
# GRAPH IMPLEMENTATION
# ====================
class GraphNode:
"""Represents a single grid cell in the puzzle"""
def __init__(self, label, row, col, arrow_direction):
self.label = label
self.row = row
self.col = col
self.arrow_direction = arrow_direction
self.visited = False
self.visit_order = None
class PuzzleGraph:
"""Graph representation using adjacency list"""
def __init__(self):
self.nodes = {}
self.adjacency_list = {}
self.solution_path = []
def add_node(self, label, row, col, arrow_direction):
self.nodes[label] = GraphNode(label, row, col, arrow_direction)
self.adjacency_list[label] = []
def add_edge(self, from_label, to_label):
if from_label in self.adjacency_list:
self.adjacency_list[from_label].append(to_label)
def get_neighbors(self, label):
return self.adjacency_list.get(label, [])
def set_solution_path(self, path):
self.solution_path = path
# ====================
# GAME LOGIC
# ====================
class GameState:
def __init__(self, graph):
self.graph = graph
self.current_position = 'A'
self.current_turn = 'Human'
self.visit_count = 1
self.human_correct_moves = 0
self.human_illegal_moves = 0
self.cpu_correct_moves = 0
self.cpu_illegal_moves = 0
self.cpu_illegal_history = set()
self.graph.nodes['A'].visited = True
self.graph.nodes['A'].visit_order = 1
self.game_over = False
self.winner = None
def is_legal_move(self, target):
if target not in self.graph.get_neighbors(self.current_position):
return False
if self.graph.nodes[target].visited:
return False
return True
def is_correct_move(self, target):
try:
idx = self.graph.solution_path.index(self.current_position)
return self.graph.solution_path[idx + 1] == target
except:
return False
def make_move(self, target):
if self.game_over:
return False, False
legal = self.is_legal_move(target)
correct = self.is_correct_move(target)
if not legal or not correct:
if self.current_turn == 'Human':
self.human_illegal_moves += 1
else:
self.cpu_illegal_moves += 1
self.cpu_illegal_history.add((self.current_position, target))
self.switch_turn()
return False, False
self.visit_count += 1
node = self.graph.nodes[target]
node.visited = True
node.visit_order = self.visit_count
self.current_position = target
if self.current_turn == 'Human':
self.human_correct_moves += 1
else:
self.cpu_correct_moves += 1
if target == 'P':
self.game_over = True
self.determine_winner()
self.switch_turn()
return True, True
def switch_turn(self):
self.current_turn = 'CPU' if self.current_turn == 'Human' else 'Human'
def determine_winner(self):
if self.human_illegal_moves < self.cpu_illegal_moves:
self.winner = 'Human'
elif self.cpu_illegal_moves < self.human_illegal_moves:
self.winner = 'CPU'
else:
self.winner = 'Draw'
# ====================
# CPU PLAYER
# ====================
class GreedyCPU:
def __init__(self, graph, game_state):
self.graph = graph
self.game_state = game_state
def distance_to_goal(self, label):
node = self.graph.nodes[label]
goal = self.graph.nodes['P']
return abs(node.row - goal.row) + abs(node.col - goal.col)
def get_best_move(self):
current = self.game_state.current_position
neighbors = self.graph.get_neighbors(current)
history = self.game_state.cpu_illegal_history
primary = [
n for n in neighbors
if not self.graph.nodes[n].visited
and (current, n) not in history
]
fallback = [n for n in neighbors if not self.graph.nodes[n].visited]
candidates = primary or fallback or neighbors
if not candidates:
return random.choice(list(self.graph.nodes.keys()))
return min(candidates, key=self.distance_to_goal)
# ====================
# GUI
# ====================
class PuzzleGameGUI:
def __init__(self, root):
self.root = root
self.root.title("Arrow Grid Puzzle - Human vs CPU")
self.graph = self.create_fixed_puzzle()
self.game_state = GameState(self.graph)
self.cpu_player = GreedyCPU(self.graph, self.game_state)
self.buttons = {}
self.create_gui()
self.update_display()
def create_fixed_puzzle(self):
graph = PuzzleGraph()
grid = [
('A',0,0,'↘'),('B',0,1,'↘'),('C',0,2,'↙'),('D',0,3,'←'),
('E',1,0,'↗'),('F',1,1,'→'),('G',1,2,'←'),('H',1,3,'←'),
('I',2,0,'→'),('J',2,1,'↙'),('K',2,2,'↖'),('L',2,3,'↑'),
('M',3,0,'→'),('N',3,1,'→'),('O',3,2,'→'),('P',3,3,'★')
]
for l,r,c,a in grid:
graph.add_node(l,r,c,a)
edges = [
('A','E'),('A','K'),('K','G'),('K','F'),('F','G'),('F','H'),
('H','G'),('G','F'),('G','E'),('E','B'),('E','A'),('B','F'),
('B','L'),('L','H'),('L','D'),('D','C'),('C','G'),('C','I'),
('I','J'),('J','N'),('J','M'),('M','N'),('N','O'),('O','P')
]
for u,v in edges:
graph.add_edge(u,v)
graph.set_solution_path(
['A','K','F','H','G','E','B','L','D','C','I','J','M','N','O','P']
)
return graph
def create_gui(self):
tk.Label(self.root, text="Arrow Grid Puzzle Game",
font=('Arial',16,'bold')).grid(row=0,column=0,columnspan=3,pady=10)
grid_frame = tk.Frame(self.root)
grid_frame.grid(row=1,column=0,padx=20)
for label,node in self.graph.nodes.items():
btn = tk.Button(
grid_frame,
text=f"{label}\n{node.arrow_direction}",
width=8, height=4,
command=lambda l=label: self.on_cell_click(l)
)
btn.grid(row=node.row,column=node.col,padx=2,pady=2)
self.buttons[label] = btn
self.history = tk.Text(self.root, width=28, height=18)
self.history.grid(row=1,column=1,padx=10)
self.history.tag_config("legal", foreground="green")
self.history.tag_config("illegal", foreground="red")
self.history.insert(tk.END,"MOVE HISTORY\n\n")
self.history.config(state="disabled")
info = tk.Frame(self.root)
info.grid(row=2,column=0,columnspan=2,pady=10)
self.turn_label = tk.Label(info,font=('Arial',12,'bold'))
self.turn_label.grid(row=0,column=0,columnspan=2)
self.human_stats = tk.Label(info)
self.cpu_stats = tk.Label(info)
self.human_stats.grid(row=1,column=0,padx=10)
self.cpu_stats.grid(row=1,column=1,padx=10)
self.position_label = tk.Label(info)
self.position_label.grid(row=2,column=0,columnspan=2)
def log(self, text, tag):
self.history.config(state="normal")
self.history.insert(tk.END, text + "\n", tag)
self.history.config(state="disabled")
self.history.see(tk.END)
def flash_illegal(self, label):
self.buttons[label].config(bg="red")
self.root.after(800, self.update_display)
def on_cell_click(self, label):
if self.game_state.current_turn != 'Human' or self.game_state.game_over:
return
success,_ = self.game_state.make_move(label)
if success:
self.log(f"Human → {label}", "legal")
else:
self.log(f"Human illegal → {label}", "illegal")
self.flash_illegal(label)
self.update_display()
if self.game_state.game_over:
self.show_winner()
else:
self.root.after(800, self.cpu_turn)
def cpu_turn(self):
if self.game_state.game_over:
return
move = self.cpu_player.get_best_move()
success,_ = self.game_state.make_move(move)
if success:
self.log(f"CPU → {move}", "legal")
else:
self.log(f"CPU illegal → {move}", "illegal")
self.flash_illegal(move)
self.update_display()
if self.game_state.game_over:
self.show_winner()
def update_display(self):
for label,node in self.graph.nodes.items():
btn = self.buttons[label]
if node.visited:
btn.config(text=f"{node.visit_order}\n{node.arrow_direction}", bg="lightgreen")
else:
btn.config(text=f"{label}\n{node.arrow_direction}", bg="SystemButtonFace")
if label == self.game_state.current_position:
btn.config(bg="yellow")
self.turn_label.config(text=f"Current Turn: {self.game_state.current_turn}")
self.human_stats.config(
text=f"Human\nCorrect: {self.game_state.human_correct_moves}\nIllegal: {self.game_state.human_illegal_moves}"
)
self.cpu_stats.config(
text=f"CPU\nCorrect: {self.game_state.cpu_correct_moves}\nIllegal: {self.game_state.cpu_illegal_moves}"
)
order = self.graph.nodes[self.game_state.current_position].visit_order
self.position_label.config(
text=f"Current Position: {self.game_state.current_position} (Grid {order})"
)
def show_winner(self):
messagebox.showinfo("Game Over", f"Winner: {self.game_state.winner}")
# ====================
# MAIN
# ====================
if __name__ == "__main__":
root = tk.Tk()
PuzzleGameGUI(root)
root.mainloop()