Pythonを使って簡単なレースゲームを作ってみましょう。
必要なもの
- Python 3.x
- Pygame ライブラリ
ゲームのルール
- プレイヤーは左右の矢印キーで車を操作する。
- 画面上には障害物が出現し、それを避けながら進む。
- 障害物にぶつかるとゲームオーバー。
ゲームの作り方
-
Pygame ライブラリをインストールする。
pip install pygame -
画面を作成する。
import pygame WIDTH = 800 HEIGHT = 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) -
車の画像を読み込む。
car_image = pygame.image.load('car.png') -
ゲームループを作成する。
while True: # イベント処理 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # 車を描画 screen.blit(car_image, (x, y)) # 画面を更新 pygame.display.update() -
車を操作するためのコードを追加する。
keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= 5 if keys[pygame.K_RIGHT]: x += 5 -
障害物を作成し、車との衝突判定を追加する。
obstacle_image = pygame.image.load('obstacle.png') obstacle_x = 400 obstacle_y = 0 if y < obstacle_y + obstacle_image.get_height(): if x + car_image.get_width() > obstacle_x and x < obstacle_x + obstacle_image.get_width(): game_over() -
ゲームオーバーの処理を追加する。
def game_over(): # ゲームオーバーの画面を表示 font = pygame.font.Font(None, 36) text = font.render('Game Over', True, (255, 0, 0)) text_rect = text.get_rect(center=(WIDTH/2, HEIGHT/2)) screen.blit(text, text_rect) pygame.display.update() # 3秒待機して終了 pygame.time.wait(3000) pygame.quit() sys.exit()
完成したゲームのサンプルコード
import sys
import pygame
WIDTH = 800
HEIGHT = 600
def game_over():
# ゲームオーバーの画面を表示
font = pygame.font.Font(None, 36)
text = font.render('Game Over', True, (255, 0, 0))
text_rect = text.get_rect(center=(WIDTH/2, HEIGHT/2))
screen.blit(text
, text_rect)
pygame.display.update()
# 3秒待機して終了
pygame.time.wait(3000)
pygame.quit()
sys.exit()
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Race Game')
car_image = pygame.image.load('car.png')
obstacle_image = pygame.image.load('obstacle.png')
x = 400
y = 500
obstacle_x = 400
obstacle_y = 0
clock = pygame.time.Clock()
while True:
clock.tick(60)
# イベント処理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 車を操作
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= 5
if keys[pygame.K_RIGHT]:
x += 5
# 障害物を移動
obstacle_y += 10
if obstacle_y > HEIGHT:
obstacle_x = random.randint(0, WIDTH - obstacle_image.get_width())
obstacle_y = -obstacle_image.get_height()
# 衝突判定
if y < obstacle_y + obstacle_image.get_height():
if x + car_image.get_width() > obstacle_x and x < obstacle_x + obstacle_image.get_width():
game_over()
# 描画
screen.fill((255, 255, 255))
screen.blit(car_image, (x, y))
screen.blit(obstacle_image, (obstacle_x, obstacle_y))
pygame.display.update()