Tic Tac Toe AI - vb.net

Started by
0 comments, last by GreyHound 16 years, 8 months ago
hey in my tic tac toe game my enemy AI isnt working, when player 1 (circles) chooses a square the AI fills all of the squares with not just crosses but circles too. this has confused me. here is the code i have so far:

Private Sub AI_turn()
        'If its the computers turn then ...
        If DetermineWinner() = False Then
            If case1() = True Then
                case1()
            ElseIf case2() = True Then
                case2()
            Else
                case3()
            End If
        End If

        ResultWinner()
    End Sub

    Private Function case1()
        Dim count As Integer

        'If i can move and win: go there
        For count = 1 To 9
            If arrBoard(count) = 0 Then
                arrBoard(count) = 2
                If DetermineWinner() = 2 Then
                    case1 = True
                    DrawBoard()
                    turn += 1
                Else
                    arrBoard(count) = 0
                    case1 = False
                End If
            End If
        Next count
    End Function

    Private Function case2()
        Dim count As Integer

        'If Player 1 can move next turn and win: go there (Block)
        For count = 1 To 9
            If arrBoard(count) = 0 Then
                arrBoard(count) = 1
                If DetermineWinner() = 1 Then
                    case2 = True
                    arrBoard(count) = 2
                    DrawBoard()
                    turn += 1
                Else
                    case2 = False
                End If
            End If
        Next count
    End Function

    Private Sub case3()
        'Else move to a random free square
        If DetermineWinner() = 0 Then
            If arrBoard(Random) = 0 Then
                DrawBoard()
                turn += 1
            End If
        End If
    End Sub
    Private Function Random() As Integer
        Random = 8 * Rnd() + 1
        MsgBox(Random)
    End Function

The wheel is spinning, but the hampster is dead!
Advertisement
I've no idea about VB but ...

Code like
if(case1() == true) //case1() is executedcase1();            //and again


will cause 2 function calls. That means every time have something like if(case123()) the function will already be executed. That's probably the reason why circles and sqares are drawn. (I just cannot read this ugly source code
:D)

and in your for loop where you try to find a square to be used you need to break the loop so it doesn't continue once it found one.

This topic is closed to new replies.

Advertisement