1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python + NumPy でゲームのランダムマップを生成して可視化する

1
Posted at

Python + NumPy でゲームのランダムマップを生成して可視化する

目次

  1. はじめに
  2. NumPyでマップを配列として作る
  3. ランダムな迷路・ダンジョン生成
  4. Matplotlibで可視化
  5. 応用例:簡単なゲームのマップに活用
  6. まとめ

1. はじめに

ゲーム制作では、迷路やダンジョンのようなマップを手軽に生成したい場面がよくあります。
Python の NumPy を使えば、配列演算だけで効率よくマップを作成できます。さらに Matplotlib を使うと可視化も簡単です。
(このままNumPyシリーズとしてつづきそう)


2. NumPyでマップを配列として作る

まずは NumPy を使って、基本的なマップ配列を作ります。
0 を「通路」、1 を「壁」として表現します。

import numpy as np

# マップサイズ
width, height = 20, 15

# ランダムに0と1を生成
map_array = np.random.choice([0, 1], size=(height, width), p=[0.7, 0.3])

print(map_array)
  • p=[0.7, 0.3] は通路:壁の割合です。
  • 出力は 2 次元配列で、迷路の基礎になります。

3. ランダムな迷路・ダンジョン生成

簡単な方法として、「壁で囲まれた通路をランダムに配置」することができます。

def generate_dungeon(width, height):
    dungeon = np.ones((height, width), dtype=int)  # 最初はすべて壁
    
    # 通路をランダムに配置
    for y in range(1, height-1):
        for x in range(1, width-1):
            if np.random.rand() > 0.3:  # 70%の確率で通路
                dungeon[y, x] = 0
    return dungeon

map_array = generate_dungeon(width, height)

さらに高度なアルゴリズム(深さ優先探索で迷路を作るなど)も応用可能です。


4. Matplotlibで可視化

生成したマップを Matplotlib で見てみましょう。

import matplotlib.pyplot as plt

plt.imshow(map_array, cmap='gray_r')  # 0=白(通路), 1=黒(壁)
plt.title("Random Dungeon Map")
plt.axis('off')
plt.show()
  • gray_r は黒を壁、白を通路として表示します。
  • ゲーム画面の簡易プレビューとして便利です。

5. 応用例:簡単なゲームでの活用

  • ターン制ゲームやローグライクでのマップ生成
  • プレイヤーや敵の移動範囲の判定
  • 自動生成ダンジョンのテスト

配列をそのままゲームの内部データとして利用できるので、高速で実用的です。


6. まとめ

  • NumPy 配列を使えば迷路・ダンジョンを簡単に生成可能
  • Matplotlib で可視化するとマップをすぐ確認できる
  • ループを使わず配列演算だけで生成すると高速化できる

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?