2次元配列で作る!迷路ゲームの基礎

2026年11月20日

広告

この記事では、まずC#のコンソールアプリで2次元配列の基本を学びます。Unity 6で盤面を作る応用は、記事後半の第4弾(3×3の盤面)と第5弾(○×ゲーム)にあります。

■ 2次元配列ってどんなもの?

  • 1次元配列 は「横一列のデータの並び」
  • 2次元配列 は「行と列がある表みたいなもの」

例えば、ゲームのマップ(フィールド)はタイル状に区切られているので、2次元配列で表現しやすいです。


■ 迷路ゲームのサンプル

◆ ゲームのイメージ

  • マップは5×5のマス目
  • 0 は「通路」、1 は「壁」とする
  • プレイヤーは P として現在位置を管理
マップのイメージ(数字)
[
 [0, 1, 0, 0, 0],
 [0, 1, 0, 1, 0],
 [0, 0, 0, 1, 0],
 [1, 1, 0, 0, 0],
 [0, 0, 0, 1, 0]
]

◆ C#のサンプルコード

using System;

namespace MazeGame
{
    class Program
    {
        static void Main(string[] args)
        {
            // 2次元配列でマップを作る
            int[,] map = new int[,]
            {
                {0, 1, 0, 0, 0},
                {0, 1, 0, 1, 0},
                {0, 0, 0, 1, 0},
                {1, 1, 0, 0, 0},
                {0, 0, 0, 1, 0}
            };

            // プレイヤーの初期位置
            int playerX = 0;
            int playerY = 0;

            while (true)
            {
                // マップを表示
                for (int y = 0; y < 5; y++)
                {
                    for (int x = 0; x < 5; x++)
                    {
                        if (x == playerX && y == playerY)
                        {
                            Console.Write("P ");
                        }
                        else if (map[y, x] == 1)
                        {
                            Console.Write("■ ");
                        }
                        else
                        {
                            Console.Write("・");
                        }
                    }
                    Console.WriteLine();
                }

                Console.WriteLine("W:上 S:下 A:左 D:右 Q:終了");
                string input = Console.ReadLine();
                input = input.ToUpper(); // 小文字で入力しても動くように大文字にそろえる

                int nextX = playerX;
                int nextY = playerY;

                // 入力に応じて移動先を計算
                if (input == "W") nextY--;
                else if (input == "S") nextY++;
                else if (input == "A") nextX--;
                else if (input == "D") nextX++;
                else if (input == "Q") break;

                // 移動先がマップ内かつ壁でない場合だけ移動
                if (nextX >= 0 && nextX < 5 && nextY >= 0 && nextY < 5 && map[nextY, nextX] == 0)
                {
                    playerX = nextX;
                    playerY = nextY;
                }

                Console.Clear();
            }
        }
    }
}

◆ コードのポイント

  1. マップの表現
    • int[,] map のように [行, 列] で表現する
    • map[y, x] でアクセスするのが基本(y が行、x が列)
  2. プレイヤーの位置
    • playerX と playerY で現在位置を管理
    • 表示のときは「ここがプレイヤーなら P」と分けて描画
  3. 移動の制御
    • 入力で上下左右を移動(ToUpper()で大文字にそろえるので、小文字で入力しても動きます)
    • 壁(1)には進めないようにチェック

◆ まとめ

2次元配列を使うと「マス目」「タイルマップ」「盤面」などが簡単に作れます。

ゲームでは特にマップやステージにピッタリの表現方法です。



【第4弾・Unity 6で応用】3×3の盤面をボタンで操作する

ここまでの迷路例はConsoleで動作するC#プログラムです。Unityの画面で盤面を使う場合は、二次元配列が盤面のデータを持ち、uGUIのButtonが見た目と入力を担当するように分けられます。キャラクター操作がないパズルや○×ゲームの基礎にもなります。

STEP 1:Canvasに3×3のボタンを配置

  • Unity 6でCanvasを作成し、子に空のUIオブジェクト「Board」を用意します。
  • BoardにGrid Layout Groupを追加し、ConstraintをFixed Column Count、Constraint Countを3に設定。Cell SizeとSpacingを見やすい値に調整します。
  • Boardの子にButton – TextMeshProを9個作り、Hierarchy上で左上から右下の順に並べます。各Buttonには子のTMPテキストが必要です。

