User:Pluke/Noughts

From Wikibooks, open books for an open world
Jump to: navigation, search
Module Module1
 
    Sub main()
        Dim board(3, 3) As Char
 
        board(1, 1) = "-"
        board(1, 2) = "-"
        board(1, 3) = "-"
        board(2, 1) = "-"
        board(2, 2) = "-"
        board(2, 3) = "-"
        board(3, 1) = "-"
        board(3, 2) = "-"
        board(3, 3) = "-"
 
        display(board)
        game(board)
        console.readline()
    End Sub
 
    Sub game(ByVal b(,) As Char)
        Dim togo As Char
        Do
            If togo = "x" Then
                togo = "o"
            Else
                togo = "x"
            End If
 
            move(b, togo)
            display(b)
        Loop While Not (win(b, togo)) And Not (drawn(b))
    End Sub
 
    Sub display(ByVal b(,) As Char)
        For i = 0 To 3
            For j = 0 To 3
                Console.Write(b(i, j))
            Next
 
            Console.WriteLine()
        Next
    End Sub
 
    Function win(ByVal b(,) As Char, ByVal p As Char)
        For h = 1 To 3
            If b(h, 1) = p And b(h, 2) = p And b(h, 3) = p Then 'column check
                Console.WriteLine(p + " WINS!")
                Return True
            ElseIf b(1, h) = p And b(2, h) = p And b(3, h) = p Then 'row check
                Console.WriteLine(p + " WINS!")
                Return True
            ElseIf b(1, 1) = p And b(2, 2) = p And b(3, 3) = p Then 'first diagonal check
                Console.WriteLine(p + " WINS!")
                Return True
            ElseIf b(1, 3) = p And b(2, 2) = p And b(3, 1) = p Then  'second diagonal check
                Console.WriteLine(p + " WINS!")
                Return True
 
            End If
        Next
 
        Return False 
    End Function
 
    Sub move(ByRef b(,) As Char, ByVal p As Char)
        Dim x, y As Integer
        Dim move As String
        Console.WriteLine(p + " - make your move in the format: x,y")
        move = Console.ReadLine()
        x = move.Substring(0, 1)
        y = move.Substring(2, 1)
        If b(x, y) = "-" Then
            b(x, y) = p
            display(b)
        Else
            Console.WriteLine("Invalid move!  Miss a turn")
        End If
    End Sub
    Function drawn(ByVal b(,) As Char)
        Dim c As Integer = 0 ' set a counter to keep track of how many spaces there are
        For i = 0 To 3
            For j = 0 To 3
                If b(i, j) = "-" Then
                    c = c + 1
                End If
            Next
        Next
 
        If c = 9 Then
            Console.WriteLine("Draw, game over!")
            Return True
        Else
            Return False
        End If
    End Function
 
End Module