Reputation: 353
I can't figure out how to loop through the jump function without having it in the first 'while True' block. None of the proposed alternatives have worked so far. Currently the only way I get it to work is having to press spacebar for each step of the jump.
import pygame
from pygame import Color
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.vy = 5
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
if self.isJump:
# using 'while' doesn't work either
if self.jumpCount >= -10:
# this doesn't work -> pygame.time.delay(100)
print(self.jumpCount)
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.jumpCount = 10
self.isJump = False
return self.isJump
def move(self):
return
def run():
bird = Bird()
while True:
pygame.time.delay(100)
# only works if I put 'bird.isJump = True, bird.jump()' here, and then it loops continuously
surface.fill(Color("blue"))
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.isJump = True
bird.jump()
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.flip()
run()
Upvotes: 0
Views: 31
Reputation: 1447
You could call the move
method every time you run the game loop, along with draw
, then call the jump
method only once, when space is clicked.
The result will be (with a few other minor changes, such as calling pygame.init
, quitting with quit
instead of pygame.quit
and removing redundant class members):
import pygame
from pygame import Color
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
self.jumpCount = 10
self.isJump = True
def move(self):
if self.isJump:
if self.jumpCount >= -10:
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.isJump = False
def run():
bird = Bird()
while True:
pygame.time.delay(100)
surface.fill(Color("blue"))
bird.move()
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.jump()
if event.type == pygame.QUIT:
quit()
pygame.display.flip()
pygame.init()
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
run()
Upvotes: 1