「搶三十」為雙人輪流報數遊戲:從 1 開始,每次可加 1 或 2,先報到 30 者勝。核心必勝策略為牢牢掌控 3 的倍數:
電腦玩家依此邏輯即可實現「先手必勝、後手伺機反制」的智能對弈。
核心邏輯置於顯示當前數字的 Edit1 控件 OnChange 事件中:
procedure TForm1.Edit1Change(Sender: TObject);
begin
if not flag then begin // 獲得控制權,電腦自動報數
temp1 := s + 1;
temp2 := s + 2;
if (temp1 mod 3) = 0 then begin // 對手數字模3為1,電腦加2
s := temp1; j := 1;
end else if (temp2 mod 3) = 0 then begin // 模3為2,電腦加1
s := temp2; j := 2;
end else begin // 隨機報數
Randomize; j := Random(2) + 1; s := s + j;
end;
Button2.Enabled := True; Button3.Enabled := True;
Button2.Caption := IntToStr(s + 1);
Button3.Caption := IntToStr(s + 2);
Edit2.Text := IntToStr(j);
ListBox1.Items.Add('電腦報的個數:' + IntToStr(j));
flag := True; // 交還控制權
Edit1.Text := IntToStr(s);
if s >= 30 then begin // 判斷勝利
Button2.Enabled := False; Button3.Enabled := False;
ShowMessage('嘿嘿,想贏我?動動腦筋再來吧!');
end;
end;
end;
使用 flag 布林變數管理雙方報數權。關鍵細節在於 Edit1.Text 更新會觸發 OnChange 事件重入:
此機制揭示事件驅動程式設計中狀態管理與重入風險的經典案例。