Cocos2d で動きのシミュレーション

概要

Cocos2d は Python で動作する2次元ゲームのフレームワークである。このページでは、動きのシミュレーションの基本を、見本プログラムを用いた演習で学ぶ。

Cocos2d 上で、ゲームの登場物(MyActor クラス)に位置と速度の属性を持たせ、自動で動くシミュレーションを段階的に構築する。1つのオブジェクトの表示から始め、位置と速度によるシミュレーション、複数オブジェクトへの拡張、プレイヤー操作と当たり判定の追加、重力シミュレーションの導入へと進む。

目次

関連する外部ページ

https://www.cocos.com/endoc.html

http://docplayer.net/62131747-Python-game-programming-by-example.html

サイト内の関連情報

Cocos2d の概要 [PDF], [パワーポイント]

ゲームエンジン[PDF], [パワーポイント]

1. 前準備

Python 3.12 のインストール

Pythonのインストールを行い、Pythonのプログラムを実行する環境を整える。扱う環境は、Windows搭載パソコンである。金子研究室では、Python 3.12.10を推奨する。

[Windows での Python 3.12 のインストール手順を見るには、ここをクリック]

Windows での Python 3.12 のインストール

以下のいずれかの方法でPython 3.12をインストールする。Pythonがインストール済みの場合、この手順は不要である。

方法 1:winget によるインストール

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動するとPATHが反映される。

