简体   繁体   中英

Python, AttributeError: 'PlayerPaddle' object has no attribute 'update'

    import pygame
from pygame.locals import *

class PlayerPaddle(object):
   def __init__(self, screensize):

    self.screensize = screensize

    self.position_x = int(screensize[0]*0.5)
    self.position_y = int(screensize[1]*0.8)

    self.width  = 10
    self.height = 4

    self.rect = pygame.Rect(self.position_x - (self.width*0.5),
                            self.position_y - (self.height*0.5),
                            self.width, self.height)
    self.color = (100, 200, 200)

    self.speed = 5
    self.direction = 0

    def update(self):
        self.position_x += self.direction * self.speed

    def render(self, screen):
        pygame.draw.rect(screen, self.color, self.rect, 0)
        pygame.draw.rect(screen, (0,0,0), self.rect, 1)

def main():
    pygame.init()

    screensize = (600, 700)
    screen = pygame.display.set_mode(screensize)

    clock = pygame.time.Clock()

    player_paddle = PlayerPaddle(screensize)

    running = True

    while running:
        clock.tick(64)


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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player_paddle.direction = 1
                elif event.key == pygame.K_RIGHT:
                    player_paddle.direction = -1
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player_paddle.direction = 0
                elif event.key == pygame.K_RIGHT:
                    player_paddle.direction = 0

        player_paddle.update()

        screen.fill((100, 100, 100))

        player_paddle.render(screen)

        pygame.display.flip()

    pygame.quit()

main()

Sorry for long code.. But I'm getting so frustrated. Why am i getting "'PlayerPaddle' object has no attribute 'update'" Error !?

For what i have been able to understand its my def update(self) function that is returning null or smth.. But how is that? Is it in my eventhandler that the error is? Is it updating the position wrong?

It looks like your indentation is off. Your methods update and render are indented inside the __init__ method. Move them out one indentation level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM