我正在Python3中使用Pygame编写蛇游戏。但是,我不断收到此TypeError信息,不仅不知道这意味着什么,也不知道如何解决
我真的没有尝试过任何东西,因为我不知道它是什么或如何解决。这是代码:
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
我不断收到的错误消息是:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable
答案 0 :(得分:1)
当您尝试通过无类型对象(例如
)建立索引时,会发生这种情况>>> x = None
>>> x[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x[0]
TypeError: 'NoneType' object is not subscriptable
为正确解决您的问题,请发布完整的代码或在self.pos
的初始值中进行设置。看来您正在将此变量设置为None
。
答案 1 :(得分:1)
这似乎是Tech With Tim的python教程的摘录:https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/
这实际上是由于randomSnack while循环内返回的放错位置引起的。
此处的完整代码:https://pastebin.com/embed_js/jB6k06hG
如果返回值在while循环内(pastebin中的第162行),则会出现此错误。我在遵循相同的教程,也收到此错误。
# When you call (line 145)
snack.draw(surface)
# you are referencing the snack that was created with (line 193)
snack = cube(randomSnack(rows, s), color=(0,255,0))
# The randomSnack function returns an x and y (line 162)
return (x,y)
# that gets passed into the cube object's "start" parameter (line 12)
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):