-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaze_runner_2d.py
More file actions
170 lines (147 loc) · 5.5 KB
/
maze_runner_2d.py
File metadata and controls
170 lines (147 loc) · 5.5 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""
Maze Runner 2D, by Al Sweigart al@inventwithpython.org
Move around a maze and try to excape. Maze files are generated by mazemakerrec.py
Tags: large, game, maze
"""
import sys, os, subprocess
# Maze File Constants
WALL = '#'
EMPTY = ' '
START = 'S'
EXIT = 'E'
PLAYER = '@'
BLOCK = chr(9617)
def displayMaze(maze):
# Display the maze
for y in range(HEIGHT):
for x in range(WIDTH):
if (x,y) == (playerx, playery):
print(PLAYER, end='')
elif (x,y) == (exitx, exity):
print('X', end='')
elif maze[(x, y)] == WALL:
print(BLOCK, end='')
else:
print(maze[(x, y)], end='')
print() # Print a newline after printing the row.
def getMazeFile():
txt_files = [f for f in os.listdir() if f.endswith('.txt') and os.path.isfile(f)]
if not txt_files:
print("No .txt files found.")
sys.exit(0)
for idx, file in enumerate(txt_files, 1):
print(f"{idx}. {file}")
try:
choice = int(input("Enter the number of the file you want to choose: "))
if 1 <= choice <= len(txt_files):
selected_file = txt_files[choice - 1]
print(f"You selected: {selected_file}")
else:
print("Invalid selection.")
except ValueError:
print("Please enter a valid number.")
return selected_file
print("""Maze Runner 2D, by Al Sweigart al@inventwithpython.com
(Maze files are generated by mazemakerrec.py)""")
# Get the maze file's filename from the user:
print('Select the number of the maze file you want to play:')
filename = getMazeFile()
# Load the maze from a file:
mazeFile = open(filename)
maze = {}
lines = mazeFile.readlines()
playerx = None
playery = None
exitx = None
exity = None
y = 0
for line in lines:
WIDTH = len(line.rstrip())
for x, character in enumerate(line.rstrip()):
assert character in (WALL, EMPTY, START, EXIT), 'Invalid character at column {}, line {}'.format(x+1, y+1)
if character in (WALL, EMPTY):
maze[(x, y)] = character
elif character == START:
playerx, playery = x, y
maze[(x, y)] = EMPTY
elif character == EXIT:
exitx, exity = x, y
maze[(x, y)] = EMPTY
y +=1
HEIGHT = y
assert playerx != None and playery != None, 'No start in maze file.'
assert exitx != None and exity != None, 'No exit in maze file.'
while True:
subprocess.run('cls', shell=True) # os.system('cls') on Windows
displayMaze(maze)
while True:
print('')
print('Enter direction, or QUIT:')
print(' W ')
print(' ASD')
move = input('> ').upper()
if move == "QUIT":
print('Thanks for playing!')
sys.exit()
if move not in ['W','A','S','D']:
print('Invalid direction. Enter one of the following directions:')
print(' W, A, S, D')
continue
#Check if the player can move in that direction:
if move == 'W' and maze[(playerx, playery - 1)] == EMPTY:
break
elif move == 'S' and maze[(playerx, playery + 1)] == EMPTY:
break
elif move == 'A' and maze[(playerx - 1, playery)] == EMPTY:
break
elif move == 'D' and maze[(playerx + 1, playery)] == EMPTY:
break
print('You cannot move in that direction.')
# Keep moving in this direction until you encounter a branch point.
if move == 'W':
while True:
playery -= 1
if (playerx, playery) == (exitx, exity):
break
if maze[(playerx, playery - 1)] == WALL:
break # Break if we hit a wall
if (maze[(playerx - 1, playery)] == EMPTY
or maze[(playerx + 1, playery)] == EMPTY):
break # Break if we've reached a branch point.
elif move == 'S':
while True:
playery += 1
if (playerx, playery) == (exitx, exity):
break
if maze[(playerx, playery + 1)] == WALL:
break # Break if we hit a wall
if (maze[(playerx - 1, playery)] == EMPTY
or maze[(playerx + 1, playery)] == EMPTY):
break # Break if we've reached a branch point.
elif move == 'A':
while True:
playerx -= 1
if (playerx, playery) == (exitx, exity):
break
if maze[(playerx - 1, playery)] == WALL:
break # Break if we hit a wall
if (maze[(playerx, playery - 1)] == EMPTY
or maze[(playerx, playery + 1)] == EMPTY):
break # Break if we've reached a branch point.
elif move == 'D':
while True:
playerx += 1
if (playerx, playery) == (exitx, exity):
break
if maze[(playerx + 1, playery)] == WALL:
break # Break if we hit a wall
if (maze[(playerx, playery - 1)] == EMPTY
or maze[(playerx, playery + 1)] == EMPTY):
break # Break if we've reached a branch point.
if (playerx, playery) == (exitx, exity):
subprocess.run('cls', shell=True)
displayMaze(maze)
print('\n\nYou have reached the exit! Good Job!\n')
print('Thanks for playing!')
sys.exit
break # Force the game to exit