为什么我的移动方法不起作用?

时间:2018-01-10 22:07:53

标签: python pygame

当我运行以下代码时,我收到此错误

reindeer.moveUp(screen)

File "C:\Users\adity\Desktop\Python\CPT.py", line 38, in moveUp

self.y = self.y - 3
AttributeError: 'pygame.Surface' object has no attribute 'y'

我希望每次用户使用reindeer类中的方法按w或s时向上或向下移动矩形。这是因为方法有问题吗?

为什么程序不知道你是什么?我在课程的属性列表中分配了它。

import pygame

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

pygame.init()

# Set the width and height of the screen [width, height]
size = (1000, 800)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
screen.fill(WHITE)
class Reindeer():
    def __init__(self): 
        self.color = (255,0,0)
        self.y_move = 3
        self.x = 100
        self.y = 100
        self.width = 100
        self.length = 100
    def draw(screen, self):
        pygame.draw.rect(screen, color, [self.x,self.y,self.width,self.length], 0)
    def moveDown(screen, self):
        self.y = self.y + 3
        pygame.draw.rect(screen, self.color, [self.x,self.y,self.width, self.length], 0)
    def moveUp(screen, self):
        self.y = self.y - 3
        pygame.draw.rect(screen, self.color, [self.x,self.y,self.width,self.length], 0)
reindeer = Reindeer()
# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                reindeer.moveDown(screen)
            elif event.key == pygame.K_s:
                reindeer.moveUp(screen)


    pygame.display.flip()


    clock.tick(60)

pygame.quit()

1 个答案:

答案 0 :(得分:1)

我终于通过(叹气)阅读代码来挖掘它。您的方法参数的顺序错误:根据定义,第一个参数是调用对象。切换方法签名:

def moveDown(self, screen):

......和所有其他人一样。