首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發 WPF/Silverlight 動畫與遊戲系列教程(七)傳說中的 A* 尋路算法(二)—— 矩陣初始化與障礙物構建

     編輯:關於C語言

引用尋路元件與變量初始化

using QX.Game.PathFinder;

Rectangle rect;
private IPathFinder PathFinder = null;
private byte[,] Matrix = new byte[1024, 1024];
private int GridSize = 20;
private System.Drawing.Point Start = System.Drawing.Point.Empty;
private System.Drawing.Point End = System.Drawing.Point.Empty;

GridSize 解析:定義視窗座標系中多大尺寸對應遊戲座標系一格。例:視窗 800×600,GridSize=20 時,視窗座標 (80,100) 對應遊戲座標 (4,5)。類似 SLG 遊戲格子,GridSize 相當於格子像素邊長。利用除以/乘以 GridSize 實現雙座標系互轉。

視窗建構函數中初始化矩陣

public Window7() {
    InitializeComponent();
    ResetMatrix();
}

private void ResetMatrix() {
    for (int y = 0; y < Matrix.GetUpperBound(1); y++)
        for (int x = 0; x < Matrix.GetUpperBound(0); x++)
            Matrix[x, y] = 1;  // 1=可通行

    // 構建障礙物示例
    for (int i = 0; i < 18; i++) {
        Matrix[i, 12] = 0;  // 0=障礙物
        rect = new Rectangle();
        rect.Fill = new SolidColorBrush(Colors.Red);
        rect.Width = GridSize;
        rect.Height = GridSize;
        Carrier.Children.Add(rect);
        Canvas.SetLeft(rect, i * GridSize);
        Canvas.SetTop(rect, 12 * GridSize);
    }
    // 其他障礙物略...
    Start = new System.Drawing.Point(1, 1);
}

預設全 1(可通行),再按需設 0 為障礙物,並同步在視窗繪製紅色方塊標示。設定起點 (1,1)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved