0
\$\begingroup\$

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!

\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

Your logic is uuh, ordered incorrectly. You're doing

  • While the game is running
    • For each event
      • Handle the event
      • Render a frame

Your logic should be

  • While the game is running
    • For each event
      • Handle the event
    • Render a frame

Indentation matters in python. You probably want to unindent everything from pressed_keys and down.

\$\endgroup\$
0
-3
\$\begingroup\$
import pygame
import random

# Inisialisasi Pygame
pygame.init()

# Konstanta
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 30
WHITE = (255, 255, 255)
BLUE = (135, 206, 235)
GREEN = (34, 139, 34)
FISH_SPEED = 2
HOOK_SPEED = 5
BOBBER_SPEED = 2

# Membuat layar
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Game Memancing Sederhana")

# Load aset (gambar bisa diganti sesuai keinginan)
try:
    angler_img = pygame.image.load("angler.png").convert_alpha()
    fish_img = pygame.image.load("fish.png").convert_alpha()
    hook_img = pygame.image.load("hook.png").convert_alpha()
    bobber_img = pygame.image.load("bobber.png").convert_alpha()
except pygame.error as e:
    print(f"Error loading image: {e}")
    pygame.quit()
    exit()

angler_rect = angler_img.get_rect(center=(SCREEN_WIDTH // 4, SCREEN_HEIGHT - 50))
fish_rect = fish_img.get_rect()
hook_rect = hook_img.get_rect(midtop=(angler_rect.midtop))
bobber_rect = bobber_img.get_rect(midbottom=hook_rect.midbottom)

# Posisi awal ikan secara acak
fish_rect.x = random.randint(SCREEN_WIDTH // 2, SCREEN_WIDTH - fish_img.get_width())
fish_rect.y = random.randint(50, SCREEN_HEIGHT // 2)
fish_direction = random.choice([-1, 1]) # -1 untuk kiri, 1 untuk kanan

# Status memancing
casting = False
reeling = False
fish_caught = False

# Skor
score = 0
font = pygame.font.Font(None, 36)

def draw_environment():
    screen.fill(BLUE)
    pygame.draw.rect(screen, GREEN, (0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100)) # Tanah
    screen.blit(angler_img, angler_rect)

def draw_fish():
    screen.blit(fish_img, fish_rect)

def draw_hook_and_bobber():
    if casting or reeling:
        screen.blit(hook_img, hook_rect)
        screen.blit(bobber_img, bobber_rect)

def display_score():
    score_text = font.render(f"Skor: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

# Game loop
running = True
clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and not casting and not reeling and not fish_caught:
                casting = True
                hook_rect.midtop = angler_rect.midtop
                bobber_rect.midbottom = hook_rect.midbottom
            elif event.key == pygame.K_SPACE and casting and not reeling:
                reeling = True

    # Pergerakan ikan
    if not fish_caught:
        fish_rect.x += FISH_SPEED * fish_direction
        if fish_rect.left < SCREEN_WIDTH // 2 or fish_rect.right > SCREEN_WIDTH:
            fish_direction *= -1
            fish_rect.y += random.randint(-20, 20)
            if fish_rect.top < 50:
                fish_rect.top = 50
            elif fish_rect.bottom > SCREEN_HEIGHT // 2:
                fish_rect.bottom = SCREEN_HEIGHT // 2

    # Mekanika melempar kail
    if casting:
        hook_rect.y -= HOOK_SPEED
        bobber_rect.midbottom = hook_rect.midbottom
        if hook_rect.top < 0:
            casting = False
            hook_rect.midtop = angler_rect.midtop
            bobber_rect.midbottom = hook_rect.midbottom

    # Mekanika menarik kail
    if reeling:
        hook_rect.y += BOBBER_SPEED
        bobber_rect.midbottom = hook_rect.midbottom
        if hook_rect.bottom > angler_rect.top:
            reeling = False
            hook_rect.midtop = angler_rect.midtop
            bobber_rect.midbottom = hook_rect.midbottom
            if fish_caught:
                fish_rect.x = random.randint(SCREEN_WIDTH // 2, SCREEN_WIDTH - fish_img.get_width())
                fish_rect.y = random.randint(50, SCREEN_HEIGHT // 2)
                fish_direction = random.choice([-1, 1])
                fish_caught = False

    # Deteksi tabrakan antara kail dan ikan
    if casting and hook_rect.colliderect(fish_rect):
        casting = False
        reeling = True
        fish_caught = True
        score += 1

    # Jika ikan tertangkap, posisikan di atas kail
    if fish_caught:
        fish_rect.midbottom = hook_rect.midtop

    # Gambar elemen game
    draw_environment()
    draw_fish()
    draw_hook_and_bobber()
    display_score()

    # Update layar
    pygame.display.flip()

    # Batasi kecepatan frame
    clock.tick(FPS)

# Keluar dari Pygame
pygame.quit()
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Please post in English on this site. \$\endgroup\$ Commented May 8 at 13:52
  • 3
    \$\begingroup\$ You simply posted your own code without any context? I also don't see how this adds anything that the previous answer from six years ago didn't already address. \$\endgroup\$ Commented May 8 at 18:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.