python - 为什么我的程序会产生列表索引问题?

标签 python pygame

我对编程非常陌生,正在尝试使用 Pygame 创建战舰游戏。我的游戏功能和人工智能与玩家的对抗,目前我正在努力研究如何将人工智能的炸弹放置到位。我创建了一个函数(bombs),将grid[row][column]设置为2,它将输出“Boom” “如果点击。如果我将单个值设置为 2(如第 55 行所示),它会起作用,但我希望随机设置炸弹。

我的游戏中处理人工智能炸弹的部分:

import random

def bombs():
    for i in range(0,8):
        row = random.randint(1,8)
        column = random.randint(1,8)
        grid[row][column] = 2
        print(row,column)
        i = i+1
 
# Create a 2 dimensional array. A two dimensional array is simply a list of lists.
grid = []
for row in range(8):
    # Add an empty array that will hold each cell
    # in this row
    grid.append([])
    for column in range(0,8):
        grid[row].append(0)  # Append a cell

错误:

Traceback (most recent call last):
  File "C:\Users\hazza\OneDrive\Desktop\Python\CHECK.py", line 54, in <module>
    bombs()
  File "C:\Users\hazza\OneDrive\Desktop\Python\CHECK.py", line 9, in bombs
    grid[row][column] = 2
IndexError: list index out of range

最佳答案

random.randint(a, b) 生成一个随机整数 N,使得 a <= N <= b。列表索引从 0 开始。
使用random.randrange生成指定范围内的随机列和行:

row = random.randrange(8)
column = random.randrange(8)
grid[row][column] = 2

random.randrange 的工作方式类似于 range ,但它不会生成范围,它只是返回指定范围内的随机数。

关于python - 为什么我的程序会产生列表索引问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472822/

相关文章:

python 2.6,pygame,乒乓球不会正确地在 y 坐标上移动

python - 如何在pygame中伪造鼠标事件?

python - HTML 和 BeautifulSoup : how to iteratively parse when the structure is not always known beforehand?

python - 是否有一个函数可以在维持我的订单的同时将我的数字四舍五入?

python - python/pygame 如何以均匀速度随机方向移动 Sprite ?

python - 为什么当我给它一个高于 16 毫秒的参数时 pygame.time.set_timer() 停止工作?

python - 如何在 pygame 中在屏幕顶部显示分数?

python - 为什么 PyCrypto 不使用默认 IV?

python - **kwargs 中具有多种类型的类型注释

python Fabric : How to retrieve a filelist of a dir