到目前为止,这是我的代码。

import pygame
import os
import sys

#start pygame
pygame.init()

#start the game and create the backround
window_width = 1920
window_height = 1010

size = (window_width, window_height)
screen = pygame.display.set_mode(size)

#put the name of the game here
pygame.display.set_caption('Le Epic Game')

#create the player

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('C:\\Users\\Dev\\Documents\\Pythontextgame\\Sprites\\temporaryplayer.jpg').convert()
        self.image.set_colorkey((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.centerx = window_width / 2
        self.rect.bottom - window_height / 2
        self.speedx = 0

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

    def update(self):
        self.rect.x += self.speedx

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

#game loop

FPS = 60
clock = pygame.time.Clock()

running = True
while running:
    clock.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_ESCAPE:
                running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        Player.moveLeft(5, 5)
    if keys[pygame.K_d]:
        Player.moveRight(5, 5)

    all_sprites.update()

    background_image = pygame.image.load('C:\\Users\\Dev\\Documents\\Pythontextgame\\backrounds\\Start.jpg').convert()

    screen.blit(background_image, [0, 0])

    all_sprites.draw(screen)
    pygame.display.flip()

pygame.quit()


但是,当我运行该程序然后按a或d按钮时,我得到了。

Traceback (most recent call last):
  File "C:\Users\Dev\Documents\Pythontextgame\start.py", line 63, in <module>
    Player.moveRight(5, 5)
  File "C:\Users\Dev\Documents\Pythontextgame\start.py", line 31, in moveRight
    self.Rect.x += pixels AttributeError: 'int' object has no attribute 'Rect'


我已经尝试查找有关此的信息,但是到目前为止,它们都没有帮助。我也想知道为什么以前没有这样做,因为这不是我使用self.rect的唯一机会。所有帮助将不胜感激。

最佳答案

Player是类。您必须分别调用对象moveLeftmoveRight方法(例如:player)。 player.moveLeft(5)player的实例:
(分别参见Method Objects Instance Objects

running = True
while running:
    # [...]

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        player.moveLeft(5)
    if keys[pygame.K_d]:
        player.moveRight(5)

关于python - 我试图用python做游戏,首先要移动角色,但是我一直遇到同样的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60345750/

10-12 16:54