【问题标题】:TypeError: 'str' object is not callable in my methodTypeError:“str”对象在我的方法中不可调用
【发布时间】:2021-12-19 02:06:34
【问题描述】:

我一直在尝试用 python 设计一个蛇游戏,但是在实现了使蛇的身体(而不是头部)移动的部分代码之后,我得到了这个错误:

TypeError: 'str' object is not callable

我在网上查看,我发现我只是说我不应该将我的变量称为“str”,但我没有,所以我有点困惑。 这是课程:

class snake(object):
    def __init__(self,x,y,h_dir,b_dir):
        self.X=x
        self.Y=y
        self.h_dir=h_dir
        self.b_dir=b_dir
    
    def direction(self):
        global head_direction
        self.direction=head_direction
        if(self.X==turn_X and self.Y==turn_Y):
            self.direction=head_direction
        return self.direction

这里是错误发生的地方:

for i in range(1,snakeLength):
        if(body[i].direction()=='UP'):
            body[i].Y-=20
        if(body[i].direction()=='RIGHT'):
            body[i].X+=20
        if(body[i].direction()=='DOWN'):
            body[i].Y+=20
        if(body[i].direction()=='LEFT'):
            body[i].X-=20
        pygame.draw.rect(window, grey, (body[i].X, body[i].Y, 20, 20))

这是完整的代码:

    # Libraries
    import pygame
    from time import*

running=True
while running:
    # Initialisation
    pygame.init()

    # Quit programm
    for event in pygame.event.get():
            if(event.type==pygame.QUIT):
                running=False

    # Class
    class snake(object):
        def __init__(self,x,y,h_dir,b_dir):
            self.X=x
            self.Y=y
            self.h_dir=h_dir
            self.b_dir=b_dir
        
        def direction(self):
            global head_direction
            self.direction=head_direction
            if(self.X==turn_X and self.Y==turn_Y):
                self.direction=head_direction
            return self.direction

    # Functions
    def displayScore():
        score_font=pygame.font.Font('/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Snake/G7StarForceTtf-OEg6.ttf',20)
        score_surface=score_font.render('SCORE '+score, True, white)
        window.blit(score_surface, (0,500))
        pygame.display.update()

    def gameOver():
        window.fill((green))
        global alive
        gameOver_font=pygame.font.Font('/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Snake/G7StarForceTtf-OEg6.ttf',50)
        gameOver_surface=gameOver_font.render('GAME OVER', True, white)
        gameOver_rect=gameOver_surface.get_rect(center=(window_X/2, window_Y/2))
        score_font=pygame.font.Font('/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Snake/G7StarForceTtf-OEg6.ttf',20)
        score_surface=score_font.render('YOUR FINAL SCORE IS '+score, True, white)
        window.blit(score_surface, (0,500))
        window.blit(gameOver_surface, (gameOver_rect))
        pygame.display.update()
        sleep(3)
        alive=False

    # Window size
    window_X=500
    window_Y=520

    # Colors
    green=pygame.Color(153,255,153)
    black=pygame.Color(0,0,0)
    grey=pygame.Color(32,32,32)
    red=pygame.Color(255,0,0)
    white=pygame.Color(255,255,255)

    # Window
    pygame.display.set_caption("Snake")
    window=pygame.display.set_mode((window_X,window_Y))
    icon=pygame.image.load('/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Snake/anaconda.png')
    pygame.display.set_icon(icon)

    # FPS
    fps=pygame.time.Clock()

    # Head
    head_X=240
    head_Y=240
    head_direction='RIGHT'
    head_no_direction='LEFT'

    # Tail
    body=['head']
    snakeLength=5
    turn_X=-1
    turn_Y=-1

    # Snake
    snake_speed=5

    # Score
    score=0

    for i in range(0,snakeLength):
        body.append(i)
    for i in range(snakeLength):
        body_X=head_X-(20*i)
        body_Y=head_Y
        body_direction=head_direction
        body[i]=snake(body_X, body_Y, head_direction, body_direction)
    alive=True
    while alive:
        window.fill((green))
        # Events
        for event in pygame.event.get():
            if(event.type==pygame.QUIT):
                running=False
                alive=False
            
            # Keystrokes
            if(event.type==pygame.KEYDOWN):
                turn_X=head_X
                turn_Y=head_Y
                if(event.key==pygame.K_UP):
                    if(head_no_direction!='UP'):
                        head_direction='UP'
                        head_no_direction='DOWN'
                elif(event.key==pygame.K_RIGHT):
                    if(head_no_direction!='RIGHT'):
                        head_direction='RIGHT'
                        head_no_direction='LEFT'
                elif(event.key==pygame.K_DOWN):
                    if(head_no_direction!='DOWN'):
                        head_direction='DOWN'
                        head_no_direction='UP'
                elif(event.key==pygame.K_LEFT):
                    if(head_no_direction!='LEFT'):
                        head_direction='LEFT'
                        head_no_direction='RIGHT'

        # Head
        pygame.draw.rect(window, black, (head_X, head_Y, 20, 20))
        if(head_direction=='UP'):
            head_Y-=20
        if(head_direction=='RIGHT'):
            head_X+=20
        if(head_direction=='DOWN'):
            head_Y+=20
        if(head_direction=='LEFT'):
            head_X-=20

        # Body
        for i in range(1,snakeLength):
            if(body[i].direction()=='UP'):
                body[i].Y-=20
            if(body[i].direction()=='RIGHT'):
                body[i].X+=20
            if(body[i].direction()=='DOWN'):
                body[i].Y+=20
            if(body[i].direction()=='LEFT'):
                body[i].X-=20
            pygame.draw.rect(window, grey, (body[i].X, body[i].Y, 20, 20))
            
            

        # Updates
        pygame.draw.rect(window, red, (0, 0, 500, 500),3)
        displayScore()
        pygame.display.update()
        fps.tick(snake_speed)

        # Game over
        if(head_X==500 or head_X==-20 or head_Y==500 or head_Y==-20):
            gameOver()

