抱歉,如果答案很简单,但我真的被困在这一个。。。 我试图做一个“蛇游戏”,但我得到一个错误,当我试图调用函数,使我的蛇移动。 错误状态为:
Traceback (most recent call last):
File "C:\Users\Fran\Desktop\SnakeISN.py", line 89, in <module>
theApp.on_execute()
File "C:\Users\Fran\Desktop\SnakeISN.py", line 80, in on_execute
snake.changeDirectionTo(3)
TypeError: 'str' object is not callable
每当我开始按箭头键。。。 导入pygame 导入系统 随机导入
class Snake():
def __init__(self):
self.x=400
self.y=590
self.direction = "RIGHT"
self.changeDirectionTo = self.direction
def changeDirectionTo(self,dir):
if dir == 1 and not self.direction == 2:
self.direction = "RIGHT"
if dir == 2 and not self.direction == 1:
self.direction = "LEFT"
if dir == 3 and not self.direction == 4:
self.direction = "UP"
if dir == 4 and not self.direction == 3:
self.direction = "DOWN"
def move(self, foodPos):
if self.direction == "RIGHT":
self.x += 100
if self.direction == "LEFT":
self.x -= 100
if self.direction == "UP":
self.y -= 100
if self.direction == "DOWN":
self.y += 100
class Appli:
windowX = 800
windowY = 600
def __init__(self):
self._running = True
self._show_surf = None
self._image_surf = None
self.snake = Snake()
def on_init(self):
pygame.init()
self._show_surf = pygame.display.set_mode((self.windowX,self.windowY), pygame.HWSURFACE)
pygame.display.set_caption('Snake V2.7')
self._running = True
self._image_surf = pygame.image.load("pygame.png").convert()
def on_event(self, event):
if event.type == QUIT:
self._running = False
def on_loop(self):
pass
def on_render(self):
self._display_surf.fill((0,0,0))
self._display_surf.blit(self._image_surf,(self.snake.x,self.snake.y))
pygame.display.flip()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
snake=Snake()
if self.on_init() == False:
self._running = False
while( self._running ):
pygame.event.pump()
action = pygame.key.get_pressed()
if action[pygame.K_RIGHT]:
snake.changeDirectionTo(1)
if action[pygame.K_LEFT]:
snake.changeDirectionTo(2)
if action[pygame.K_UP]:
snake.changeDirectionTo(3)
if action[pygame.K_DOWN]:
snake.changeDirectionTo(4)
self.on_loop()
self.on_render()
self.on_cleanup()
if __name__ == "__main__" :
theApp = App()
theApp.on_execute()
有人知道问题出在哪里吗? 第一次出现这个错误时,我把所有方向的“右”、“左”、“上”、“下”改成了1、2、3、4,希望它能解决“str call”错误,但它没有。。。你知道吗
谢谢你的帮助
理解错误消息是解决问题的关键。你知道吗
调用函数时,可以添加括号和任何参数:
但是当你给一个不是函数的东西加上括号时会发生什么呢?你知道吗
因此,您的错误表明您试图调用的函数(
changeDirectionTo(3)
)不是函数,而是字符串。你知道吗由于有一行
def changeDirectionTo
将其声明为函数,请查找changeDirectionTo
的其他替代此定义的用法。你知道吗问题出在
def __init__
。这两行声明一个字符串,然后将其赋给changeDirectionTo
,覆盖前面的函数定义。你知道吗使用其他变量名或删除行来解决问题。你知道吗
在snake的
__init__
方法中,您定义了一个属性self.changeDirectionTo
,它指向一个字符串,并重写同名的方法。你知道吗你应该删除那一行。你知道吗
从
__init__
方法中去掉这一行:你已经把一个函数
changeDirectionTo
变成了一个字符串。。。你知道吗相关问题 更多 >
编程相关推荐