【ゼロから始めるPython】Pythonでブロック崩しゲームを作ってみよう!

Python
この記事を書いた人
柊あい

生成AI研究家。新卒で一般企業に就職するも、日々の過酷な残業でメンタルを崩し、退職。
そんな中、生成AIに出会い、当時はまだ珍しかったAI活用フリーランサーとして活動。現在はAI活用を広めるインフルエンサーとして、本サイトの記事の執筆を担当。

公式SNSをフォローする

はじめに

ブロック崩しは、シンプルでありながら楽しいゲームで、プログラミングの学習にも最適です。

この記事では、PythonのPygameライブラリを使用して、基本的なブロック崩しゲームを作成する方法をステップバイステップで解説します。

本ゲームでは、ボール、バー(プレイヤーの操作するパドル)、そして破壊するためのブロックが登場します。

また、ゲームのスタート画面、ゲームプレイ中の操作、そしてゲームクリアやゲームオーバー時の画面遷移についても取り上げます。それでは、コードを書きながら、PythonとPygameの基本を学びましょう。

Pythonで制作できるゲーム一覧はこちらの記事で確認できます!

準備: 必要なライブラリのインストール

まず、pygameライブラリをインストールします。以下のコマンドをターミナルで実行してください。

pygameはゲーム開発用のライブラリで、グラフィックスの表示、音の再生、イベントの取り扱いなど、ゲーム開発に必要な機能を提供します。sysはPythonの組み込みモジュールで、スクリプトの実行を制御する関数を持っています。

pip install pygame

ステップ1: 必要なライブラリをインポート

最初に、Pythonのpygameモジュールとsysモジュールをインポートします。

import pygame
import sys

ステップ2: Pygameの初期化と基本設定

Pygameを使用するための初期設定を行います。画面のサイズを定義し、ウィンドウを生成します。また、ゲームで使用する色やフォントの設定もこの段階で行います。

import pygame
import sys

# Pygameの初期化
pygame.init()

# ウィンドウの設定
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('ブロック崩しゲーム')

# 色の設定
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# フォントの設定
font = pygame.font.Font(None, 36)

ステップ3: ゲームオブジェクトの設定

ゲームに必要なオブジェクトを設定します。これにはボール、プレイヤーが操作するバー、そして壊すべきブロックが含まれます。各オブジェクトは特定のサイズと位置で初期化されます。

# ボールの設定
ball_size = 20
ball = pygame.Rect(width / 2 - ball_size / 2, height - 50 - ball_size, ball_size, ball_size)

# プレイヤー(バー)の設定
player_width = 100
player_height = 20
player = pygame.Rect(width / 2 - player_width / 2, height - 40, player_width, player_height)

# ブロックの設定
block_width = 60
block_height = 20
blocks = [pygame.Rect(x * (block_width + 10) + 50, y * (block_height + 10) + 50, block_width, block_height) for x in range(10) for y in range(4)]

Pythonでのゲーム制作を学びたい人はこちらの書籍がおすすめです!

Amazon.co.jp: Pythonではじめるゲーム制作 超入門 知識ゼロからのプログラミング&アルゴリズムと数学 eBook : 廣瀬 豪: 本
Amazon.co.jp: Pythonではじめるゲーム制作 超入門 知識ゼロからのプログラミング&アルゴリズムと数学 eBook : 廣瀬 豪: 本

ステップ4: ゲームのメインループとステートマシン

ゲームのメインループを設定し、ゲームの状態(スタート画面、プレイ中、ゲームオーバー、ゲームクリア)に応じて異なる処理を行います。このループはゲームが終了するまで続きます。各イベントに対して適切な応答を行い、ゲームのロジックを管理します。

def main_game():
    global ball, player, blocks
    ball_speed_x = 4
    ball_speed_y = -4
    player_speed = 0

    running = True
    game_state = 'start'  # スタート画面から始める

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if game_state in ['game_over', 'game_clear']:
                        game_state = 'start'
                        ball = pygame.Rect(width / 2 - ball_size / 2, height - 50 - ball_size, ball_size, ball_size)
                        player = pygame.Rect(width / 2 - player_width / 2, height - 40, player_width, player_height)
                        blocks = [pygame.Rect(x * (block_width + 10) + 50, y * (block_height + 10) + 50, block_width, block_height) for x in range(10) for y in range(4)]
                    elif game_state == 'start':
                        game_state = 'play'
                if game_state == 'play':
                    if event.key == pygame.K_LEFT:
                        player_speed = -6
                    elif event.key == pygame.K_RIGHT:
                        player_speed = 6
            if event.type == pygame.KEYUP:
                if game_state == 'play':
                    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                        player_speed = 0

        # ゲームのロジック
        if game_state == 'play':
            player.x += player_speed
            if player.left <= 0:
                player.left = 0
            if player.right >= width:
                player.right = width

            ball.x += ball_speed_x
            ball.y += ball_speed_y

            if ball.top <= 0:
                ball_speed_y = -ball_speed_y
            if ball.bottom >= height:
                game_state = 'game_over'
            if ball.left <= 0 or ball.right >= width:
                ball_speed_x = -ball_speed_x

            if ball.colliderect(player):
                ball_speed_y = -ball_speed_y

            for block in blocks[:]:
                if ball.colliderect(block):
                    ball_speed_y = -ball_speed_y
                    blocks.remove(block)
            if not blocks:
                game_state = 'game_clear'

        # 画面の描画
        screen.fill(BLACK)
        if game_state == 'start':
            text = font.render('Press Enter to start', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))
        elif game_state == 'play':
            pygame.draw.rect(screen, BLUE, player)
            pygame.draw.ellipse(screen, RED, ball)
            for block in blocks:
                pygame.draw.rect(screen, GREEN, block)
        elif game_state == 'game_over':
            text = font.render('Game Over! Press Enter to restart', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))
        elif game_state == 'game_clear':
            text = font.render('Game Clear! Press Enter to restart', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))

        pygame.display.flip()
        pygame.time.Clock().tick(60)

