我不明白为什么在调用任何移动函数时会出现索引超出范围异常。我将播放器设置在“地图”的右下角,因此它应该能够向北或向西移动,但由于某种原因,我不断收到超出范围异常的索引。
这是主程序:
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;
}