python virus (game)
- User
python virus (game)
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
python virus (game)
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Berikut contoh mini‑game bertema “virus” (bukan virus sungguhan, tentu saja) yang dibuat dengan pygame. Pemain menggerakkan “antivirus” untuk menembak ikon virus yang jatuh dari atas layar.
Anda bisa men‐copy kode di bawah ke file virus_game.py.
# -------------------------------
# Mini Game: Virus Invader
# Dibuat dengan pygame
# -------------------------------
import pygame
import random
import sys
# --- Inisialisasi ---
pygame.init()
WIDTH, HEIGHT = 500, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Virus Invader – Python Mini Game")
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (220, 20, 60)
GREEN = (50, 205, 50)
FONT = pygame.font.SysFont("Arial", 24)
# --- Pemain (Antivirus) ---
PLAYER_SIZE = 50
player_img = pygame.Surface((PLAYER_SIZE, PLAYER_SIZE))
player_img.fill(GREEN)
# --- Peluru ---
BULLET_W, BULLET_H = 5, 10
BULLET_SPEED = -7
# --- Musuh (Virus) ---
ENEMY_SIZE = 40
enemy_img = pygame.Surface((ENEMY_SIZE, ENEMY_SIZE))
enemy_img.fill(RED)
ENEMY_SPEED = 3
SPAWN_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN_EVENT, 700) # spawn setiap 700 ms
# -----------------------------
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_img
self.rect = self.image.get_rect(midbottom=(WIDTH//2, HEIGHT-10))
self.speed = 6
def update(self, keys):
if keys[pygame.K_LEFT] and self.rect.left > 0:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT] and self.rect.right < WIDTH:
self.rect.x += self.speed
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((BULLET_W, BULLET_H))
self.image.fill(WHITE)
self.rect = self.image.get_rect(center=(x, y))
def update(self, *_):
self.rect.y += BULLET_SPEED
if self.rect.bottom < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_img
self.rect = self.image.get_rect(
midtop=(random.randint(ENEMY_SIZE//2, WIDTH-ENEMY_SIZE//2), -ENEMY_SIZE)
)
def update(self, *_):
self.rect.y += ENEMY_SPEED
if self.rect.top > HEIGHT:
self.kill()
# -----------------------------
def draw_text(surface, text, pos, color=WHITE):
img = FONT.render(text, True, color)
rect = img.get_rect(topleft=pos)
surface.blit(img, rect)
# -----------------------------
def main():
global all_sprites, bullets, enemies
clock = pygame.time.Clock()
score = 0
running = True
player = Player()
all_sprites = pygame.sprite.Group(player)
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == SPAWN_EVENT:
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
player.shoot()
# --- Update ---
keys = pygame.key.get_pressed()
all_sprites.update(keys)
# --- Collision: bullet vs enemy ---
hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
score += len(hits)
# --- Collision: enemy vs player (game over) ---
if pygame.sprite.spritecollideany(player, enemies):
running = False
# --- Gambar ke layar ---
WIN.fill(BLACK)
all_sprites.draw(WIN)
draw_text(WIN, f"Score: {score}", (10, 10))
pygame.display.flip()
# --- Game Over Screen ---
WIN.fill(BLACK)
draw_text(WIN, "GAME OVER", (WIDTH//2 - 80, HEIGHT//2 - 30))
draw_text(WIN, f"Final Score: {score}", (WIDTH//2 - 90, HEIGHT//2 + 10))
pygame.display.flip()
pygame.time.wait(2500)
pygame.quit()
sys.exit()
# -----------------------------
if __name__ == "__main__":
main()
Cara Menjalankan:
pygame (sekali saja):
pip install pygame
virus_game.py.python virus_game.py
Kontrol:
• ← / → : Gerakkan antivirus.
• Spasi : Tembak peluru.
Tujuan:
Hancurkan sebanyak mungkin “virus” merah dan hindari tertabrak. Semoga menyenangkan! 🎮
ada error di kodenya saat aku jalanin di programiz
Kemungkinan besar bukan kodenya yang “rusak”, melainkan lingkungan Programiz on‑line yang memang tidak mendukung aplikasi grafis Pygame. Di mayoritas IDE berbasis web (termasuk Programiz, Replit versi biasa, dsb.):
• Tidak ada server X / display → Pygame tidak bisa membuat jendela.
• Modul pygame belum ter‑install dan tidak boleh di‑install oleh user.
Akibatnya Anda biasanya mendapat salah satu error berikut:
ModuleNotFoundError: No module named 'pygame'
atau
pygame.error: No available video device
| # | Opsi | Penjelasan Singkat |
|---|---|---|
| 1 | Jalankan di komputer lokal | • Install Python + pip install pygame.• Copy file virus_game.py lalu python virus_game.py. |
| 2 | Pakai cloud IDE yang mendukung grafis | Contoh: Replit “Pygame” template, Gitpod + VNC, Codespaces + Xvfb, d‑ll. |
| 3 | Set SDL_VIDEODRIVER="dummy" (headless) | Hanya untuk uji unit‐test; tidak muncul jendela, jadi gamenya tidak bisa dimainkan. |
| 4 | Ubah jadi game berbasis teks | Jika Anda harus tetap di Programiz, tulis ulang game memakai output teks (mis. ASCII art) atau gunakan modul curses (tetap text‑mode). |
| 5 | Bagikan error‑log lengkap | Kalau ternyata Anda menjalankan di lingkungan lain yang mendukung grafis namun masih error, paste pesan error‑nya supaya saya bisa mem‑debug detail. |
Di bawah ini mini‑game sederhana yang hanya memakai console, jadi tidak butuh Pygame:
"""
Virus Dodge – versi teks
Pemain (A) di bagian bawah layar menghindari virus (V) yang jatuh.
Gunakan a / d (kiri / kanan) lalu Enter untuk bergerak.
"""
import os, random, time, sys
WIDTH = 20 # lebar arena
HEIGHT = 10 # tinggi arena
SPEED = 0.2 # jeda antar frame (detik)
player_x = WIDTH // 2
virus_y = -1 # belum muncul
virus_x = random.randint(0, WIDTH - 1)
score = 0
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def draw():
clear()
for y in range(HEIGHT):
line = ''
for x in range(WIDTH):
if y == virus_y and x == virus_x:
line += 'V'
elif y == HEIGHT - 1 and x == player_x:
line += 'A'
else:
line += '.'
print(line)
print(f'Score: {score}')
print('Gerak: a = kiri, d = kanan, q = quit')
try:
while True:
draw()
# input non‑blocking sederhana
start = time.time()
command = ''
while time.time() - start < SPEED:
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
command = sys.stdin.readline().strip()
break
if command == 'q':
break
elif command == 'a' and player_x > 0:
player_x -= 1
elif command == 'd' and player_x < WIDTH - 1:
player_x += 1
# gerakkan virus
virus_y += 1
if virus_y >= HEIGHT:
virus_y = 0
virus_x = random.randint(0, WIDTH - 1)
score += 1
# deteksi tabrakan
if virus_y == HEIGHT - 1 and virus_x == player_x:
draw()
print('GAME OVER!')
break
except KeyboardInterrupt:
pass
Kode di atas bersifat full console, jadi bisa dijalankan di Programiz atau IDE daring mana pun yang hanya mendukung input/output teks.
• Programiz tidak mendukung Pygame, jadi wajar muncul error.
• Coba jalankan di mesin lokal atau cloud IDE yang memang menyediakan display.
• Kalau tetap mau di Programiz, gunakan versi teks seperti contoh di atas.
• Jika error terjadi di lingkungan lain, kirim pesan error lengkapnya supaya bisa kita perbaiki bareng‑bareng.