1
1
import random
2
2
3
+
3
4
def create_board ():
4
5
numbers = list (range (1 , 16 ))
5
6
random .shuffle (numbers )
@@ -8,31 +9,38 @@ def create_board():
8
9
board = [numbers [i :i + 4 ] for i in range (0 , 16 , 4 )]
9
10
return board
10
11
12
+
11
13
def display_board (board ):
12
14
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 ))
14
17
print ('-' * 23 )
15
18
19
+
16
20
def get_empty_position (board ):
17
21
for i in range (4 ):
18
22
for j in range (4 ):
19
23
if board [i ][j ] is None :
20
24
return i , j
21
25
26
+
22
27
def is_valid_move (move , empty_row , empty_col ):
23
28
row , col = move
24
29
return (0 <= row < 4 and 0 <= col < 4 and
25
30
(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
+
27
33
28
34
def make_move (board , move ):
29
35
empty_row , empty_col = get_empty_position (board )
30
36
row , col = move
31
37
board [empty_row ][empty_col ], board [row ][col ] = board [row ][col ], board [empty_row ][empty_col ]
32
38
39
+
33
40
def check_win (board ):
34
41
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
35
42
43
+
36
44
def game_of_fifteen ():
37
45
board = create_board ()
38
46
@@ -42,7 +50,8 @@ def game_of_fifteen():
42
50
43
51
while not check_win (board ):
44
52
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: " )
46
55
47
56
if move .lower () == 'q' :
48
57
print ("Quitting the game..." )
@@ -66,5 +75,6 @@ def game_of_fifteen():
66
75
if check_win (board ):
67
76
print ("Congratulations! You solved the puzzle." )
68
77
78
+
69
79
if __name__ == "__main__" :
70
80
game_of_fifteen ()
0 commit comments