2次元配列で作る!迷路ゲームの基礎
■ 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();
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();
}
}
}
}
◆ コードのポイント
- マップの表現
- int[,] map のように [行, 列] で表現する
- map[y, x] でアクセスするのが基本(y が行、x が列)
- プレイヤーの位置
- playerX と playerY で現在位置を管理
- 表示のときは「ここがプレイヤーなら P」と分けて描画
- 移動の制御
- 入力で上下左右を移動
- 壁(1)には進めないようにチェック
◆ まとめ
2次元配列を使うと「マス目」「タイルマップ」「盤面」などが簡単に作れます。
ゲームでは特にマップやステージにピッタリの表現方法です。
訪問数 9 回, 今日の訪問数 1回
ディスカッション
コメント一覧
まだ、コメントがありません