見出し画像

Pythonで簡単なグラフィカルなゲームを作りました

昨日はテキストベースの簡単なゲームを作ったので、今回はグラフィカルなゲームを作ってみました。

今回は基本的な「ブロック回避ゲーム」を作りました。
プレイヤーはキーボードの矢印キーを使用して画面上を移動するプレイヤーのブロックを制御し、降ってくるブロックを避けます。
プレイヤーがブロックにぶつかるとゲームが終了する、といった単純なものです。

わかりにくいですがゲーム画面です。

'pygame'のインストールが必要です。

pip install pygame
import pygame
import random

pygame.init()

# 画面サイズの設定
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 色の定義
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

# プレイヤー設定
player_width = 50
player_height = 50
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 10
player_velocity = 5

# 敵(ブロック)設定
enemy_width = 50
enemy_height = 50
enemy_x = random.randrange(0, screen_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 4

clock = pygame.time.Clock()
running = True

# ゲームのメインループ
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_velocity
    if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
        player_x += player_velocity

    screen.fill(white)

    # プレイヤーの描画
    pygame.draw.rect(screen, black, [player_x, player_y, player_width, player_height])

    # 敵の描画
    pygame.draw.rect(screen, red, [enemy_x, enemy_y, enemy_width, enemy_height])
    enemy_y += enemy_speed
    if enemy_y > screen_height:
        enemy_y = -enemy_height
        enemy_x = random.randrange(0, screen_width - enemy_width)

    # 衝突のチェック
    if enemy_y < player_y + player_height and enemy_y + enemy_height > player_y:
        if enemy_x < player_x + player_width and enemy_x + enemy_width > player_x:
            running = False

    pygame.display.update()
    clock.tick(60)

pygame.quit()

これは必要最低限のコードし書いてないので、スコアの追跡、複数の敵の追加、レベルアップのシステムなど加えたら面白くなるかもしれません。

コード変更して遊んでみたら勉強になると思います!

シキでした!

この記事が気に入ったらサポートをしてみませんか?