首页 > 解决方案 > 蛇游戏 - str 对象不可调用

问题描述

对不起,如果答案很简单,但我真的坚持这个......我正在尝试制作一个“蛇游戏”,但是当我尝试调用该函数以使我的蛇移动时出现错误。错误状态:

    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

每当我开始按箭头键... import pygame import sys import random

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()

有谁知道问题出在哪里?第一次遇到此错误时,我将所有方向 "RIGHT" 、 "LEFT" 、 "UP" 、 "DOWN" 更改为 1,2,3,4 ,希望它能解决 'str call' 错误,但它没...

感谢帮助

标签: pythonstring

解决方案


在您的蛇的__init__方法中,您定义了一个属性 ,self.changeDirectionTo它指向一个字符串并覆盖具有相同名称的方法。

您应该删除该行。


推荐阅读