I have this code that creates a matrix filled with zeros. I want to replace some of the zeros with a “sign” which is given when creating a snake object. I then want to replace the zeros in the matrix with my sign without increasing the total amount of elements in the matrix.
With my “growth” function in the snake class I want to make sure that only zeros is overwritten but I get the error:
ValueError: (1, 4) is not in list
When I’m sure that position actually do exist! The error code is different each time I run the program since the cordinates are generated on random. Here’s my code:
class field:
def __init__(self):
self.table= [ [ "0" for i in range(10) ] for j in range(10) ]
def printfield(self):
for row in self.table:
print (row)
Class snake:
def __init__(self,sign):
self.sign = sign
self.x = random.randint(1,9)
self.y = random.randint(1,9)
field.table[self.x][self.y] = sign
def growth(self, list, index, element):
if list[index] != 0:
return False
else:
field.table[self.x-v*b][self.y-v*c] = element
def increase(self,p,b,c):
for v in range(p+1):
self.growth(field.table,field.table.index((self.x-v*b,self.y-v*c)), self.sign)
You’re confusing your indices in the two-dimensional list with values in the list. The statement
looks for a value of (in your given error case)
(1, 4)inside of the listfield.table, which is of course not there. What you probably want is accessingfield.table[1][4]. You could just pass the tuple as a variable togrowthand use its elements as indices for the list, or passfield.table[self.x-v*b]as the list to growth andself.y-v*cas the index to access on that list.Also, you are filling the list with
"0"s but checking against0inside yourgrowthfunction.