I am making a videogame in python that is based on an adventurer. I got the adventurer to move around with a jump-cooldown and to be able to move left or right.
import pygame
from sys import exit as end
import random
import time
pygame.init()
HEIGHT = 1200
WIDTH = 600
screen = pygame.display.set_mode((HEIGHT, WIDTH))
center_screen = (int(HEIGHT // 2), int(WIDTH // 2))
player_scale = 3
clock = pygame.time.Clock()
FPS = 60
# Land
class Land():
def __init__(self, x, y, type):
self.x = x
self.y = y
self.type = type
# Player
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, speed, grav):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.jumping = False
self.grav = grav
self.moving_left = False
self.moving_right = False
self.speed = speed
self.animation_list = []
self.frame_index = 0
self.time = pygame.time.get_ticks()
self.type = "idle"
for i in range(3):
img = pygame.image.load(f"player/{self.type}/{i}.png")
img = pygame.transform.scale(img, (int(img.get_width() * player_scale), int(img.get_height() * player_scale)))
self.animation_list.append(img)
self.player = img
self.player_rect = img.get_rect(center = (self.x, self.y))
def moving(self):
dx = 0
dy = 0
self.jump_cooldown = 1
if self.moving_left:
dx = -self.speed
if self.moving_right:
dx = self.speed
if self.jumping:
self.jump_cooldown = 0
dy = player.grav
player.grav += 1
if player.grav == 21:
self.jumping = False
self.jump_cooldown = 1
self.player_rect.x += dx
self.player_rect.y += dy
def update_animation(self):
ANIMATION_COOLDOWN = 200
self.player = self.animation_list[self.frame_index]
if pygame.time.get_ticks() - self.time > ANIMATION_COOLDOWN:
self.time = pygame.time.get_ticks()
self.frame_index += 1
if self.frame_index == len(self.animation_list):
self.frame_index = 0
def draw(self):
screen.blit(self.player, self.player_rect)
player = Player(center_screen[0], center_screen[1], 5, 1)
run = True
while True:
screen.fill((1, 255, 122))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
end()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player.moving_left = True
if event.key == pygame.K_d:
player.moving_right = True
if event.key == pygame.K_SPACE and player.jump_cooldown == 1:
player.jumping = True
player.grav = -20
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player.moving_left = False
if event.key == pygame.K_d:
player.moving_right = False
if run:
player.moving()
player.draw()
player.update_animation()
else:
pass
clock.tick(FPS)
pygame.display.update()
Now what I am trying to do is get the self.type
to switch to “jump” when I press SPACE.
(char sprites for jump and idle are 3 imgs, all name 0.png, 1.png, and 2.png)
I tried changing it into a function to change it. It still didn’t work.