问题描述
我想提出一个井字棋游戏。我需要检查,如果一个球员点击他们已经点击了一个正方形。
I am making a Tic-Tac-Toe game. I need to check if a player is clicking on a square they have already clicked.
问题是显示在第一个错误单击本身。
我更新的代码是:
Problem is error is shown in the first click itself.My update code is:
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。我的矩阵是用于存储信息的3×3矩阵。如果是0,这意味着它已经被clicked.So在循环我检查店[I,J] == 0
然后设置 showerror
1。
现在在绘制函数我提出这个要求showerror
showerror
is set to 0 whenever left button is clicked. My matrix is a 3x3 matrix for storing information. If it is 0 that means it has been already clicked.So in the loop I check if store[i,j] == 0
then set showerror
to 1.Now in the draw function I made this call for showerror
spriteBatch.Begin();
if (showerror == 1)
{
spriteBatch.Draw(invalid, new Rectangle(25, 280, 105, 19), Color.White);
}
spriteBatch.End();
但问题是每当我在空方点击它变成十字但误差会shown.Please帮助我
Problem is whenever i click on empty square it turns into cross but error gets shown.Please help me out
推荐答案
如何解决:
添加一个新的全局变量来存储来自前一帧的鼠标状态:
Add a new global variable to store the mouse state from the previous frame:
MouseState oldMouseState;
目前您的更新方法的开始(或结束),添加此,
At the very beginning (or end) of your update method, add this,
oldMouseState = mouse;
和替换
if (mouse.LeftButton == ButtonState.Pressed)
与
if (mouse.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
这样做是什么检查,如果你做了一个点击,其释放的键,然后按下,因为有时你可能持有多帧的关键
What this does is check if you made one click, having the key released then pressing, because sometimes you may hold the key for multiple frames.
通过设置 oldMouseState:
To Recap:
要回顾更新之前, currentMouseState
(或者你用它做后),您garantee的 oldMouseState
将在后面 currentMouseState
。使用这个你可以检查一个按钮下跌前一帧,但现在不是了,并相应地处理输入。一个好主意延长,这是写一些推广方法,如 IsHolding()
, IsClicking()
等。
By setting oldMouseState
before you update the currentMouseState
(Or after you are done with it), you garantee that oldMouseState
will be one frame behind currentMouseState
. Using this you can check if a button was down the previous frame, but not anymore, and handle input accordingly. A good idea to extend this is write some extension methods like IsHolding()
, IsClicking()
, etc.
在简单的代码:
private MouseState oldMouseState, currentMouseState;
protected override void Update(GameTime gameTime)
{
oldMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
//TODO: Update your code here
}
这篇关于XNA - Mouse.Left按钮获取更新多次执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!