SLGBaseで戦術級シミュレーションゲームを作ってみる

7.移動範囲と最短経路の計算

最終更新:

slgbase

- view
管理者のみ編集可

7-1.選択操作UIの作成


移動範囲と最短経路のデモンストレーションのため、以下の仕様を追加します。
  • ユニットを選択すると、そのユニットの移動可能範囲を表示する
1.移動可能範囲内のセルをクリックすると、そのセルにユニットが存在しなければ
 そのセルに移動する。
2.移動可能範囲外のセルをクリックすると、そのセルまでの最短経路を表示する。
 移動可能な経路が存在しなければ、その旨を表示する。

移動可能範囲はMapBaseクラスのGetMoveRange()、最短経路はMapBaseクラスのGetRoute()で
取得可能です。

Form1.cs(一部)
public partial class Form1 : Form
    {
 
        // - 略 -
 
        //add 7-1
        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            Position p = _map.View2Cell(pictureBox1, new Position(e.X, e.Y));
            Cell c;
            Unit u;
 
            switch (_moveMode)
            {
                case MoveMode.SelectUnit:
                    u = (Unit)_map.Units.Pick(p);
                    c = (Cell)_map.GetCell(p);
                    if (p!=null && u != null)
                    {
                        //移動範囲計算・設定
                        _map.GetMoveRange(u, c, _map.MoveRangeCells);
 
                        _selectedUnit = u;
                        _moveMode = MoveMode.SelectMoveTarget;
 
                        pictureBox1.Invalidate();
                    }
 
                    break;
                case MoveMode.SelectMoveTarget:
                    c = (Cell)_map.GetCell(p);
                    if (_selectedUnit != null && c != null)
                    {
                        //指定セルが移動範囲内か
                        if (_map.MoveRangeCells.Contains(c) && _map.Units.Pick(c) == null)
                        {
                            //移動範囲内ならユニットを移動
                            _selectedUnit.SetPos(p);
 
                            //移動経路を設定
                            _map.MoveRangeCells.Clear();
                            do
                            {
                                _map.MoveRangeCells.Add(c);
                                c = (Cell)c.routeInfo.prevCell;
                            } while (c != null);
                        }
                        else
                        {
                            //最短経路計算・設定
                            if (!_map.GetRoute(_selectedUnit, _selectedUnit, c, _map.MoveRangeCells))
                                MessageBox.Show("到達可能な経路がありません");
                        }
                        _moveMode = MoveMode.SelectUnit;
                        pictureBox1.Invalidate();
                    }
                    break;
                default: break;
            }
        }
        private MoveMode _moveMode = MoveMode.SelectUnit;   //現在の操作モードを記憶
        private Unit _selectedUnit = null;                  //選択されたユニットを記憶
    }
 
    //add 7-1
    public enum MoveMode
    {
        SelectUnit,
        SelectMoveTarget,
    }
 
 


7-2.実行結果とここまでのプロジェクト


移動範囲表示
#ref error :ご指定のファイルが見つかりません。ファイル名を確認して、再度指定してください。 (移動範囲.jpg)


最短経路表示
#ref error :ご指定のファイルが見つかりません。ファイル名を確認して、再度指定してください。 (最短経路.jpg)


ウィキ募集バナー