[英]Why am I getting an index out of range exception
我不明白為什么在調用任何移動函數時都會出現索引超出范圍的異常。 我將播放器設置在“地圖”的右下角,因此它應該可以向北或向西移動,但是由於某種原因,我一直在獲取索引超出范圍的異常。
這是主程序:
namespace DungeonWalk
{
class Program
{
static void Main(string[] args)
{
int length, width;
Console.WriteLine("What size dungeon do you want to traverse?");
try
{
Console.Write("Length: ");
length = Int32.Parse(Console.ReadLine());
Console.Write("Width: ");
width = Int32.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid parameters.");
return;
}
var map = Tile.CreateMap(length, width);
var player = new Player(map.GetLength(0) - 1, map.GetLength(1) - 1);
while(true)
{
Console.WriteLine("What do you want to move next?");
var move = Console.ReadLine().ToLower();
while (true)
{
switch (move)
{
case "north":
Move.North(player, map[player.YPosition, player.XPosition]);
break;
case "south":
Move.South(player, map[player.YPosition, player.XPosition]);
break;
case "east":
Move.East(player, map[player.YPosition, player.XPosition]);
break;
case "west":
Move.West(player, map[player.YPosition, player.XPosition]);
break;
default:
Console.WriteLine("Not a vaild direction. Use cardinal directions.");
break;
}
}
}
}
}
}
這是要移動的代碼:
namespace DungeonWalk
{
class Move
{
public static void North(Player player, Tile tile)
{
if(tile.NorthWall)
{
Console.WriteLine("There is a wall before you. You cannot proceed any further.");
}
else
{
player.YPosition -= 1;
}
}
public static void South(Player player, Tile tile)
{
if (tile.SouthWall)
{
Console.WriteLine("There is a wall before you. You cannot proceed any further.");
}
else
{
player.YPosition += 1;
}
}
public static void West(Player player, Tile tile)
{
if (tile.WestWall)
{
Console.WriteLine("There is a wall before you. You cannot proceed any further.");
}
else
{
player.XPosition -= 1;
}
}
public static void East(Player player, Tile tile)
{
if (tile.EastWall)
{
Console.WriteLine("There is a wall before you. You cannot proceed any further.");
}
else
{
player.XPosition += 1;
}
}
}
}
最后是CreateMap的代碼
public static Tile[,] CreateMap(int length, int width)
{
var map = new Tile[length, width];
for (int i = 0; i < length; i++)
{
for (int j = 0; j < width; j++)
{
map[i, j] = new Tile(j, i, length, width);
}
}
return map;
}
主程序中的兩個while
循環看起來有些奇怪,我不確定是否是故意的。
當前實現:
while(true)
{
Console.WriteLine("What do you want to move next?");
var move = Console.ReadLine().ToLower();
while (true)
{
switch (move)
{
// Move player...
}
}
}
只要求用戶移動一次,然后內部的while
循環將使玩家永遠沿指定方向移動。 (請注意, break
僅會從switch
語句中中斷,而不會從while
中的內部中斷。)
如果消除了內循環,則可以一次執行一個步驟:
while(true)
{
Console.WriteLine("What do you want to move next?");
var move = Console.ReadLine().ToLower();
switch (move)
{
// Move player...
}
}
除非Tile
訪問器中發生了一些時髦的事情(例如NorthWall
或XPosition
),否則Move
方法中看不到任何可能導致IndexOutOfRangeException
。
map
索引可能會超出范圍,例如以下行:
map[player.YPosition, player.XPosition]
如果沒有正確配置牆壁,則如上所述,內部while
循環將使播放器永遠沿相同方向移動,直到數組索引增加到地圖的邊界之外,從而產生異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.