Reputation: 37
I want dinosaur to duck only when I press the space bar.
In other words, if I take off the space bar, I want the dinosaur to come back to the running position.
But now, when I press the space bar, the dinosaur goes down and doesn't come back up.
I really don't know how to fix it to implement that function.
import pygame
import os
pygame.init()
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1100
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
RUNNING = [pygame.image.load(os.path.join("Assets/Dino", "DinoRun1.png")),
pygame.image.load(os.path.join("Assets/Dino", "DinoRun2.png"))]
JUMPING = pygame.image.load(os.path.join("Assets/Dino", "DinoJump.png"))
DUCKING = [pygame.image.load(os.path.join("Assets/Dino", "DinoDuck1.png")),
pygame.image.load(os.path.join("Assets/Dino", "DinoDuck2.png"))]
class Dino:
X_POS = 80
Y_POS = 400
Y_POS_DUCK = 430
def __init__(self):
self.run_img = RUNNING
self.duck_img = DUCKING
self.dino_run = True
self.dino_duck = False
self.step_index = 0
self.image = self.run_img[0]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS
def update(self, userInput):
if self.dino_run:
self.run()
if self.dino_duck:
self.duck()
if self.step_index >= 10:
self.step_index = 0
if userInput[pygame.K_UP]:
self.dino_run = True
self.dino_duck = False
self.Y_POS = 100
self.Y_POS_DUCK = 130
elif userInput[pygame.K_DOWN]:
self.dino_run = True
self.dino_duck = False
self.Y_POS = 400
self.Y_POS_DUCK = 430
***elif userInput[pygame.K_SPACE]:
self.dino_run = False
self.dino_duck = True***
def run(self):
self.image = self.run_img[self.step_index // 5]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS
self.step_index += 1
def duck(self):
self.image = self.duck_img[self.step_index // 5]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS_DUCK
self.step_index += 1
def draw(self, SCREEN):
SCREEN.blit(self.image, (self.dino_rect.x, self.dino_rect.y))
def main():
run = True
clock = pygame.time.Clock()
player = Dino()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
SCREEN.fill((255, 255, 255))
userInput = pygame.key.get_pressed()
player.draw(SCREEN)
player.update(userInput)
clock.tick(30)
pygame.display.update()
Upvotes: 0
Views: 68
Reputation: 6176
In the update
method add another if
statement to check when spacebar is released:
...
elif userInput[pygame.K_SPACE]:
self.dino_run = False
self.dino_duck = True
if not userInput[pygame.K_SPACE]:
self.dino_run = True
self.dino_duck = False
Upvotes: 1