winforms 如何防止玩家穿过迷宫中的墙壁?(C#)

deikduxw  于 2022-11-16  发布在  C#
关注(0)|答案(1)|浏览(130)

enter image description here
红方:播放器图片框;
蓝色方块:终点;
黑色方块:墙;
我在PictureBox中组织了一个迷宫。
玩家是一个有一定大小的物体,其图片框是已知的。我想移动玩家顺利地通过迷宫,墙壁阻止他们通过。
目前有问题的球员通过墙壁,如图所示。

public partial class Form1 : Form
{
    private int XTILES = 25;
    private int YTILES = 25;
    private int TILESIZE = 10;
    private PictureBox[,] mazeTiles;
}

  public void CreateNewMaze()
    {
        mazeTiles = new PictureBox[XTILES, YTILES];
        for (int i = 0; i < XTILES; i++)
        {
            for (int j = 0; j < YTILES; j++)
            {
                mazeTiles[i, j] = new PictureBox();
                int xPosition = (i * TILESIZE) + 25;
                int yPosition = (j * TILESIZE) + 10;
                mazeTiles[i, j].SetBounds(xPosition, yPosition, TILESIZE, TILESIZE);

                this.Controls.Add(mazeTiles[i, j]);
            }
        }
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        bool isRoad = mazeTiles[(PlayerPictureBox.Left - 25) / TILESIZE, (PlayerPictureBox.Top - 10) / TILESIZE].BackColor != Color.Black;
       
        switch (keyData)
        {

            case Keys.Left:

                if (isRoad)
                    PlayerPictureBox.Left -= 10;                                                   
                return true;

            case Keys.Right:
                if (isRoad)
                    PlayerPictureBox.Left += 10;                                                                        
                return true;

            case Keys.Up:
                if (isRoad)
                    PlayerPictureBox.Top -= 10;                                      
                return true;

            case Keys.Down:
                if (isRoad)
                    PlayerPictureBox.Top += 10;  
        
           return true;
         }
           return base.ProcessCmdKey(ref msg, keyData);            
      }
sigwle7e

sigwle7e1#

您需要检查墙是否在预期移动的方向。您现在正在做的是检查当前位置的道路。
请尝试以下操作:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        int dx = 0;
        int dy = 0;
        switch (keyData)
        {
            case Keys.Left: dx = -1; break;
            case Keys.Right: dx = 1; break;
            case Keys.Up: dy = -1; break;
            case Keys.Down: dy = 1; break;
            default: return base.ProcessCmdKey(ref msg, keyData);
        }

        var x = dx + (PlayerPictureBox.Left - 25) / TILESIZE;
        var y = dy + (PlayerPictureBox.Top - 10) / TILESIZE;

        bool isRoad = mazeTiles[x, y].BackColor != Color.Black;
        if (isRoad)
        {
            PlayerPictureBox.Left += dx * TILESIZE;
            PlayerPictureBox.Top += dy * TILESIZE;
        }
        return true;
    }

相关问题