main_game()


コード全体

import pygame
import sys

# Pygameの初期化
pygame.init()

# ウィンドウの設定
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('ブロック崩しゲーム')

# 色の設定
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# フォントの設定
font = pygame.font.Font(None, 36)

# ボールの設定
ball_size = 20
ball = pygame.Rect(width / 2 - ball_size / 2, height - 50 - ball_size, ball_size, ball_size)

# プレイヤー(バー)の設定
player_width = 100
player_height = 20
player = pygame.Rect(width / 2 - player_width / 2, height - 40, player_width, player_height)

# ブロックの設定
block_width = 60
block_height = 20
blocks = [pygame.Rect(x * (block_width + 10) + 50, y * (block_height + 10) + 50, block_width, block_height) for x in range(10) for y in range(4)]

# ゲームのメインループ
def main_game():
    global ball, player, blocks
    ball_speed_x = 4
    ball_speed_y = -4
    player_speed = 0

    running = True
    game_state = 'start'  # スタート画面から始める

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if game_state in ['game_over', 'game_clear']:
                        game_state = 'start'
                        ball = pygame.Rect(width / 2 - ball_size / 2, height - 50 - ball_size, ball_size, ball_size)
                        player = pygame.Rect(width / 2 - player_width / 2, height - 40, player_width, player_height)
                        blocks = [pygame.Rect(x * (block_width + 10) + 50, y * (block_height + 10) + 50, block_width, block_height) for x in range(10) for y in range(4)]
                    elif game_state == 'start':
                        game_state = 'play'
                if game_state == 'play':
                    if event.key == pygame.K_LEFT:
                        player_speed = -6
                    elif event.key == pygame.K_RIGHT:
                        player_speed = 6
            if event.type == pygame.KEYUP:
                if game_state == 'play':
                    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                        player_speed = 0

        # ゲームのロジック
        if game_state == 'play':
            player.x += player_speed
            if player.left <= 0:
                player.left = 0
            if player.right >= width:
                player.right = width

            ball.x += ball_speed_x
            ball.y += ball_speed_y

            if ball.top <= 0:
                ball_speed_y = -ball_speed_y
            if ball.bottom >= height:
                game_state = 'game_over'
            if ball.left <= 0 or ball.right >= width:
                ball_speed_x = -ball_speed_x

            if ball.colliderect(player):
                ball_speed_y = -ball_speed_y

            for block in blocks[:]:
                if ball.colliderect(block):
                    ball_speed_y = -ball_speed_y
                    blocks.remove(block)
            if not blocks:
                game_state = 'game_clear'

        # 画面の描画
        screen.fill(BLACK)
        if game_state == 'start':
            text = font.render('Press Enter to start', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))
        elif game_state == 'play':
            pygame.draw.rect(screen, BLUE, player)
            pygame.draw.ellipse(screen, RED, ball)
            for block in blocks:
                pygame.draw.rect(screen, GREEN, block)
        elif game_state == 'game_over':
            text = font.render('Game Over! Press Enter to restart', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))
        elif game_state == 'game_clear':
            text = font.render('Game Clear! Press Enter to restart', True, WHITE)
            screen.blit(text, (width / 2 - text.get_width() / 2, height / 2 - text.get_height() / 2))

        pygame.display.flip()
        pygame.time.Clock().tick(60)

main_game()

プレイ画面

以下のコマンドを実行して、実際に作ったゲームで遊んでみましょう。

ファイルの名前の部分(block_kuzusshi)は、皆さんがつけた名前に適宜変えてください。

python block_kuzusshi.py

実際にゲームを実行した時の画面が下記の通りです。

エンターキーを押すとゲームがスタートします。

ボールが落ちてしまうとゲームオーバーとなります。

全てのブロックを消せるとゲームクリア画面が表示されますね!

まとめ

さて、このチュートリアルでは、pygameを使ったブロック崩しを作成する方法を学びました。このコードを改良することで、さらに複雑なゲームに挑戦できます。

ところで、ここでここまで記事を読んでいただいた皆さんにお知らせしなければならないことがあります…

実は、このプログラム、ChatGPTに全て書いてもらっているのです。

ChatGPTを使えば、今までエンジニアが数時間掛けて書いていたコードを、ものの3分で作成してくれます。

これからエンジニアとして活躍したい方、文系からエンジニアを目指したい方は、ぜひChatGPTの活用方法を学んで、高度なIT人材になりましょう!

ChatGPTを使ってPythonでゲームを制作したい方は、こちらのAIスクールがおすすめです!

ChatGPT活用塾
「起業家として成功したい」「フリーランスで稼ぎたい」「副業で稼ぎたい」そんな方々向けのChatGPT講座。eラーニング+コーチングであなたの業務を効率化させます。

なお、当サイト限定の特典として、無料面談フォーム入力時に下記の招待コードを入力すると、受講料が20%OFFになります!!!

ChatGPT活用塾に入塾を検討されている方は、ぜひ、こちらの割引をご利用ください!!

招待コード:STAIT2025