-
Notifications
You must be signed in to change notification settings - Fork 0
/
puzzle.py
317 lines (278 loc) · 11.7 KB
/
puzzle.py
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
import pygame , random , sys , heapq
#COULEURS
WHITE = (255,255,255)
BLACK = (0,0,0)
NEON = (26, 192, 207)
#CONTANTES
WIDTH , HEIGHT = 1000 , 600
FPS = 60
GAME_SIZE = 3
TILE_SIZE = 200
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Define a font and create a surface with the message
pygame.font.init()
font = pygame.font.SysFont(None, 50)
win_message = font.render("Congratulations! You won!", True, BLACK)
win_message_rect = win_message.get_rect(center=(WIDTH // 3, HEIGHT // 4))
#load all images
Shuffle_Button = pygame.image.load("assets/SHUFFLEBUTTON.png")
Reset_Button = pygame.image.load("assets/reset.png")
BFS_Button = pygame.image.load("assets/bfs.png")
A_etoile = pygame.image.load("assets/A_etoile.png")
Play_button = pygame.image.load("assets/play_button.png")
TITLE = pygame.image.load("assets/title.png")
message = pygame.image.load("assets/reset_message.png")
image1 = pygame.image.load("assets/1.png")
image2 = pygame.image.load("assets/2.png")
image3 = pygame.image.load("assets/3.png")
image4 = pygame.image.load("assets/4.png")
image5 = pygame.image.load("assets/5.png")
image6 = pygame.image.load("assets/6.png")
image7 = pygame.image.load("assets/7.png")
image8 = pygame.image.load("assets/8.png")
empty_image = pygame.image.load("assets/empty.png")
images={0:empty_image, 1:image1, 2:image2, 3:image3, 4:image4, 5:image5, 6:image6, 7:image7, 8:image8}
#load sound effect
pygame.mixer.init()
win_sfx = pygame.mixer.Sound("sound_effects/Winning_Sound_Effect.mp3")
class Button:
def __init__(self, image, position):
self.image = image
self.rect = self.image.get_rect(topleft=position)
def draw(self, screen):
screen.blit(self.image, self.rect)
def is_clicked(self, mouse_pos):
#check if left mouse button is clicked on button
return self.rect.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0] == 1
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("8-puzzle game")
self.clock = pygame.time.Clock()
self.player_grid = self.create_grid()
self.completed_grid = self.create_grid()
self.shuffle_once = False
self.shuffled_grids = []
def create_grid(self):
GRID = []
CELL_NUM = 1
for row in range(GAME_SIZE):
GRID.append([])
for col in range(GAME_SIZE):
GRID[row].append(CELL_NUM)
CELL_NUM += 1
GRID[2][2] = 0
return GRID
def draw_grid(self):
for horz_line in range(-1,GAME_SIZE * TILE_SIZE , TILE_SIZE):
pygame.draw.line(screen , BLACK , (horz_line,0) , (horz_line,GAME_SIZE * TILE_SIZE))
for vert_line in range(-1,GAME_SIZE * TILE_SIZE, TILE_SIZE):
pygame.draw.line(screen, BLACK,(0,vert_line),(GAME_SIZE * TILE_SIZE ,vert_line))
def draw_tiles(self):
for row , list_row in enumerate(self.player_grid):
for col , element in enumerate(list_row):
for i in (images.keys()):
if element == i:
self.rect = images[i].get_rect()
self.update(row ,col)
screen.blit(images[i],(self.rect.y,self.rect.x))
def update(self , x , y):
self.rect.x = x * TILE_SIZE
self.rect.y = y * TILE_SIZE
def valid_move(self , row , col):
empty_x , empty_y = self.find_empty_tile(self.player_grid)
return (row == empty_x and abs(col - empty_y) == 1) or (col == empty_y and abs(row - empty_x) == 1)
def clicked_tile(self,mouse_x , mouse_y):
x = mouse_y // TILE_SIZE
y = mouse_x // TILE_SIZE
return x , y
def find_empty_tile(self , grid):
for x , list_row in enumerate(grid):
for y , element in enumerate(list_row):
if element == 0:
return x , y
def handle_move(self , tile_x , tile_y):
empty_x , empty_y = self.find_empty_tile(self.player_grid)
if self.valid_move(tile_x , tile_y):
self.player_grid[empty_x][empty_y] = self.player_grid[tile_x][tile_y]
self.player_grid[tile_x][tile_y] = 0
draw_all()
def shuffle(self):
reset_button.image = Reset_Button
for i in range(99):
empty_x , empty_y = self.find_empty_tile(self.player_grid)
directions = [(empty_x + 1 , empty_y),(empty_x - 1 , empty_y),(empty_x , empty_y + 1),(empty_x , empty_y - 1)]
valid_moves = [(x , y) for x , y in directions if 0 <= x <= 2 and 0 <= y <= 2]
next_x , next_y = random.choice(valid_moves)
self.handle_move(next_x , next_y)
self.shuffle_once = True
shuffle_grid = [row[:] for row in self.player_grid]
self.shuffled_grids.append(shuffle_grid)
def win(self):
return self.player_grid == self.completed_grid
def reset(self):
if self.shuffle_once:
if self.shuffled_grids == []:
reset_button.image = message
else:
self.player_grid = self.shuffled_grids[0]
self.shuffled_grids = []
def a_etoile_solution(self):
current_grid = [row[:] for row in self.player_grid]
depth = 0
visited = set()
priority_queue = [(self.evaluate_state2(current_grid , depth), current_grid, [])]
while priority_queue:
_, grid , path = heapq.heappop(priority_queue)
visited.add(tuple(map(tuple, grid)))
if self.evaluate_state(grid) == 0:
return path
neighbors = self.generate_grids(grid)
depth += 1
for neighbor in neighbors:
if tuple(map(tuple, neighbor)) not in visited:
heapq.heappush(priority_queue, (self.evaluate_state2(neighbor , depth), neighbor , path+[neighbor]))
return None
def bfs_solution(self):
current_grid = [row[:] for row in self.player_grid]
visited = set()
priority_queue = [(self.evaluate_state(current_grid), current_grid, [])]
while priority_queue:
_, grid , path = heapq.heappop(priority_queue)
visited.add(tuple(map(tuple, grid))) # Convertir la grille en tuple pour vérifier la visite
if self.evaluate_state(grid) == 0:
return path
neighbors = self.generate_grids(grid)
for neighbor in neighbors:
if tuple(map(tuple, neighbor)) not in visited:
heapq.heappush(priority_queue, (self.evaluate_state(neighbor), neighbor , path+[neighbor]))
return None
def evaluate_state(self, state):
# Fonction d'évaluation : retourne le nombre de tuiles mal placées
nbre_unplaced_tiles = 0
for i in range(GAME_SIZE):
for j in range(GAME_SIZE):
if state[i][j] != self.completed_grid[i][j]:
nbre_unplaced_tiles += 1
return nbre_unplaced_tiles
def evaluate_state2(self, state , depth):
nbre_unplaced_tiles = 0
for i in range(GAME_SIZE):
for j in range(GAME_SIZE):
if state[i][j] != self.completed_grid[i][j]:
nbre_unplaced_tiles += 1
return nbre_unplaced_tiles + depth
def generate_grids(self, grid):
neighbors = []
empty_x, empty_y = self.find_empty_tile(grid)
directions = [(empty_x + 1, empty_y), (empty_x - 1, empty_y), (empty_x, empty_y + 1), (empty_x, empty_y - 1)]
for next_x, next_y in directions:
if 0 <= next_x < GAME_SIZE and 0 <= next_y < GAME_SIZE:
new_grid = [row[:] for row in grid]
new_grid[empty_x][empty_y], new_grid[next_x][next_y] = new_grid[next_x][next_y], new_grid[empty_x][empty_y]
neighbors.append(new_grid)
return neighbors
#Create buttons
shuffle_button = Button(Shuffle_Button, (WIDTH - 300, HEIGHT - 575))
reset_button = Button(Reset_Button, (WIDTH - 300, HEIGHT - 425))
bfs_button = Button(BFS_Button, (WIDTH - 300, HEIGHT - 275))
a_etoile_button = Button(A_etoile, (WIDTH - 300, HEIGHT - 125))
play_button = Button(Play_button, (WIDTH //2 - 100, HEIGHT //2 - 50))
def draw_buttons():
shuffle_button.draw(screen)
reset_button.draw(screen)
bfs_button.draw(screen)
a_etoile_button.draw(screen)
def draw_all():
screen.fill(NEON)
game.draw_tiles()
game.draw_grid()
draw_buttons()
def main_menu():
screen.fill(NEON)
title_rect = TITLE.get_rect()
title_rect.x = WIDTH//2 - 300
while True:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x , mouse_y = pygame.mouse.get_pos()
mouse_pos = (mouse_x,mouse_y)
if play_button.is_clicked(mouse_pos):
return True
play_button.draw(screen)
screen.blit(TITLE,title_rect )
pygame.display.update()
#GAME LOOP
run = main_menu()
moves = 0
game = Game()
game.shuffle()
sound_is_played = False
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x , mouse_y = pygame.mouse.get_pos()
mouse_pos = (mouse_x,mouse_y)
clicked_x , clicked_y = game.clicked_tile(mouse_x , mouse_y)
if shuffle_button.is_clicked(mouse_pos):
moves = 0
game.shuffle()
sound_is_played = False
elif reset_button.is_clicked(mouse_pos):
moves = 0
game.reset()
sound_is_played = False
elif bfs_button.is_clicked(mouse_pos):
win_path = game.bfs_solution()
if win_path:
for i , grid_step in enumerate(win_path):
game.player_grid = grid_step
moves = i + 1
print("move n°",moves)
for row in grid_step:
print(row)
draw_all()
pygame.display.update()
pygame.time.wait(500)
else:
print("Aucune solution trouvée.")
elif a_etoile_button.is_clicked(mouse_pos):
win_path = game.a_etoile_solution()
if win_path:
for i , grid_step in enumerate(win_path):
game.player_grid = grid_step
moves = i + 1
print("move n°",moves)
for row in grid_step:
print(row)
draw_all()
pygame.display.update()
pygame.time.wait(500)
else:
print("Aucune solution trouvée.")
else:
if pygame.mouse.get_pressed()[0] == 1 and not game.win():
game.handle_move(clicked_x, clicked_y)
moves += 1
if game.win():
screen.fill(NEON)
shuffle_button.draw(screen)
reset_button.draw(screen)
screen.blit(win_message, win_message_rect)
moves_text = font.render(f"Moves: {moves}", True, BLACK)
moves_rect = moves_text.get_rect(midtop=(WIDTH // 3, HEIGHT // 2))
screen.blit(moves_text, moves_rect)
if sound_is_played == False:
win_sfx.play()
sound_is_played = True
else:
draw_all()
game.clock.tick(FPS)
pygame.display.update()