REM Python 3.12 をシステム領域にインストール
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; $c=[Environment]::GetEnvironmentVariable('Path','Machine'); if((Test-Path $p) -and (';'+$c+';' -notlike \"*;$p;*\") -and (';'+$c+';' -notlike \"*;$s;*\")){[Environment]::SetEnvironmentVariable('Path',\"$p;$s;$c\",'Machine')}"

方法 2:インストーラーによるインストール

  1. Python公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンからWindows用インストーラーをダウンロードする。
  2. ダウンロードしたインストーラーを実行する。
  3. 初期画面の下部に表示される「Add python.exe to PATH」にチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから python コマンドを実行できない。
  4. 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。

インストールの確認

コマンドプロンプトで以下を実行する。

python --version

バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

Python の開発環境 Visual Studio Code のインストールと Python 用の設定

Python の開発環境Visual Studio Code(プログラムを編集するソフトウェア。以下、VS Code)を整える。

[Windows での Visual Studio Code のインストールと Python 用の設定手順を見るには、ここをクリック]

Windows での Visual Studio Code のインストールと Python 用の設定手順

1. VS Code と拡張機能のインストール

以下のコマンドにより,既存の VS Code を削除し,全ユーザー共有の設定で再インストールしたうえで,拡張機能(VS Code に機能を追加するソフトウェア)をまとめて導入する.

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windows キーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして,コマンド全体をコマンドプロンプトにコピー&ペーストする。

インストールコマンド


REM ============================================================
REM Microsoft Visual Studio Code
REM ============================================================
winget uninstall -e --id Microsoft.VisualStudioCode --silent --disable-interactivity --accept-source-agreements
rmdir /s /q C:\ProgramData\vscode-extensions 2>nul
rmdir /s /q "%APPDATA%\Code" 2>nul
rmdir /s /q "%USERPROFILE%\.vscode" 2>nul
rmdir /s /q "%LOCALAPPDATA%\Microsoft\vscode-update" 2>nul

REM VS Code をシステム領域に新規インストール
winget install --scope machine --id Microsoft.VisualStudioCode -e --silent --accept-source-agreements --accept-package-agreements

REM 全ユーザー共有の拡張機能フォルダ
mkdir C:\ProgramData\vscode-extensions 2>nul
icacls "C:\ProgramData\vscode-extensions" /grant "Everyone:(OI)(CI)M" /T

REM スタートメニューのショートカットを --extensions-dir 付きで再作成
rmdir /s /q "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code" 2>nul
del "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk" 2>nul
powershell -NoProfile -Command "$s=New-Object -ComObject WScript.Shell; $lnk=$s.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk'); $lnk.TargetPath='C:\Program Files\Microsoft VS Code\Code.exe'; $lnk.Arguments='--extensions-dir \"C:\ProgramData\vscode-extensions\"'; $lnk.Save()"
REM ショートカットの検証
powershell -NoProfile -Command "$s=New-Object -ComObject WScript.Shell; $lnk=$s.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk'); Write-Host 'TargetPath:' $lnk.TargetPath; Write-Host 'Arguments:' $lnk.Arguments"

REM ファイル / フォルダ右クリックの「Code で開く」を登録
reg add "HKLM\SOFTWARE\Classes\*\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%1\"" /f
reg add "HKLM\SOFTWARE\Classes\Directory\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%1\"" /f
reg add "HKLM\SOFTWARE\Classes\Directory\Background\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%V\"" /f

REM --extensions-dir 付きで起動する code.cmd ラッパを作成
REM (%* を echo で書くと対話的 cmd で失われるため、PowerShell で [char]37+'*' を書き出す)
powershell -NoProfile -Command "$pct=[char]37; $q=[char]34; $c='@echo off'+[char]13+[char]10+$q+'C:\Program Files\Microsoft VS Code\bin\code.cmd'+$q+' --extensions-dir '+$q+'C:\ProgramData\vscode-extensions'+$q+' '+$pct+'*'+[char]13+[char]10; [IO.File]::WriteAllText('C:\ProgramData\vscode-extensions\vscode.cmd',$c,[Text.Encoding]::ASCII)"

REM 拡張機能のインストール
set "CODE=C:\Program Files\Microsoft VS Code\bin\code.cmd"
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --uninstall-extension GitHub.copilot
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --uninstall-extension GitHub.copilot-chat
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.python
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.vscode-pylance
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.debugpy
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension MS-CEINTL.vscode-language-pack-ja
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension saoudrizwan.claude-dev
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension rust-lang.rust-analyzer
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension tamasfe.even-better-toml
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension anthropic.claude-code
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension almenon.arepl
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --list-extensions --show-versions
echo === セットアップ完了 ===

2. Python インタプリタの選択

同一マシンに複数の Python がインストールされている場合,VS Code で使用する Python 本体(インタプリタ:Python プログラムを解釈・実行するソフトウェア)を選択する必要がある.

  1. コマンドパレット(コマンド名で機能を呼び出す VS Code の入力欄)を開く(Ctrl+Shift+P
  2. Python: Select Interpreter と入力する
  3. 表示される一覧から,使用する Python(例:C:\Program Files\Python312\python.exe)を選択する.

Python プログラム実行手順

[Windows での Python プログラム実行手順を見るには、ここをクリック]

Windows での Python 実行手順(Visual Studio Codeを使用)

プログラムファイルの作成と保存

  1. 左サイドバーの「エクスプローラー」アイコン(Ctrl+Shift+E)をクリックする
  2. 「NO FOLDER OPENED」(作業対象フォルダが未選択の状態)と表示される場合は,「Open Folder」をクリックし,プログラムを保存するフォルダを選択する

    続いて「フォルダを信用するか」を確認する画面(フォルダ内のコードを実行してよいか確認する VS Code の仕組み)が表示されるので,チェックして Yes を選択する

  3. フォルダ名の右側に表示される「新しいファイル」アイコンをクリックする
  4. ファイル名(例:aitask.py.ファイル名は何でも良い)を入力し Enter を押す.拡張子は .py(Python ファイルを示す拡張子)とする
  5. 実行したいコードを選択し,Ctrl+C でコピーする.VS Code のエディタ領域に Ctrl+V で貼り付ける
  6. Ctrl+S で保存する

プログラムの実行

  1. エディタ右上の三角形「▷」アイコン(Run Python File:現在開いている Python ファイルを実行するボタン)をクリックする.または,エディタ上で右クリックし「ターミナルで Python ファイルを実行」を選択する
  2. VS Code 下部のターミナル(コマンドの入出力を表示する画面)に,実行結果(print 関数の出力等)が表示される
  3. tkinter(Python 標準の GUI ライブラリ)のファイル選択ダイアログを使うプログラムを実行した場合は,ダイアログが開くので対象画像を選択する
  4. VS Code 下部のターミナルで実行結果を確認する.OpenCV ウィンドウ(OpenCV が画像を表示するために開く専用ウィンドウ)が開いた場合はそちらも確認する.OpenCV ウィンドウは,マウスクリックでウィンドウをアクティブ(操作対象の状態)にしてからキーを押すと終了する

2. 必要なライブラリのインストール

管理者権限コマンドプロンプトを起動する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。

cocos2d は pyglet 1.4.10 以上 2.0 未満に依存する。次のコマンドで cocos2d, pyglet をインストールする。

pip uninstall pyglet -y
pip install -U --no-user cocos2d "pyglet<2.0,>=1.4.10"

3. 実行手順

コードを実行する(メモ帳を用いる場合は a.py のようなファイル名で保存して実行)。

動作確認チェックリスト

確認項目期待される結果
プログラム起動時640×480 のウィンドウが表示される
起動直後の画面文字「o」が画面上に表示される(位置はランダムなので、画面が真っ黒になることがある。その場合は一度終了して再実行する)
時間経過文字「o」が少しずつ動く
ボールが画面端に到達画面の境界(x: 0〜640、y: 0〜480)で反射する
マウスクリック(演習4以降)オブジェクトが増える
矢印キー操作(演習5)Player(「+」)が上下左右に移動する
Player と MyActor の接近(演習5)MyActor の色が赤 (255,10,10,255) に変化する
終了操作右上の「x」をクリックしてウィンドウを閉じる

4. 演習1:ゲームの登場物とレイヤ

手順:次のコードを実行し、画面に文字「o」が1つ表示されることを確認する。確認したら、右上の「x」をクリックして終了する。

ヒント:MyActor クラス(Label クラスのサブクラス)のオブジェクト ball を作成し、レイヤ(Layer00 クラス)に追加して表示する。

考察ポイント:ball の位置はランダムに決まるため、実行のたびに表示位置が変わることを確かめる。位置がランダムなので、画面が真っ黒になることがある。その場合は一度終了して再実行する。

import random
import cocos
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
import sys
import pyglet
setattr(sys.modules['pyglet'], 'mock_level', None)

class MyActor(cocos.text.Label):
    def __init__(self, text, x, y, vx, vy, size, rgba):
        super(MyActor, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.vx = vx
        self.vy = vy
        self.position = cocos.euclid.Vector2(x, y)

class Layer00(Layer):
    is_event_handler = True
    def __init__(self):
        super(Layer00, self).__init__()
        random.seed()
        self.ball = MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255))
        self.add(self.ball)

director.init(width=640, height=480)
director.run( scene.Scene( Layer00() ) )

5. 演習2:位置と速度のシミュレーション

手順:次のコードを実行し、文字「o」が自動で動き、画面の境界で反射することを確認する。確認したら、右上の「x」をクリックして終了する。

ヒント:Layer00 クラスに update メソッドを追加し、self.schedule(self.update) で毎フレーム呼び出すことで、MyActor オブジェクトを自動で動かす。画面の境界では速度を反転させて反射させる。

考察ポイント:速度 vx, vy の大小と、1フレームあたりの移動量の関係を読み取る。ボールの位置をランダムに設定しているので、画面が真っ黒になることがある。その場合は一度終了して再実行する。

import random
import cocos
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
import sys
import pyglet
setattr(sys.modules['pyglet'], 'mock_level', None)

class MyActor(cocos.text.Label):
    def __init__(self, text, x, y, vx, vy, size, rgba):
        super(MyActor, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.vx = vx
        self.vy = vy
        self.position = cocos.euclid.Vector2(x, y)

class Layer00(Layer):
    is_event_handler = True
    def __init__(self):
        super(Layer00, self).__init__()
        random.seed()
        self.ball = MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255))
        self.add(self.ball)
        self.schedule(self.update)
    def update(self, dt):
        self.ball.x += self.ball.vx * dt
        self.ball.y += self.ball.vy * dt
        if self.ball.x >= 640 or self.ball.x < 0:
            self.ball.vx = -self.ball.vx
        if self.ball.y >= 480 or self.ball.y < 0:
            self.ball.vy = -self.ball.vy

director.init(width=640, height=480)
director.run( scene.Scene( Layer00() ) )

6. 演習3:MyActor クラスの複数のオブジェクト

手順:次のコードを実行し、複数の文字「o」が同時に動くことを確認する。確認したら、右上の「x」をクリックして終了する。

ヒント:MyActor オブジェクトを5つに増やし、for ループで子ノードを走査して全オブジェクトを更新する。

考察ポイント:オブジェクトごとに速度が異なるため、動き方がばらつくことを読み取る。

import random
import cocos
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
import sys
import pyglet
setattr(sys.modules['pyglet'], 'mock_level', None)

class MyActor(cocos.text.Label):
    def __init__(self, text, x, y, vx, vy, size, rgba):
        super(MyActor, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.vx = vx
        self.vy = vy
        self.position = cocos.euclid.Vector2(x, y)

class Layer00(Layer):
    is_event_handler = True
    def __init__(self):
        super(Layer00, self).__init__()
        random.seed()
        for i in range(5):
            self.add(MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255)))
        self.schedule(self.update)
    def update(self, dt):
        for _, node in self.children:
            node.x += node.vx * dt
            node.y += node.vy * dt
            if node.x >= 640 or node.x < 0:
                node.vx = -node.vx
            if node.y >= 480 or node.y < 0:
                node.vy = -node.vy

