Oke! Berikut contoh sederhana kode Python untuk game casual menggunakan library pygame. Game ini adalah game menangkap objek: pemain menggerakkan kotak untuk menangkap bola yang jatuh.
Pastikan kamu sudah install pygame dengan perintah:
bash
pip install pygame
Kode gamenya:
python
import pygame
import random
# Inisialisasi pygame
pygame.init()
# Ukuran layar
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Casual Catch Game")
# Warna
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Pemain
player_width, player_height = 100, 20
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - player_height - 10
player_speed = 7
# Objek yang jatuh (bola)
ball_radius = 15
ball_x = random.randint(ball_radius, WIDTH - ball_radius)
ball_y = -ball_radius
ball_speed = 5
# Skor
score = 0
# Font
font = pygame.font.SysFont(None, 36)
# Clock
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60) # 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Input pemain
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width:
player_x += player_speed
# Update posisi bola jatuh
ball_y += ball_speed
# Jika bola melewati bawah layar, reset ke atas dan kurangi skor
if ball_y > HEIGHT + ball_radius:
ball_x = random.randint(ball_radius, WIDTH - ball_radius)
ball_y = -ball_radius
score -= 1 # Penalti melewatkan bola
# Cek collision antara bola dan pemain
player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
ball_rect = pygame.Rect(ball_x - ball_radius, ball_y - ball_radius,
ball_radius * 2, ball_radius * 2)
if player_rect.colliderect(ball_rect):
score += 1
ball_x = random.randint(ball_radius, WIDTH - ball_radius)
ball_y = -ball_radius
# Gambar latar
screen.fill(WHITE)
# Gambar pemain
pygame.draw.rect(screen, BLACK, player_rect)
# Gambar bola
pygame.draw.circle(screen, RED, (ball_x, ball_y), ball_radius)
# Gambar skor
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.flip()
pygame.quit()
Game ini simpel banget: kamu menggerakkan kotak hitam dengan tombol kiri/kanan untuk menangkap bola merah yang jatuh. Skor akan bertambah jika berhasil menangkap dan berkurang jika bola terlewat.
Kalau mau dikembangkan atau buat game lain, bilang ya!