GetNextPosition in maze (2d array)

Viewed 55

I'm trying to implement GetNextPosition in maze (2d array).

Here is sample code with logic I'm trying to implement.

The problem is, I don't know how to return the next position. I know it should be a boolean, or at least that's how I wrote the main function. Maybe my approach is completely wrong and I'm making things harder then they should be.

public class DwarfLeft : DwarfBase
{
    public override ConsoleColor Color => ConsoleColor.Yellow;

    private int _angle;

    public DwarfLeft(Maze m) : base(m.StartX, m.StartY)
    {
        //Entry validation
        _angle = m.StartAngle;
    }

    public override bool GetNextPosition(out int nx, out int ny)
    {
        // "return" new position based on _angle and X,Y
    }

    public override void NextPositionUnreachable()
    {
        // Didn't moved
        OldX = X;
        OldY = Y;

        _angle += 90;
        if (_angle > 360) _angle = _angle - 360;
    }
}

What i'm trying to do here is getting the next position where the dwarf could move on

    class Program
    {
        static void Main(string[] args)
        {
            var src = "D:\\1\\maze.dat";
            var maze = new MazeLoader().LoadMaze(src);

            var dwarfs = new List<DwarfBase>();

            MazePresenter.Render(maze);

            dwarfs.Add(new DwarfLeft(maze));

            while (dwarfs.Count > 0)
            {
                #region movement

                for (var i = 0; i < dwarfs.Count; i++)
                {
                    int nx, ny;
                    if (!dwarfs[i].GetNextPosition(out nx, out ny)) continue;

                    // check for BlockType
                    var bc = maze.GetBlockType(nx, ny);
                    switch (bc)
                    {
                        // if pos. == finish || "space" - go there
                        case eBlockType.Space:
                        case eBlockType.Finish: dwarfs[i].MoveToPosition(nx, ny); continue;
                        default:
                            // if pos. unreachable - rotate x axis and repeat procedure
                            dwarfs[i].NextPositionUnreachable();
                            continue;
                    }
                }

                #endregion
            }
        }
    }
}

The maze is rectangular, made of '#' for wall, 'S' for start, 'F' for finish and ' ' for position where dwarf can move.

Thanks in advance for any help, I really appreciate it and happy rest of Easter :)

1 Answers

You need to examine what's in the cell you're considering moving to to decide if you can move there or have to pick another direction.

And note that it's easier to use an enum North, South, East, West than to use Angle.

And note that unless you're wall-following and have a maze that can be solved by wall-following your dwarf is going to wander hopelessly. You need to apply more intelligence to getting through a maze.

Related