Sign in to follow this  
AncientHunter

Tic Tac Toe AI - vb.net

Recommended Posts

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

Share this post


Link to post
Share on other sites
I've no idea about VB but ...

Code like

if(case1() == true) //case1() is executed
case1(); //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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this