gpt4 book ai didi

c# - 等到点击事件被触发 C#

转载 作者:可可西里 更新时间:2023-11-01 08:34:13 29 4
gpt4 key购买 nike

我正在开发一个纸牌游戏,但我需要一个函数来停止程序,直到玩家没有点击他的纸牌的 PictureBox 来丢弃它。我的游戏算法是这样的:

int nextDrawer = 0; // the players which will discard a card are determinated in counterclockwise starting from the human player
for (int i = 0; i < players; i++) // untill all the players hasn't drawed a card
{
if (i == 0) .... // the human player has to click on a picture box to discard a card
else .... // an AI player will discard a card which is selected randomly from the 3 cards which AI has got in its hand
}

问题是当一个曼斯结束时,第一个弃牌的人可能会改变。如果玩家用 0(人类玩家)、1(第一个 AI 玩家)、2(第二个 AI 玩家)和 3(第三个 AI 玩家)进行编号,则在第一局中,第一个弃牌的是人类玩家,但在第二个第一个弃牌的人可能是 2 个 AI 玩家,人类玩家必须等到他之前的所有 AI 玩家都弃牌(在这种情况下,该回合将是 2-3-0-1)。

如果AI玩家还没有出牌,如何取消点击事件?

更新

我并不总是需要等待所有 AI 玩家都抽了一张牌:如果曼斯的获胜者是数字 2,则该轮将是 2-3-0-1:这意味着玩家必须等待 AI 玩家 2 和 3 抽到,然后玩家必须单击一个 PictureBox,循环将返回到 AI 玩家,然后允许 AI 玩家 1 弃牌。

更新 2

我是这么想的:

int leader = 0; // who is going to discard first
int nextDiscarder = leader; // next player who's going to discard
for (int i = 0; i < nPlayers; i++) // until all the players hasn't discarded
{
if (nextDiscarder == 0) // the human has to discard
{
enablePictureBoxClickEvent;
// now before the loop continue the program has to wait the event click on a picture box
}
else
{
AI[nextDiscarder].discard(); // the ai player will discard
}
if (nextDiscarder == players - 1) // if nextDiscarder has reached the end of the table
nextDiscarder = 0; // return to the begin until all player has discarded a card
else
++nextDiscarder; // continue to discard with the next player
}

在我的事件点击中我会做这样的事情:

private myEventClick(object sender, EventArgs e)
{
.... // do the instructions needed to discard a card
disableMyEventClick;
returnToLoop;
}

但主要问题是我不知道如何用代码编写我的指令returnToLoop

最佳答案

我知道大多数人会争辩说你应该使用事件驱动的方法,但是 async/await 特性可以用来轻松实现这样的事情,而不需要手动实现状态机器。

我已经在 Force loop to wait for an event 中发布了类似的方法和 A Better Way to Implement a WaitForMouseUp() Function? , 所以基本上这是与前者相同的助手,将 Button 替换为 Control:

public static class Utils
{
public static Task WhenClicked(this Control target)
{
var tcs = new TaskCompletionSource<object>();
EventHandler onClick = null;
onClick = (sender, e) =>
{
target.Click -= onClick;
tcs.TrySetResult(null);
};
target.Click += onClick;
return tcs.Task;
}
}

现在您需要做的就是将您的方法标记为async 并使用await:

// ...
if (nextDiscarder == 0) // the human has to discard
{
// now before the loop continue the program has to wait the event click on a picture box
await pictureBox.WhenClicked();
// you get here after the picture box has been clicked
}
// ...

关于c# - 等到点击事件被触发 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514733/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com