11import random
22
3+
34def create_board ():
45 numbers = list (range (1 , 16 ))
56 random .shuffle (numbers )
@@ -8,31 +9,38 @@ def create_board():
89 board = [numbers [i :i + 4 ] for i in range (0 , 16 , 4 )]
910 return board
1011
12+
1113def display_board (board ):
1214 for row in board :
13- print (' | ' .join (str (num ).rjust (2 ) if num is not None else ' ' for num in row ))
15+ print (' | ' .join (str (num ).rjust (2 )
16+ if num is not None else ' ' for num in row ))
1417 print ('-' * 23 )
1518
19+
1620def get_empty_position (board ):
1721 for i in range (4 ):
1822 for j in range (4 ):
1923 if board [i ][j ] is None :
2024 return i , j
2125
26+
2227def is_valid_move (move , empty_row , empty_col ):
2328 row , col = move
2429 return (0 <= row < 4 and 0 <= col < 4 and
2530 (row == empty_row and abs (col - empty_col ) == 1 or
26- col == empty_col and abs (row - empty_row ) == 1 ))
31+ col == empty_col and abs (row - empty_row ) == 1 ))
32+
2733
2834def make_move (board , move ):
2935 empty_row , empty_col = get_empty_position (board )
3036 row , col = move
3137 board [empty_row ][empty_col ], board [row ][col ] = board [row ][col ], board [empty_row ][empty_col ]
3238
39+
3340def check_win (board ):
3441 return all (board [i ][j ] == i * 4 + j + 1 for i in range (4 ) for j in range (4 )) and board [3 ][3 ] is None
3542
43+
3644def game_of_fifteen ():
3745 board = create_board ()
3846
@@ -42,7 +50,8 @@ def game_of_fifteen():
4250
4351 while not check_win (board ):
4452 display_board (board )
45- move = input ("Enter the number you want to move (1-15) or 'Q' to quit: " )
53+ move = input (
54+ "Enter the number you want to move (1-15) or 'Q' to quit: " )
4655
4756 if move .lower () == 'q' :
4857 print ("Quitting the game..." )
@@ -66,5 +75,6 @@ def game_of_fifteen():
6675 if check_win (board ):
6776 print ("Congratulations! You solved the puzzle." )
6877
78+
6979if __name__ == "__main__" :
7080 game_of_fifteen ()
0 commit comments