简体   繁体   中英

Why does my program generate a list indexing issue?

I'm really new to programming and am trying to create a battleships game using Pygame. My game features and AI vs a player and currently I am struggling on how to put the AI's bombs into place. I've created a function( bombs ) that sets the grid[row][column] to 2 , where it'll output "Boom" if clicked. It works if I set and individual value to 2 as shown in line 55, but I want the bombs to be set randomly.

The part of my game that deals with the AI's bombs:

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

The error:

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) generates a random integer N such that a <= N <= b . List indices start at 0.
Use random.randrange to generate a random column and row in a specified range:

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

random.randrange works like range , but it doesn't generate a range, it just returns a random number in the specified range.

Your grid has 8 items, with indices from 0 to 7 (zero based indexing). However, random.randint(1,8) takes random number from 1 to 8, including the boundary values. So if the random number is 8, you get this index out of range error (you can easily debug it with print ing the value before the line

Change it to

row = random.randint(0,7) # column the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM