This is the first game I have tried to make on PyGame, and I have followed the PyGame Primer tutorial (https://realpython.com/pygame-a-primer/) to do so. I'm practically done, but when I run the game, it runs incredibly slowly when I provide no input. when I spam-click an arrow key, the game will run smoothly, but if I don't do anything or hold down a key, it will run at < 10 FPS. How could I change it so that it will run consistently regardless of input? This is my code:
import pygame
import random
from pygame.locals import *
FPS = 25
fpsclock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.image = pygame.image.load('Images/Star-Rider.png').convert()
self.image.set_colorkey((0, 0, 0), RLEACCEL)
self.rect = self.image.get_rect()
def update(self, pressed_keys):
if pressed_keys[K_UP]:
self.rect.move_ip(0, -20)
if pressed_keys[K_DOWN]:
self.rect.move_ip(0, 20)
if pressed_keys[K_LEFT]:
self.rect.move_ip(-20, 0)
if pressed_keys[K_RIGHT]:
self.rect.move_ip(20, 0)
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > 800:
self.rect.right = 800
if self.rect.top < 0:
self.rect.top = 0
elif self.rect.bottom > 600:
self.rect.bottom = 600
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super(Enemy, self).__init__()
self.image = pygame.image.load('Images/Hand-Projectile.png').convert()
self.image.set_colorkey((0, 0, 0), RLEACCEL)
self.rect = self.image.get_rect(center=(random.randint(820, 900), random.randint(0,600)))
self.speed = random.randint(5,20)
def update(self):
self.rect.move_ip(-self.speed, 0)
if self.rect.right < 0:
self.kill
pygame.init()
screen = pygame.display.set_mode((800,600))
ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 1000)
player = Player()
enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
elif event.type == ADDENEMY:
new_enemy = Enemy()
enemies.add(new_enemy)
all_sprites.add(new_enemy)
pressed_keys = pygame.key.get_pressed()
if pressed_keys:
player.update(pressed_keys)
enemies.update()
screen.fill((135,206,250))
screen.blit(entity.image, entity.rect)
if pygame.sprite.spritecollideany(player, enemies):
player.kill()
pygame.display.flip()
fpsclock.tick(FPS)
Thank you for taking the time to read this! Any advice would be much appreciated!