7

我正在制作井字游戏。我需要检查玩家是否点击了他们已经点击过的方块。

问题是第一次点击本身显示错误。我的更新代码是:

    MouseState mouse = Mouse.GetState();
    int x, y;
    int go = 0;
    if (mouse.LeftButton == ButtonState.Pressed)
    {
        showerror = 0;
        gamestate = 1;
        x = mouse.X;
        y = mouse.Y;
        int getx = x / squaresize;
        int gety = y / squaresize;
        for (int i = 0; i < 3; i++)
        {
            if (go == 1)
            {
                break;
            }
            for (int j = 0; j < 3; j++)
            {
                if (getx == i && gety == j)
                {
                    if (storex[i, j] == 0)
                    {
                       showerror = 1;
                    }
                    go = 1;
                    if (showerror != 1)
                    {
                        loc = i;
                        loc2 = j;
                        storex[i, j] = 0;
                        break;
                    }
                }
            }
        }
    }

showerror每当单击左键时设置为 0。我的矩阵是用于存储信息的 3x3 矩阵。如果它是 0 意味着它已经被点击了。所以在循环中我检查是否store[i,j] == 0设置showerror为 1。现在在绘图函数中我调用了 showerror

spriteBatch.Begin();
if (showerror == 1)
{
    spriteBatch.Draw(invalid, new Rectangle(25, 280, 105, 19), Color.White);                                        
}
spriteBatch.End();

问题是每当我点击空白方块时,它会变成十字但会显示错误。请帮帮我

4

1 回答 1

11

怎么修:

添加一个新的全局变量来存储前一帧的鼠标状态:

MouseState oldMouseState;

在更新方法的最开始(或结束)处,添加以下内容,

oldMouseState = mouse;

并更换

if (mouse.LeftButton == ButtonState.Pressed)

if (mouse.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)

它的作用是检查您是否单击了一次,然后释放键然后按下,因为有时您可能会按住键多个帧。

回顾一下:

通过oldMouseState在更新之前设置currentMouseState(或者在你完成之后),你保证oldMouseState将落后一帧currentMouseState。使用它,您可以检查按钮是否在前一帧中,但不再是,并相应地处理输入。扩展它的一个好主意是编写一些扩展方法,如IsHolding(),IsClicking()等。

在简单的代码中:

private MouseState oldMouseState, currentMouseState;
protected override void Update(GameTime gameTime)
{
     oldMouseState = currentMouseState;
     currentMouseState = Mouse.GetState();
     //TODO: Update your code here
}
于 2013-03-31T22:05:28.857 回答