MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / loadLevels

Function loadLevels

src/gamesbyexample/sokoban.py:156–189  ·  view source on GitHub ↗
(levelFilename)

Source from the content-addressed store, hash-verified

154
155
156def loadLevels(levelFilename):
157 if not os.path.exists('sokobanlevels.txt'):
158 print('Error: Cannot find the level file. Download it from')
159 print('https://inventwithpython.com/sokobanlevels.txt')
160 sys.exit()
161 allLevels = []
162 with open(levelFilename) as levelFile:
163 # Each level is represented by a dictionary:
164 currentLevelFromFile = {WIDTH: 0, HEIGHT: 0}
165 y = 0
166 for line in levelFile.readlines():
167 if line.startswith(';'):
168 continue # Ignore comments in the level file.
169
170 if line == '\n':
171 if currentLevelFromFile == {WIDTH: 0, HEIGHT: 0}:
172 continue # Ignore this level file line.
173 # Finished with the current level:
174 allLevels.append(currentLevelFromFile)
175 currentLevelFromFile = {WIDTH: 0, HEIGHT: 0}
176 y = 0 # Reset y back to 0.
177 continue
178
179 # Add the line to the current level.
180 # We use line[:-1] so we don't include the newline:
181 for x, levelChar in enumerate(line[:-1]):
182 currentLevelFromFile[(x, y)] = levelChar
183 y += 1
184
185 if len(line) - 1 > currentLevelFromFile[WIDTH]:
186 currentLevelFromFile[WIDTH] = len(line) - 1
187 if y > currentLevelFromFile[HEIGHT]:
188 currentLevelFromFile[HEIGHT] = y
189 return allLevels
190
191
192def displayLevel(levelNum, maxLevelNum, levelData):

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected