Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Sprite doesn't display pygame

I'm totally new to pygame. I'm trying to reproduce a flappy bird in order to experiment this library. My issue is this one. I have methods within a Bird class. But when I use the moveBird method, the sprite is visible, but not when I use the BirdDown method and I'm not sure why. I first thought it was because it wasn't updating the sprite inside the loop so I try to blit inside it but still nothing. Some explanation would be appreciate thank you.

import pygame
from pygame.locals import *

WIDTH = 640
HEIGHT = 480

class Bird:
    def __init__(self, y, window):
        self.sprite = pygame.image.load('bird.png').convert()
        self.velocity = 1
        self.position = y
        self.window = window

    def getPosition(self):
        return self.position

    def getSpeed(self):
        return self.speed

    def moveBird(self):
        self.position += self.velocity

    def birdUpdate(self):
        self.window.blit(self.sprite, (0, self.position))

    def BirdDown(self):
        while self.position != HEIGHT:
            self.birdUpdate()
            self.position += self.velocity

and this is the main of the project

import pygame
from pygame.locals import *
import sys
from bird import Bird, WIDTH, HEIGHT

pygame.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird Clone")
te = Bird(0, screen)

def redraw():
    te.moveBird()
    #te.BirdDown()
    te.birdUpdate()
    pygame.display.update()

while 1:
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
    redraw()
question from:https://stackoverflow.com/questions/65834824/sprite-doesnt-display-pygame

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

1 Answer

0 votes
by (71.8m points)

Why is there loop in the BirdDown method? What do you expect?

You have to use the application loop. Remove the loop from Bird.birdDown:

class Bird:
    # [...]

    def birdDown(self):
        self.position += self.velocity

Call te.birdDown() in the application loop:

def redraw():
    screen.fill(0)
    te.birdUpdate()
    pygame.display.update()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygme.K_SPACE:
                te.moveBird()

    te.birdDown()
    redraw()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...