我需要帮助。

【问题讨论】:

  • 错误在哪一行?粘贴完整的错误跟踪!
  • 整个部分:if(body[i].direction()=='UP'): body[i].Y-=20 if(body[i].direction()== 'RIGHT'): body[i].X+=20 if(body[i].direction()=='DOWN'): body[i].Y+=20 if(body[i].direction()== 'LEFT'): body[i].X-=20
  • 一些通用的东西:在 Python 3 中不再需要从 object 继承。if(foo): 在 python 中并不常见,请改用 if foo:

标签: python string pygame typeerror


【解决方案1】:

这部分:

   for i in range(1,snakeLength):
        if(body[i].direction()=='UP'):
            body[i].Y-=20
        if(body[i].direction()=='RIGHT'):
            body[i].X+=20
        if(body[i].direction()=='DOWN'):
            body[i].Y+=20
        if(body[i].direction()=='LEFT'):
            body[i].X-=20
        pygame.draw.rect(window, grey, (body[i].X, body[i].Y, 20, 20))

应该是这样的:

for i in range(1,snakeLength):
    if(body[i].direction=='UP'):
        body[i].Y-=20
    if(body[i].direction=='RIGHT'):
        body[i].X+=20
    if(body[i].direction=='DOWN'):
        body[i].Y+=20
    if(body[i].direction=='LEFT'):
        body[i].X-=20
    pygame.draw.rect(window, grey, (body[i].X, body[i].Y, 20, 20))

您的代码还出现了一些其他问题,但这对我来说可以解决您的问题。

如果您仍然遇到问题,这是我完成的代码,运行时没有出现错误。请注意,我替换了你的图标和字体文件名,以便我可以使用我机器上的可用资源。

(剧透!)
# Libraries
import pygame
from time import*