STEP 2:Board3x3.cs

using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Board3x3 : MonoBehaviour
{
    [SerializeField] private Button[] cells = new Button[9];

    // 0 = 空欄、1 = 印あり。配列は [行, 列] で扱う
    private readonly int[,] board = new int[3, 3];

    private void Start()
    {
        if (cells.Length != 9)
        {
            Debug.LogError("Cellsには9個のButtonを設定してください。");
            return;
        }

        for (int i = 0; i < cells.Length; i++)
        {
            if (cells[i] == null)
            {
                Debug.LogError($"Cellsの{i}番目が未設定です。");
                return;
            }
        }

        for (int i = 0; i < cells.Length; i++)
        {
            int index = i; // ラムダ式に渡す番号を保持
            cells[i].onClick.AddListener(() => ToggleCell(index));
            RefreshCell(i);
        }
    }

    private void ToggleCell(int index)
    {
        int row = index / 3;
        int col = index % 3;
        board[row, col] = board[row, col] == 0 ? 1 : 0;
        RefreshCell(index);
    }

    private void RefreshCell(int index)
    {
        int row = index / 3;
        int col = index % 3;
        TMP_Text label = cells[index].GetComponentInChildren<TMP_Text>();
        if (label != null)
            label.text = board[row, col] == 1 ? "●" : "";
    }
}

board[row, col]が盤面の状態で、index / 3は行番号、index % 3は列番号です。例えば左上は[0,0]、中央は[1,1]、右下は[2,2]になります。Grid Layout Groupはボタンの配置担当で、int[,]はゲームの状態担当です。UnityのGridコンポーネントやTilemapとは用途が異なります。

STEP 3:スクリプトを登録して動作を確認する

  • 空のGameObject「BoardController」を作成して Board3x3 を追加し、InspectorのCellsの9枠へボタンを左上から順に登録します。ボタンのOn Click()への手動登録は不要です。
  • Play Modeで中央のマスを押すと「●」が表示され、もう一度押すと消える。
  • 左上、中央、右下のマスが、それぞれ配列の[0,0]、[1,1]、[2,2]に対応していることを確かめる。
  • Cellsが9個か、各ボタンにTMPテキストがあるか、Hierarchy(シーン)にEventSystemがあるかを確認する。

応用として、空欄・○・×の3種類にして交互に置けばターン制ゲームへ発展できます。まずは「配列の値を変える処理」と「画面を更新する処理」が別になっていることを説明できるようにしましょう。

シリーズ総合案内に戻る。


【第5弾・Unity 6で応用】○×ゲームで手番交代と勝敗判定を学ぶ

前の3×3盤面を発展させ、2人が交互に「○」と「×」を置くゲームにします。置ける条件の確認 → 配列の更新 → 勝敗・引き分け判定 → 次の手番へという処理順がポイントです。手番があるカードゲームやボードゲームにも応用できます。

STEP 1:シーンの準備

  • 前の演習で作成したCanvasと9個のButtonをそのまま使います。前の Board3x3 コンポーネントは無効化または削除してください。両方を同時に付けると、同じボタンに複数のクリック処理が登録されます。
  • Canvasに手番・結果表示用のTextMeshProテキスト(StatusText)と、やり直し用のButton(ResetButton)を追加します。
  • StatusTextには「○ の番」「引き分け」などの日本語を表示します。文字が□で表示されるときは、TextMeshProで日本語を表示する方法の手順で日本語フォントを設定してください。

STEP 2:TicTacToeController.cs