director.init(width=640, height=480)
director.run( scene.Scene( Layer00() ) )

7. 演習4:マウスクリックによるオブジェクトの追加

手順:次のコードを実行し、マウスをクリックするとオブジェクトが増えることを確認する。確認したら、右上の「x」をクリックして終了する。

ヒント:Layer00 クラスに on_mouse_press メソッドを追加する。マウスクリックでオブジェクトが増える。

考察ポイント:クリックのたびに追加されるオブジェクトが、既存のオブジェクトと同じ規則で動くことを読み取る。

import random
import cocos
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
import sys
import pyglet
setattr(sys.modules['pyglet'], 'mock_level', None)

class MyActor(cocos.text.Label):
    def __init__(self, text, x, y, vx, vy, size, rgba):
        super(MyActor, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.vx = vx
        self.vy = vy
        self.position = cocos.euclid.Vector2(x, y)

class Layer00(Layer):
    is_event_handler = True
    def __init__(self):
        super(Layer00, self).__init__()
        random.seed()
        for i in range(5):
            self.add(MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255)))
        self.schedule(self.update)
    def update(self, dt):
        for _, node in self.children:
            node.x += node.vx * dt
            node.y += node.vy * dt
            if node.x >= 640 or node.x < 0:
                node.vx = -node.vx
            if node.y >= 480 or node.y < 0:
                node.vy = -node.vy
    def on_mouse_press(self, x, y, buttons, modifiers):
        self.add( MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255)) )

