python - 如何修复此列表超出范围?
问题描述
我正在制作一个玩家可以在 8x8 网格上移动的游戏,但是我收到了一个错误,其中的值超出了范围。
这是我的代码:
def player_movement():
grid0 = []
grid1 = []
i = 0
n = 0
while i < 8: #this makes the grid
grid0.append("0")
i += 1
while n < 8:
grid1.append(grid0.copy())
n += 1
grid1[0][0] = "X" # this places the player on the top left of the grid
for l in grid1:
print(l)
while True:
player_movex = int(input("Move right how many?"))# instructions to move the player
player_movey = int(input("Move down how many??"))
for y, row in enumerate(grid1): #this finds the player on the grid
for x, i in enumerate(row):
if i == "X":
grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]
for j in grid1: #prints out the grid in the 8x8 format
print(j)
我正在输入列表范围内的值,即 0-7。
这是我屏幕上出现的错误:
Traceback (most recent call last):
File "D:\Python\Treasure Hunt game.py", line 83, in <module>
player_movement()
File "D:\Python\Treasure Hunt game.py", line 78, in player_movement
grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]
IndexError: list index out of range
解决方案
我宁愿编码如下:
def player_movement():
n = 8
grid = [['0'] * n for _ in range(n)]
m = 'x'
grid[0][0] = m # this places the player on the top left of the grid
for i in grid:
print(i)
while True:
# instructions to move the player
player_movex = int(input("Move right how many? "))
player_movey = int(input("Move down how many?? "))
move(grid, m, n, player_movey, player_movex)
for j in grid: # prints out the grid in the 8x8 format
print(j)
def move(grid, m, n, move_y, move_x):
for y, row in enumerate(grid): # this finds the player on the grid
for x, i in enumerate(row):
if i == m:
a, b = y + move_y, x + move_x
if a >= n:
print(f'Sorry, move {move_y} down will out of range!\n')
return
if b >= n:
print(f'Sorry, move {move_x} right will out of range!\n')
return
grid[y][x], grid[a][b] = grid[a][b], grid[y][x]
return
player_movement()
推荐阅读
- php - 从数据库表中检索数据时出现错误
- python - 如何在 Python 中进行并行处理?
- node.js - 在 Adonisjs 中插入多行不起作用
- java - 使用 brew cask 在 MacOs Catalina10.15 上安装 Java6
- scala - 如何将 Set[Tuple2] 中的数据转换为案例类
- c++ - 嵌套的 lambda 和可变关键字
- twitter-bootstrap - 将 Bootstrap 3 迁移到 4 后的布局问题(表格宽度、内联元素未垂直堆叠)
- python - 为什么 map 函数从数据框中删除列
- java - Android中checkbox和checkedtextview的区别?RecyclerView 使用哪个?
- javascript - 如何将 TypeScript 定义文件用于另一个函数