Dino Game Python Code: Simple Obstacle Avoidance Game
Tentu! Berikut adalah contoh kode untuk game Dino:
import pygame
import random
# Inisialisasi pygame
pygame.init()
# Ukuran layar game
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Dino Game')
# Warna yang digunakan dalam game
white = (255, 255, 255)
black = (0, 0, 0)
# Ukuran dino
dino_width = 64
dino_height = 64
# Koordinat dino
dino_x = 50
dino_y = screen_height - dino_height - 50
# Kecepatan jatuh dan lompat dino
fall_speed = 0
jump_force = 10
# Koordinat dan kecepatan rintangan (cactus)
cactus_width = 32
cactus_height = 64
cactus_x = screen_width
cactus_y = screen_height - cactus_height - 50
cactus_speed = 5
# Skor pemain
score = 0
font = pygame.font.Font('freesansbold.ttf', 20)
def show_score():
score_text = font.render('Score: ' + str(score), True, black)
screen.blit(score_text, (10, 10))
def game_over():
game_over_text = font.render('Game Over', True, black)
screen.blit(game_over_text, (screen_width // 2 - 50, screen_height // 2))
# Looping game
running = True
game_over_flag = False
while running:
screen.fill(white)
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 dino_y == screen_height - dino_height - 50:
fall_speed = -jump_force
if not game_over_flag:
# Pergerakan dino
fall_speed += 1
dino_y += fall_speed
# Pergerakan rintangan (cactus)
cactus_x -= cactus_speed
# Jika rintangan melewati layar
if cactus_x < -cactus_width:
cactus_x = screen_width
score += 1
# Jika dino menabrak rintangan
if dino_x < cactus_x + cactus_width and dino_x + dino_width > cactus_x and dino_y + dino_height > cactus_y:
game_over_flag = True
# Gambar dino
pygame.draw.rect(screen, black, (dino_x, dino_y, dino_width, dino_height))
# Gambar rintangan (cactus)
pygame.draw.rect(screen, black, (cactus_x, cactus_y, cactus_width, cactus_height))
show_score()
else:
game_over()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
game_over_flag = False
score = 0
dino_y = screen_height - dino_height - 50
cactus_x = screen_width
pygame.display.update()
# Keluar dari pygame
pygame.quit()
Kode ini menggunakan pygame untuk membuat game Dino sederhana. Dalam game ini, pemain harus menghindari rintangan (cactus) dengan melompat menggunakan tombol spasi. Skor pemain akan bertambah setiap kali rintangan berhasil dilewati. Jika pemain menabrak rintangan, game over dan pemain dapat memulai kembali dengan menekan tombol enter.
原文地址: https://www.cveoy.top/t/topic/qCkA 著作权归作者所有。请勿转载和采集!