我正在尝试制作一个井字游戏,其中个人电脑随机从数组中选择一个数字,并根据数字选择一个按钮并更改其文本属性。如何让它不选择已有文本属性的按钮?这是我的代码:
Dim AIChoice As Integer
AIChoice = AIChoic.Next(0, AI.Length - 1)
If AI.GetValue(AIChoice) = 1 And Button1.Text = "" Then
Button1.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 2 And Button2.Text = "" Then
Button2.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 3 And Button3.Text = "" Then
Button3.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 4 And Button4.Text = "" Then
Button4.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 5 And Button5.Text = "" Then
Button5.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 6 And Button6.Text = "" Then
Button6.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 7 And Button7.Text = "" Then
Button7.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 8 And Button8.Text = "" Then
Button8.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
ElseIf AI.GetValue(AIChoice) = 9 And Button9.Text = "" Then
Button9.Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)
我之前还有一个数字1-9的数组。
答案 0 :(得分:0)
这应该与您发布的代码完全相同,只是它会继续选择一个随机数,直到找到一个空字符串为Text
的按钮。请注意,最好将按钮创建为数组,而不是创建一个额外的数组来引用它们,但这是最简单的修复,我认为你不会遇到任何其他方式会避免的问题。 / p>
Dim AllButtons() As Button = {Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9}
Dim AIChoice As Integer
Do
AIChoice = AIChoic.Next(0, AI.Length - 1)
Loop Until AllButtons(AI.GetValue(AIChoice) - 1).Text = ""
AllButtons(AI.GetValue(AIChoice) - 1).Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)