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
| import random
import re
import sys
def display_intro():
"""Show welcome message."""
print("Welcome to the Sliding Puzzle Game!")
print("Instructions: Slide the number tiles to the empty position to solve the puzzle.")
print()
def validate_input(user_input):
"""Check if the input for moves is valid."""
user_input = re.sub(r'\s+', '', user_input).lower()
if len(user_input) != len(set(user_input)):
return False
if len(user_input) != 4:
return False
if not user_input.isalpha():
return False
return True
def generate_puzzle():
"""Create a random puzzle layout."""
puzzle_tiles = random.sample(range(1, 9), 8)
puzzle_tiles.append(' ')
random.shuffle(puzzle_tiles)
return [puzzle_tiles[i:i+3] for i in range(0, len(puzzle_tiles), 3)]
def print_puzzle(puzzle):
"""Display the current state of the puzzle."""
for row in puzzle:
print(' '.join(map(str, row)))
print()
def make_move(puzzle, user_input, move_map):
"""Execute a move based on user input."""
if user_input not in move_map.values():
print("Invalid move! Please use the specified keys for left, right, up, or down moves.")
return False
for move, key in move_map.items():
if key == user_input:
direction = move
break
directions = {'left': (0, -1), 'right': (0, 1), 'up': (-1, 0), 'down': (1, 0)}
move_row, move_col = directions[direction]
for i in range(3):
for j in range(3):
if puzzle[i][j] == ' ':
continue
new_row, new_col = i + move_row, j + move_col
if 0 <= new_row < 3 and 0 <= new_col < 3 and puzzle[new_row][new_col] == ' ':
puzzle[i][j], puzzle[new_row][new_col] = puzzle[new_row][new_col], puzzle[i][j]
return True
print("Invalid move! Cannot move in that direction.")
return False
def is_solved(puzzle):
"""Check if the puzzle is solved."""
return puzzle == [[1, 2, 3], [4, 5, 6], [7, 8, ' ']]
def get_valid_moves(puzzle):
"""Determine the valid moves for the current puzzle layout."""
empty_row, empty_col = None, None
for i in range(3):
for j in range(3):
if puzzle[i][j] == ' ':
empty_row, empty_col = i, j
break
if empty_row is not None:
break
valid_moves = []
if empty_col > 0:
valid_moves.append('right')
if empty_col < 2:
valid_moves.append('left')
if empty_row > 0:
valid_moves.append('down')
if empty_row < 2:
valid_moves.append('up')
return valid_moves
def play_game():
"""Main function to play the game."""
display_intro()
move_map = {}
user_keys = input("Enter four
letters representing left, right, up, down moves (e.g., 'adws'): ").strip().lower()
if len(user_keys) != 4 or len(set(user_keys)) != 4 or not user_keys.isalpha():
print("Invalid input! Please enter four different letters representing four directions.")
return play_game()
directions = ['left', 'right', 'up', 'down']
for i in range(4):
move_map[directions[i]] = user_keys[i]
valid_keys = ', '.join([f"{direction.capitalize()}-{move_map[direction]}" for direction in move_map])
puzzle = generate_puzzle()
moves_made = 0
while True:
print_puzzle(puzzle)
if is_solved(puzzle):
print(f"Congratulations! You solved the puzzle in {moves_made} moves!")
play_again = input("Enter 'n' to play again or 'q' to quit: ").strip().lower()
if play_again == 'n':
return play_game()
elif play_again == 'q':
print("Thank you for playing!")
sys.exit()
else:
print("Invalid input! Please enter 'n' to play again or 'q' to quit.")
continue
valid_moves = get_valid_moves(puzzle)
valid_moves_prompt = ', '.join([f"to {direction.capitalize()}-{move_map[direction]}" for direction in valid_moves])
move_prompt = f"You can move {valid_moves_prompt}: "
user_move = input(move_prompt).strip().lower()
if make_move(puzzle, user_move, move_map):
moves_made += 1
if __name__ == "__main__":
play_game()
|