Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

python - I want this cube in pygame to move when I update it

My cube in which I am updating to move 5 pixels every frame, will not move. I have checked my code and I cannot find the issue, send pizza. I wish to make the cube move right 5 pixels every frame.

#---- Main-----
import pygame, sys
from os import path
from settings import *
from sprites import *

class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption(TITLE)
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()

    def update(self):
        #self.dt = self.clock.tick(FPS) / 1000
        self.new()
        self.draw()

    def draw(self):
        self.sprites.update()
        self.sprites.draw(self.screen)
        pygame.display.flip()
        self.clock.tick(30)
    def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()

    def new(self):
        self.screen.fill(DARKGREY)
        self.sprites = pygame.sprite.Group()
        player = Player(self)

    def quit(self):
        pygame.quit()
        sys.exit()


while True:
    g = Game()
    g.events()
    g.update()

separate file

#---sprites
import pygame
from settings import *

class Player(pygame.sprite.Sprite):
    def __init__(self, game):
        self.groups = game.sprites
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.image = pygame.Surface((TILESIZE, TILESIZE))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()

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

separat file

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

WIDTH = 600
HEIGHT = 500
FPS = 60
TITLE = 'bruh zelda'
PLAYER_SPEED = 100

TILESIZE = 32
TILEWIDTH = WIDTH / TILESIZE
TILEHEIGHT = HEIGHT / TILESIZE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to create the instance of the Game class before the application loop:

g = Game()
while True:
    g.events()
    g.update()

The Cube must be created in the constructor of the Game class rather than in draw:

class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption(TITLE)
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        self.new()

    def update(self):
        #self.dt = self.clock.tick(FPS) / 1000
        self.draw()

    # [...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...