Как переместить пигментный спрайт вверх - PullRequest
1 голос
/ 21 апреля 2020

Я использую Pygame и следую инструкциям ЗДЕСЬ . У меня есть следующий код:

import pygame
import sys
#Let's import the Car Class
from player import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)

SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            playerCar.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            playerCar.moveRight(5)
        if keys[pygame.K_UP]:
            playerCar.moveUp(5)

        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREEN)
        #Draw The Road
        pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        pygame.draw.line(screen, WHITE, [140,0],[140,300],5)

        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per secong e.g. 60
        clock.tick(60)

pygame.quit() 

if keys[pygame.K_UP]:
            playerCar.moveUp(5)

- мой собственный вклад. У меня также есть мой класс спрайтов:

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.

    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])

        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()

        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()
    def moveRight(self, pixels):
        self.rect.x += pixels

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

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

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

- мой собственный вклад. Раньше, когда мой вклад был:

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

, мой спрайт двигался вправо, когда я нажимал стрелку вверх. С кодом, как сейчас, я получаю сообщение об ошибке:

TypeError: moveUp() missing 1 required positional argument: 'y'

Как это исправить и заставить мой спрайт двигаться вверх, когда я нажимаю стрелку вверх?

1 Ответ

2 голосов
/ 21 апреля 2020

Вы хотите изменить self.rect.x на self.rect.y:

Попробуйте изменить строку

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

на эту:

def moveUp(self, pixels):
                self.rect.y += pixels
...