我正在使用此代碼以及之后的其他方法,但無法讓我在設計器中使用的表單彈出。唯一成功彈出的是 MessageBox 詢問玩家是否愿意扮演 X為什么我的表單根本不會加載。
namespace mmelichar_Topic6_Activity13
{
public partial class mmelichar_TicTacToe : Form
{
int player = 0;
int position;
int turn = 0;
int playerMove;
int firstMove;
int secondMove;
string[,] location = new string[3, 3] { { "", "", "" }, { "", "", "" }, { "", "", "" } };
public mmelichar_TicTacToe()
{
InitializeComponent();
}
private void mmelichar_TicTacToe_Load(object sender, EventArgs e)
{
//There's only two moves that have to be hard-coded for AI to be able to
//play tic-tac-toe near perfectly, each game /should/ result in a tie or
//a win for the CPU. Other than that, the tryWin and tryBlock methods
//should be able to win the game if there is an availability for that,
//or block the opponent from winning if they cannot win quite yet.
Random rnd = new Random();
DialogResult dialogResult = MessageBox.Show("Do you want to play as X?", "Player Choice", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dialogResult == DialogResult.Yes)
{
player = 1;
}
else if (dialogResult == DialogResult.No)
{
player = 0;
}
//player is O
if (player == 0 && turn == 0)
{
firstTurnCPU();
//player turn
mre.WaitOne();
}
//player is X
if (player == 1 && turn == 0)
{
//player turn 1
mre.WaitOne();
//cpu turn 1
firstTurnCPU();
//player turn 2
mre.WaitOne();
//cpu turn 2
secondTurnCPU();
//player turn 3
mre.WaitOne();
//cpu turn 3
tryWin();
tryBlock();
//player turn 4
mre.WaitOne();
//cpu turn 4
tryWin();
tryBlock();
//player turn
}
}
private readonly ManualResetEvent mre = new ManualResetEvent(false);
private void playerTurn_EventHandler(object sender, EventArgs e)
{
mre.Set();
}
編輯:更新代碼以洗掉 while 回圈并包括我的 ManualResetEvent
uj5u.com熱心網友回復:
你有一個無限回圈:
while (playing)
{
// perform a bunch of logic
// but probably don't do anything async or properly interact with the UI
}
UI 威脅的無限回圈肯定會阻止 UI 繪制到螢屏上。(它也可能比你想要的更多地與 CPU 一起逃跑。)
如果您確實想要一種“游戲回圈”風格的游戲構建,您可以在 Windows 表單中采用一些方法。但現在是在走這條路之前認真考慮游戲設計的好時機。
Windows 表單是高度事件驅動的。它大部分時間處于空閑狀態,并在用戶與 UI 互動時做出回應。(單擊此處,將滑鼠懸停在此處等)如果您的游戲適合該結構(基于回合等),則使用該結構,因為它更原生于 Windows 表單。
您還可以將兩者結合起來,使用 Windows 表單事件來處理用戶互動,但是當程式啟動時,您可以為游戲回圈創建一個單獨的執行緒,以在后臺處理正在進行的事件/邏輯。只要確保回圈不會通過不斷運行來殺死 CPU。在回圈的每次迭代中讓執行緒休眠一會兒是合理的。
uj5u.com熱心網友回復:
我的代碼中有兩個問題:
首先,一個我忘記洗掉的無限回圈,不必要地增加了 CPU 使用率。
其次,使用 ManualResetEvent 而不是僅使用程式內的正常流程來手動控制從播放器到 CPU,反之亦然。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465210.html
