2016-10-04 71 views
0

我對C#比較新,我正在創建一個基本的老派地牢任務遊戲,以幫助我掌握視覺工作室和Windows窗體。c#使用數組作爲地圖

我想使用一個對象數組作爲地圖,然後我可以在兩者之間移動(請讓我知道是否有更好的方法)。 (編輯爲清楚起見)所以,如果我開始在currentroom = maparray [0,1],按左將其更改爲currentroom = maparray [0,0]

這裏是我的陣列碼:

 public object area_init() 
    {Area hall = new Area("Hall", "big hall", "null", false, 1, 2, false); 
     Area room = new Area("Room", "room", "null", false, 1, 2, false); 

     Area[,] maparray = { { hall, room, hall }, 
      { hall,hall,room}, 
      { hall,room,room} 
     }; 
object[,] maparray = new object[3,3]; 

當時我想指的是房間,我目前正在像這樣(我知道這是不正確的):

txtbox_ticker.AppendText("You are in a " + maparray[0,1]); 

,然後更新了「currentroom」變量說我在哪個房間可以。任何人都會告訴我做這件事的最好方法,以及我出錯的地方?

+0

A [字典](https://msdn.microsoft.com/en-us/library/xfhwa508(V = vs.110)的.aspx)將在這裏工作良好。 '字典 myDungeon'。 –

+0

字典不會讓我在2D空間中移動嗎? 我使用數組的原因是行和列排列成基本地圖。 如果您的currentroom是maparray [0,1],則按左鍵會將您移動到maparray [0,0]等等。 – Retro

+0

每個區域都可以有'string left ='剩餘房間名稱''作爲屬性。然後你可以通過調用'myDungeon [currentArea.left]'來獲得新的區域。你真正需要的是更多的連接圖結構。 –

回答

1

區域可以被視爲連接圖中的節點。邊緣由特定節點連接到的節點定義。

你可以像這樣定義你的區域類。

public class Area 
{ 
    public string Name {get;set;} 
    public string Left {get;set;} 
    public string Right {get;set;} 
    public string Up {get;set;} 
    public string Down {get;set;} 

    // if you really need an x-y location put it here. 
} 

然後在後臺有一本字典可以訪問相關信息。字典很棒,因爲你可以使用房間的名字來訪問它的屬性而不是索引。

Dictionary<string,Area> MyDungeon = new Dictionary<string,Area>(); 

// define two areas that are linked. 

Area hall = new Area(); 
hall.Name = "hall" 
hall.Left = "room"; // go left from here to get to the room 

Area room = new Area(); 
room.Name = "room"; 
room.Right = "hall"; // go right to get to the hall 

MyDungeon.Add(hall.Name,hall); 
MyDungeon.Add(room.Name,room); 

讓我們在大廳裏開始關閉用戶。

Area CurrentArea = MyDungeon["hall"]; 

現在說用戶按左箭頭鍵,你需要處理它。你可以做如下的事情。

private void Move_PreviewKeyDown(object sender, KeyEventArgs e) 
{ 
    if(e.Key == Key.Left) 
     { 
      CurrentArea = MyDungeon[CurrentArea.Left]; 
      txtbox_ticker.AppendText("You are now in " + CurrentArea.Name); 
     } 

    else if(e.Key == Key.Right) 
     { 
      CurrentArea = MyDungeon[CurrentArea.Right]; 
      txtbox_ticker.AppendText("You are now in " + CurrentArea.Name); 
     } 

} 
+0

太棒了!非常感謝Felix - 你已經讓一個真正的業餘開發者非常開心。 – Retro

+0

我的榮幸,很高興幫助。 –