Skip to content

Commit e963420

Browse files
authored
Add Number Maze Game implementation for issue #869
1 parent 6145cd1 commit e963420

1 file changed

Lines changed: 97 additions & 0 deletions

File tree

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import random
2+
import os
3+
import sys
4+
5+
6+
def clear_screen():
7+
"""Clear the terminal screen."""
8+
os.system('cls' if os.name == 'nt' else 'clear')
9+
10+
11+
def create_maze(size=8):
12+
"""Create a random number maze."""
13+
maze = [[random.randint(1, 9) for _ in range(size)] for _ in range(size)]
14+
start = (0, 0)
15+
goal = (size - 1, size - 1)
16+
maze[start[0]][start[1]] = 'S'
17+
maze[goal[0]][goal[1]] = 'G'
18+
return maze, start, goal
19+
20+
21+
def display_maze(maze, player_pos):
22+
"""Display the maze with player position."""
23+
clear_screen()
24+
print("\nNumber Maze Game - Reach the Goal (G)!\n")
25+
print("Controls: W=Up, A=Left, S=Down, D=Right, Q=Quit\n")
26+
for i, row in enumerate(maze):
27+
for j, cell in enumerate(row):
28+
if (i, j) == player_pos:
29+
print('[P]', end=' ')
30+
elif cell == 'S':
31+
print('[S]', end=' ')
32+
elif cell == 'G':
33+
print('[G]', end=' ')
34+
else:
35+
print(f'[{cell}]', end=' ')
36+
print()
37+
print()
38+
39+
40+
def get_move():
41+
"""Get player move input."""
42+
if os.name == 'nt':
43+
import msvcrt
44+
key = msvcrt.getch().decode('utf-8').upper()
45+
else:
46+
import tty
47+
import termios
48+
fd = sys.stdin.fileno()
49+
old_settings = termios.tcgetattr(fd)
50+
try:
51+
tty.setraw(fd)
52+
key = sys.stdin.read(1).upper()
53+
finally:
54+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
55+
return key
56+
57+
58+
def move_player(pos, direction, size):
59+
"""Calculate new player position."""
60+
y, x = pos
61+
if direction == 'W' and y > 0:
62+
return (y - 1, x)
63+
elif direction == 'S' and y < size - 1:
64+
return (y + 1, x)
65+
elif direction == 'A' and x > 0:
66+
return (y, x - 1)
67+
elif direction == 'D' and x < size - 1:
68+
return (y, x + 1)
69+
return pos
70+
71+
72+
def play_game():
73+
"""Main game logic."""
74+
maze, start, goal = create_maze()
75+
player_pos = start
76+
moves = 0
77+
78+
while player_pos != goal:
79+
display_maze(maze, player_pos)
80+
print(f"Moves: {moves}")
81+
move = get_move()
82+
83+
if move == 'Q':
84+
print("\nGame quit. Thanks for playing!")
85+
return
86+
87+
new_pos = move_player(player_pos, move, len(maze))
88+
if new_pos != player_pos:
89+
moves += 1
90+
player_pos = new_pos
91+
92+
display_maze(maze, player_pos)
93+
print(f"\nCongratulations! You reached the goal in {moves} moves!")
94+
95+
96+
if __name__ == "__main__":
97+
play_game()

0 commit comments

Comments
 (0)