Reputation: 4013
I've declared a matrix with the following code:
matrix = [[' ' for x in range(x1)] for x in range(y1)]
But when I try to find a random element and change it's value with the following code:
randomX = random.randint(0, x)
randomY = random.randint(0, y)
if matrix[randomX][randomY] == ' ':
try:
matrix[randomX][randomY] = 'G'
scr.addstr(randomX, randomY, matrix[randomX][randomY])
scr.refresh()
except IndexError:
return
I get an IndexError. I tried to just write some garbage code to exit the function if it runs in to an IndexError. It works once, then it still throws the error.
Note, x1 is the same as x in the function. Same goes with y1 and y.
Any clue what I'm doing wrong?
Upvotes: 1
Views: 997
Reputation: 633
Indexes go out of range because radint picks a number including edges of scopes. x1 should be x1 = x + 1. But it is better not to have various variables where one is enough. Also, LafexIos right about indexing (first Y then X).
import random
x = 3
y = 4
matrix = [[' ' for ind_x in range(x)] for ind_y in range(y)]
for m in matrix:
print m
print '---------------------'
randomX = random.randint(0, x-1)
print 'random x: ', randomX
randomY = random.randint(0, y-1)
print 'random y: ', randomY
if matrix[randomY][randomX] == ' ':
matrix[randomY][randomX] = 'G'
print '---------------------'
for m in matrix:
print m
Output:
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
---------------------
random x: 1
random y: 0
---------------------
[' ', 'G', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
Upvotes: 0
Reputation: 7735
Your indices are in wrong order. You should access them by
matrix[randomY][randomX]
or change the order in comprehension.
matrix = [[' ' for y in range(y1)] for x in range(x1)]
Also, as Garrett pointed out in comments, randint()
is inclusive on both ends so you might want to use randint(0,x-1)
and randint(0,y-1)
.
Upvotes: 7