There seem to be a few things that are a bit weird with that code, but I'm going to focus on what causes the
Hero to
eat the walls.
In your method
static bool CanMove(Navigation c)
, the only constraints applied are checking if you
Hero moves off the sceren, you also need to check if they've hit a wall. Changing it to something like this might do the trick for you;
static bool CanMove(Navigation c, Map map)
{
if (c.Up < 0 || c.Up >= Console.WindowWidth)
return false;
if (c.Down < 0 || c.Down >= Console.WindowHeight)
return false;
if (map.MapArray[c.Up, c.Down] != ' ')
return false;
return true;
}
This also means that you can't have your
Hero starting at
(0, 0) as that is a wall, I've therefore also amended the
LoadGame
to cater for this, below is my rewritten version of your
Program
class;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Map_v1._0
{
class Program
{
public static Navigation Player { get; set; }
static void Main(string[] args)
{
int MapLevels = 5;
Map[] map = new Map[MapLevels];
Map currentmap = new Map();
currentmap.Generate_Run(currentmap, Player);
currentmap.Generator_Display(currentmap, Player);
LoadGame(currentmap);
ConsoleKeyInfo keyInfo;
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Escape)
{
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
MoveHero(0, -1, currentmap);
break;
case ConsoleKey.RightArrow:
MoveHero(1, 0, currentmap);
break;
case ConsoleKey.DownArrow:
MoveHero(0, 1, currentmap);
break;
case ConsoleKey.LeftArrow:
MoveHero(-1, 0, currentmap);
break;
}
}
}
static void MoveHero(int x, int y, Map map)
{
Navigation newHero = new Navigation()
{
Up = Player.Up + x,
Down = Player.Down + y
};
if (CanMove(newHero, map))
{
RemoveHero(map);
Console.SetCursorPosition(newHero.Up, newHero.Down);
Console.Write("i");
Player = newHero;
}
}
static void RemoveHero(Map map)
{
Console.SetCursorPosition(Player.Up, Player.Down);
Console.Write(map.MapArray[Player.Up, Player.Down]);
}
static bool CanMove(Navigation c, Map map)
{
if (c.Up < 0 || c.Up >= Console.WindowWidth)
return false;
if (c.Down < 0 || c.Down >= Console.WindowHeight)
return false;
if (map.MapArray[c.Up, c.Down] == 'E')
return true;
if (map.MapArray[c.Up, c.Down] != ' ')
return false;
return true;
}
static void SetBackgroundColor()
{
Console.Clear();
}
static void LoadGame(Map map)
{
Player = new Navigation()
{
Up = 0,
Down = 0
};
for (int r = 0; r < 10; ++r)
{
for (int c = 0; c < 10; ++c)
{
if (map.MapArray[c, r] == ' ')
MoveHero(c, r, map);
}
}
}
}
}
I know game programming can be a daunting experience, but keep at it as it is very rewarding when you make something that works :)
Hope this helps,
Fredrik