繁体   English   中英

我正在尝试用 python 制作游戏,首先是让角色移动,但我一直遇到同样的错误

[英]I'm trying to make a game in python, starting by getting the character moving, but i keep getting the same error

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

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是班级。 您必须分别调用对象playermoveLeft moveRight方法(例如: player.moveLeft(5) )。 playerPlayer一个实例:
(分别参见 方法对象实例对象

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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