在excel VBA上简单的Tic Tac Toe

我试图做一个非常简单的井字游戏,我有一个class,而不是X和O你的颜色单元格内部蓝色(用户)和红色(macros),没有人工智能。

但是每当我想到它就会陷入无限循环

Sub Tic() Dim r1 As Integer Dim r2 As Integer Do r1 = Int(Rnd * 3) + 1 r2 = Int(Rnd * 3) + 1 If Cells(r1, r2).Interior.Color = xlNone Then 'with colorindex instead of color it fills before crashing Cells(r1, r2).Interior.Color = vbRed End If Loop While Cells(r1, r2).Interior.Color = vbBlue Or Cells(r1, r2).Interior.Color <> vbRed 'tried removing the first condition but the result is the same, same with changing the second to equal End Sub 

现在我只允许使用我使用的function,所以我不能改变太多

所以我想它应该做的是检查,如果细胞没有填充任何颜色,那么它应该为红色,如果它的蓝色或红色,那么它应该什么都不做,并寻找另一个未填充的单元格。

不pipe怎么看,我只是不知道哪个部分是错的,所以如果你不能回答我很感激,如果有人指出哪个部分是错误的,所以我可以专注于它

如果循环命中一个蓝色的单元格,那么你的If语句不会执行,并且你的While条件会被满足,这意味着你被困在一个循环中。

也许在进入循环之前设置一个非彩色单元格数量的计数器会更好,然后每次为单元格着色时减less它。 然后当计数器为0时可以退出循环。

所以如果你有9个单元,你可以使用

 Dim r1 As Integer Dim r2 As Integer Dim blankCells As Integer blankCells = 9 Do r1 = Int(Rnd * 3) + 1 r2 = Int(Rnd * 3) + 1 If Cells(r1, r2).Interior.Color = xlNone Then 'with colorindex instead of color it fills before crashing blankCells = blankCells - 1 Cells(r1, r2).Interior.Color = vbRed End If Loop While blankCells > 0