1

So i am making a game involving a 2d array, and i ask the user to input a grid height and width, here is the code that makes the grid

Grid=[['O'for x in range(gridS[0])]for y in range(gridS[1])]

I later change gridS[0] and 1 to gridX and Y

then i try to add players into the grid, again I ask the user how many players (stored in variable opponents) are playing, then add that many players

            if opponents>0:
            Grid[gridX-1][gridY-2]='P'
            if opponents>1:
                Grid[0][(gridY-2)]='P'
                if opponents>3:
                    Grid[gridX-1][0]='P'

however, when testing, it comes up with this error:

>>> How many bots do you want to play against?
>>> 10
>>> Please enter a number between 0 and 3
>>> 2
2

    Grid[gridX-1][gridY-2]='P'
IndexError: list assignment index out of range
5
  • That is a list not an array. Commented Jul 12, 2017 at 18:32
  • my teacher said array - my bad Commented Jul 12, 2017 at 18:33
  • It is a pedantic point, and loosely, it could be referred to as an array, but it is better to be precise. Commented Jul 12, 2017 at 18:35
  • What do gridX and gridY hold before that line? Print them there and you will see your error Commented Jul 12, 2017 at 18:39
  • it holds a number between 6 and 12, which the user decides Commented Jul 12, 2017 at 18:40

1 Answer 1

1

The problem is your nested comprehension constructs a nested array with the dimensions "flipped". Consider:

>>> dims = (4, 2)
>>> GRID = [['0' for x in range(dims[0])] for y in range(dims[1])]
>>> GRID
[['0', '0', '0', '0'], ['0', '0', '0', '0']]

That would typically be called a 2X4 "matrix". And although that is a red flag, it is a notational issue. The fundamental problem is you are indexing into the first axis using gridX, gridY = dims. So:

>>> x, y = dims
>>> x
4
>>> len(GRID)
2
>>> GRID[x]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

To make everything work out, use the following comprehension:

 Grid=[['O'for y in range(gridS[1])]for x in range(gridS[0])]

In other words, the inner-comprehension creates the second axis, the outer creates the first. But you were thinking about it in the opposite way.

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

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.