pythonコード百科事典

コピペですぐ使えるPythonコードをご紹介

Pythonで簡単なゲームを作成する(ピンポンゲーム)

概要とサンプルコード

Pythonでゲームを作成するには、様々なライブラリやフレームワークがあります。
以下に、pygameを用いたゲーム作成のサンプルを紹介します。

# Pygame モジュールをインポートする
import pygame

# Pygame の初期化
pygame.init()

# ウィンドウのサイズを設定する
width, height = 640, 480
screen = pygame.display.set_mode((width, height))

# ゲームのタイトルを設定する
pygame.display.set_caption('Ping Pong')

# ボールを作成する
ball_x, ball_y = width / 2, height / 2
ball_radius = 10
ball_color = (255, 255, 255)
ball_speed_x, ball_speed_y = 1, 1

# バーを作成する
bar_width, bar_height = 15, 100
bar_x, bar_y = 20, height / 2 - bar_height / 2
bar_color = (255, 255, 255)
bar_speed = 5

# スコアを保存する変数
score = 0

# メインループ
running = True
while running:
    # イベントを処理する
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                bar_y = max(bar_y - bar_speed, 0)
            if event.key == pygame.K_DOWN:
                bar_y = min(bar_y + bar_speed, height - bar_height)

    # ボールを移動させる
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # 壁との衝突判定
    if ball_x < ball_radius or ball_x > width - ball_radius:
        ball_speed_x = -ball_speed_x
    if ball_y < ball_radius or ball_y > height - ball_radius:
        ball_speed_y = -ball_speed_y

    # ボールが左辺に衝突した時のみスコアをリセットする
    if ball_x < ball_radius:
        # スコアをリセットする
        score = 0
        # ボールを初期位置に戻す
        ball_x, ball_y = width / 2, height / 2
    # バーとの衝突判定
    if ball_x < bar_x + bar_width and ball_x > bar_x and ball_y < bar_y + bar_height and ball_y > bar_y:
        ball_speed_x = -ball_speed_x
        # スコアをインクリメントする
        score += 1

    # 画面をクリアする
    screen.fill((0, 0, 0))

    # ボールを描画する
    pygame.draw.circle(screen, ball_color, (int(ball_x), int(ball_y)), ball_radius)

    # バーを描画する
    pygame.draw.rect(screen, bar_color, (bar_x, bar_y, bar_width, bar_height))

    # スコアを表示する
    font = pygame.font.Font(None, 30)
    text = font.render(f'Score: {score}', True, (255, 255, 255))
    screen.blit(text, (width - 100, 10))

    # 画面を更新する
    pygame.display.flip()

# Pygame を終了する
pygame.quit()