I’m testing out a bit of a code that I’m going to use for a simple game but I get this error in init gamefield[x][y] = tecken TypeError: 'field' object does not support indexing
The game is somewhat similar to snake and What I want my program to do is to first create a gamefield which is a matrix where I want to insert my snake(I call it worm here) which is represented by “+”, the position should be chosen randomly.
I then want to be able to decide in which direction the worm grow hence the grow function.
Can anyone see what’s the problem in here? Any help would be greatly appreciated!
import random
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 worm:
def __init__(self,tecken):
x = random.randint(1,9)
y = random.randint(1,9)
gamefield[x][y] = tecken
def grow(self,p,b,c):
try :
for antal in range(p):
if p != 0:
gamefield[x-antal*b][y-antal*c] = "+"
except IndexError :
print ("Game Over")
p = 2
b = 3
c = 0
gamefield = field()
hilda = worm("+")
hilda.grow(p,b,c)
print(gamefield.printfield)
The list is
gamefield.table.gamefielditself is not indexable.If you want to, you can define
__getitem__and__setitem__, so as to wrap the operations ontable. Alternatively, you can simply instantiategamefieldas your list of lists instead of making it a separate type of object.