这是到目前为止我的代码。
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
是一个类。您必须分别调用对象 player
的 moveLeft
和 moveRight
方法(例如:player.moveLeft(5)
)。 player
是 Player
的实例:
(分别参见Method ObjectsInstance 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/