director.init(width=640, height=480)
director.run( scene.Scene( Layer00() ) )

8. 演習5:Player クラスと当たり判定・重力シミュレーション

手順:次のコードを実行し、矢印キーで Player(「+」)を動かせること、Player が MyActor に近づくと MyActor の色が赤に変わること、MyActor が重力で下向きに加速することを確認する。確認したら、右上の「x」をクリックして終了する。

ヒント:Player クラスを追加し、キーボードの矢印キーで操作する。クラスの判定は「if ( isinstance(node, MyActor) ):」のように行う。当たり判定は「if ( ( ( self.player.x - 4 ) < node.x ) and ( node.x < ( self.player.x + 4 ) ) and ( ( self.player.y - 4 ) < node.y ) and ( node.y < ( self.player.y + 4 ) ) ):」のように行う。重力は GRAVITY 定数を vy に加算して表す。

考察ポイント:重力の加算により、MyActor の縦方向の動きが放物運動になることを読み取る。また、isinstance による判定で Player が更新対象から外れていることを確かめる。

import random
import cocos
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
import sys
import pyglet
setattr(sys.modules['pyglet'], 'mock_level', None)
from pyglet.window import key

GRAVITY = -30

class MyActor(cocos.text.Label):
    def __init__(self, text, x, y, vx, vy, size, rgba):
        super(MyActor, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.vx = vx
        self.vy = vy
        self.position = cocos.euclid.Vector2(x, y)

class Player(cocos.text.Label):
    def __init__(self, text, x, y, size, rgba):
        super(Player, self).__init__(
            text,
            font_name = "Times New Roman",
            font_size = size,
            anchor_x = 'center',
            anchor_y = 'center',
            color = rgba
        )
        self.position = cocos.euclid.Vector2(x, y)

class Layer00(Layer):
    is_event_handler = True
    def __init__(self):
        super(Layer00, self).__init__()
        random.seed()
        for i in range(5):
            self.add(MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255)))
        self.player = Player("+", 320, 80, 40, (120, 200, 255, 255))
        self.add(self.player)
        self.schedule(self.update)
    def update(self, dt):
        for _, node in self.children:
            if ( isinstance(node, MyActor) ):
                node.vy += GRAVITY * dt
                node.x += node.vx * dt
                node.y += node.vy * dt
                if node.x >= 640 or node.x < 0:
                    node.vx = -node.vx
                if node.y >= 480 or node.y < 0:
                    node.vy = -node.vy
                if ( ( ( self.player.x - 4 ) < node.x ) and ( node.x < ( self.player.x + 4 ) ) and ( ( self.player.y - 4 ) < node.y ) and ( node.y < ( self.player.y + 4 ) ) ):
                    node.element.color = (255,10,10,255)
    def on_mouse_press(self, x, y, buttons, modifiers):
        self.add( MyActor("o", random.random() * 640, random.random() * 360 + 80, random.random() * 100 - 50, - random.random() * 50, 32, (255, 255, 255, 255)) )
    def on_key_press(self, symbol, modifiers):
        if symbol == key.RIGHT:
            self.player.x += 8
        elif symbol == key.LEFT:
            self.player.x -= 8
        elif symbol == key.UP:
            self.player.y += 8
        elif symbol == key.DOWN:
            self.player.y -= 8

director.init(width=640, height=480)
director.run( scene.Scene( Layer00() ) )

9. まとめ