running=True
while running:
    # Initialisation
    pygame.init()

    # Quit programm
    for event in pygame.event.get():
            if(event.type==pygame.QUIT):
                running=False

    # Class
    class snake(object):
        def __init__(self,x,y,h_dir,b_dir):
            self.X=x
            self.Y=y
            self.h_dir=h_dir
            self.b_dir=b_dir
            
        def direction(self):
            global head_direction
            self.direction=head_direction
            if(self.X==turn_X and self.Y==turn_Y):
                self.direction=head_direction
            return self.direction

    # Functions
    def displayScore():
        score_font=pygame.font.Font('Debrosee-ALPnL.ttf',20)
        score_surface=score_font.render('SCORE '+str(score), True, white)
        window.blit(score_surface, (0,500))
        pygame.display.update()

    def gameOver():
        window.fill((green))
        global alive
        gameOver_font=pygame.font.Font('Debrosee-ALPnL.ttf',50)
        gameOver_surface=gameOver_font.render('GAME OVER', True, white)
        gameOver_rect=gameOver_surface.get_rect(center=(window_X/2, window_Y/2))
        score_font=pygame.font.Font('Debrosee-ALPnL.ttf',20)
        score_surface=score_font.render('YOUR FINAL SCORE IS '+str(score), True, white)
        window.blit(score_surface, (0,500))
        window.blit(gameOver_surface, (gameOver_rect))
        pygame.display.update()
        sleep(3)
        alive=False

    # Window size
    window_X=500
    window_Y=520

    # Colors
    green=pygame.Color(153,255,153)
    black=pygame.Color(0,0,0)
    grey=pygame.Color(32,32,32)
    red=pygame.Color(255,0,0)
    white=pygame.Color(255,255,255)

    # Window
    pygame.display.set_caption("Snake")
    window=pygame.display.set_mode((window_X,window_Y))
    icon=pygame.image.load('anaconda.png')
    pygame.display.set_icon(icon)

    # FPS
    fps=pygame.time.Clock()

    # Head
    head_X=240
    head_Y=240
    head_direction='RIGHT'
    head_no_direction='LEFT'

    # Tail
    body=['head']
    snakeLength=5
    turn_X=-1
    turn_Y=-1

    # Snake
    snake_speed=5

    # Score
    score=0

    for i in range(0,snakeLength):
        body.append(i)
    for i in range(snakeLength):
        body_X=head_X-(20*i)
        body_Y=head_Y
        body_direction=head_direction
        body[i]=snake(body_X, body_Y, head_direction, body_direction)
        alive=True
    while alive:
        window.fill((green))
        # Events
        for event in pygame.event.get():
            if(event.type==pygame.QUIT):
                running=False
                alive=False
                
            # Keystrokes
            if(event.type==pygame.KEYDOWN):
                turn_X=head_X
                turn_Y=head_Y
                if(event.key==pygame.K_UP):
                    if(head_no_direction!='UP'):
                        head_direction='UP'
                        head_no_direction='DOWN'
                elif(event.key==pygame.K_RIGHT):
                    if(head_no_direction!='RIGHT'):
                        head_direction='RIGHT'
                        head_no_direction='LEFT'
                elif(event.key==pygame.K_DOWN):
                    if(head_no_direction!='DOWN'):
                        head_direction='DOWN'
                        head_no_direction='UP'
                elif(event.key==pygame.K_LEFT):
                    if(head_no_direction!='LEFT'):
                        head_direction='LEFT'
                        head_no_direction='RIGHT'

        # Head
        pygame.draw.rect(window, black, (head_X, head_Y, 20, 20))
        if(head_direction=='UP'):
            head_Y-=20
        if(head_direction=='RIGHT'):
            head_X+=20
        if(head_direction=='DOWN'):
            head_Y+=20
        if(head_direction=='LEFT'):
            head_X-=20

        # Body
        for i in range(1,snakeLength):
            if(body[i].direction=='UP'):
                body[i].Y-=20
            if(body[i].direction=='RIGHT'):
                body[i].X+=20
            if(body[i].direction=='DOWN'):
                body[i].Y+=20
            if(body[i].direction=='LEFT'):
                body[i].X-=20
                pygame.draw.rect(window, grey, (body[i].X, body[i].Y, 20, 20))
                
            

        # Updates
        pygame.draw.rect(window, red, (0, 0, 500, 500),3)
        displayScore()
        pygame.display.update()
        fps.tick(snake_speed)

        # Game over
        if(head_X==500 or head_X==-20 or head_Y==500 or head_Y==-20):
            gameOver()

【讨论】:

  • 它工作了我不再有任何错误但身体不动这是为什么???
  • 使用我刚刚添加的代码,它似乎可以移动。它不会转向并朝相反的方向移动,但这似乎是有目的的,并且在蛇类游戏中是有意义的。
  • 你还改变了什么?
  • 我在您进行连接的函数中添加了显式类型转换。我想就是这样。
猜你喜欢
  • 2015-03-07
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 2020-09-16
  • 2019-06-11
相关资源
最近更新 更多