using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class TicTacToeController : MonoBehaviour
{
    [SerializeField] private Button[] cells = new Button[9];
    [SerializeField] private TMP_Text statusText;
    [SerializeField] private Button resetButton;

    private readonly int[,] board = new int[3, 3];
    private int currentPlayer = 1; // 1 = ○、2 = ×
    private bool finished;

    private void Start()
    {
        if (cells.Length != 9 || statusText == null || resetButton == null)
        {
            Debug.LogError("Cells(9個)、Status Text、Reset Buttonを設定してください。");
            enabled = false;
            return;
        }

        for (int i = 0; i < cells.Length; i++)
        {
            if (cells[i] == null || cells[i].GetComponentInChildren<TMP_Text>() == null)
            {
                Debug.LogError($"Cells[{i}]のButtonまたはTMPテキストが未設定です。");
                enabled = false;
                return;
            }
        }

        for (int i = 0; i < cells.Length; i++)
        {
            int index = i;
            cells[i].onClick.AddListener(() => PlaceMark(index));
        }
        resetButton.onClick.AddListener(RestartGame);
        RestartGame();
    }

    private void PlaceMark(int index)
    {
        if (finished) return;

        int row = index / 3;
        int col = index % 3;
        if (board[row, col] != 0) return; // 置いた場所には置けない

        board[row, col] = currentPlayer;
        RefreshBoard();

        if (HasWon(currentPlayer))
        {
            finished = true;
            statusText.text = $"{Mark(currentPlayer)} の勝ち!";
        }
        else if (IsFull())
        {
            finished = true;
            statusText.text = "引き分け";
        }
        else
        {
            currentPlayer = currentPlayer == 1 ? 2 : 1;
            statusText.text = $"{Mark(currentPlayer)} の番";
        }

        if (finished) RefreshBoard(); // 終了後はすべて押せなくする
    }

    private bool HasWon(int player)
    {
        for (int i = 0; i < 3; i++)
        {
            if (board[i, 0] == player && board[i, 1] == player && board[i, 2] == player)
                return true; // 行
            if (board[0, i] == player && board[1, i] == player && board[2, i] == player)
                return true; // 列
        }

        return (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player)
            || (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player);
    }

    private bool IsFull()
    {
        for (int row = 0; row < 3; row++)
            for (int col = 0; col < 3; col++)
                if (board[row, col] == 0) return false;
        return true;
    }

    private void RefreshBoard()
    {
        for (int index = 0; index < 9; index++)
        {
            int row = index / 3;
            int col = index % 3;
            cells[index].GetComponentInChildren<TMP_Text>().text = Mark(board[row, col]);
            cells[index].interactable = !finished && board[row, col] == 0;
        }
    }

    private string Mark(int value)
    {
        return value == 1 ? "○" : value == 2 ? "×" : "";
    }

    public void RestartGame()
    {
        for (int row = 0; row < 3; row++)
            for (int col = 0; col < 3; col++)
                board[row, col] = 0;

        currentPlayer = 1;
        finished = false;
        statusText.text = "○ の番";
        RefreshBoard();
    }
}

STEP 3:スクリプトを登録して手番と判定を確認

  • 空のGameObjectを作成して TicTacToeController を追加し、InspectorでCellsの9要素にボタンを左上から右下へ登録し、Status TextとReset Buttonを割り当てます。各ButtonのOn Click()への手動登録は不要です。
  • ○で1マス置いたら「× の番」になり、使用済みのマスをもう一度押せない。
  • 先手が左上・上中央・右上をそろえると「○ の勝ち!」になり、以後の入力を受け付けない。
  • 縦3マスと斜め3マスの勝利も確認する。
  • どちらも3マスそろえず9マス埋まると「引き分け」になる。
  • ResetButtonで全マスが空に戻り、再び○から開始する。

考え方:board[row, col]は「空欄=0、○=1、×=2」というデータです。currentPlayerは現在の手番、finishedはゲーム終了フラグです。行・列・斜めの8通りを判定すれば勝者が決まり、どちらも勝っておらず空欄がなくなったときだけ引き分けです。

発展として、勝敗判定を別クラスへ分離する、先手を選択できるようにする、第2弾のenumによる状態管理を使って「対局中」「結果表示」を明示する、といった改良に挑戦できます。C#のターン制バトル教材では異なるゲームで手番制の考え方を学べます。また、Unity×AIによる三目並べの制作フローも関連資料です。

シリーズ総合案内に戻る。

訪問数 188 回, 今日の訪問数 1回

広告

C#

Posted by hidepon