Skip to content

Commit f3bb287

Browse files
authored
Game_of_Fifteen.py
1 parent c0b68a7 commit f3bb287

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Game of Fifteen/Game_of_Fifteen.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import random
2+
3+
def create_board():
4+
numbers = list(range(1, 16))
5+
random.shuffle(numbers)
6+
numbers.append(None)
7+
8+
board = [numbers[i:i+4] for i in range(0, 16, 4)]
9+
return board
10+
11+
def display_board(board):
12+
for row in board:
13+
print(' | '.join(str(num).rjust(2) if num is not None else ' ' for num in row))
14+
print('-' * 23)
15+
16+
def get_empty_position(board):
17+
for i in range(4):
18+
for j in range(4):
19+
if board[i][j] is None:
20+
return i, j
21+
22+
def is_valid_move(move, empty_row, empty_col):
23+
row, col = move
24+
return (0 <= row < 4 and 0 <= col < 4 and
25+
(row == empty_row and abs(col - empty_col) == 1 or
26+
col == empty_col and abs(row - empty_row) == 1))
27+
28+
def make_move(board, move):
29+
empty_row, empty_col = get_empty_position(board)
30+
row, col = move
31+
board[empty_row][empty_col], board[row][col] = board[row][col], board[empty_row][empty_col]
32+
33+
def check_win(board):
34+
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+
36+
def game_of_fifteen():
37+
board = create_board()
38+
39+
print("Welcome to the Game of Fifteen!")
40+
print("Arrange the numbers in numerical order by sliding the tiles.")
41+
print("Enter 'Q' to quit.")
42+
43+
while not check_win(board):
44+
display_board(board)
45+
move = input("Enter the number you want to move (1-15) or 'Q' to quit: ")
46+
47+
if move.lower() == 'q':
48+
print("Quitting the game...")
49+
break
50+
51+
if not move.isdigit() or int(move) not in range(1, 16):
52+
print("Invalid input. Please enter a number from 1 to 15.")
53+
continue
54+
55+
move = int(move)
56+
empty_row, empty_col = get_empty_position(board)
57+
58+
moves = [(empty_row - 1, empty_col), (empty_row + 1, empty_col),
59+
(empty_row, empty_col - 1), (empty_row, empty_col + 1)]
60+
61+
if any(is_valid_move(move, row, col) for row, col in moves):
62+
make_move(board, (empty_row, empty_col))
63+
else:
64+
print("Invalid move. Try again.")
65+
66+
if check_win(board):
67+
print("Congratulations! You solved the puzzle.")
68+
69+
if __name__ == "__main__":
70+
game_of_fifteen()

0 commit comments

Comments
 (0)