2

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
1
  • Arrays are 0-indexed. Make sure your rng function returns at least 0 and less than array length. Commented Aug 18, 2020 at 16:30

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 printing the value before the line

Change it to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.