Search code examples
arraysvb.netmultidimensional-arraytic-tac-toe

Using 2D Array for Tic Tac Toe in Visual Basic


I have to make a tic tac toe game for my Visual Basic class that uses an array to keep track of the state of the game, but I have no idea how to set up this array. The program is supposed to have 2 views (a GUI which I have already done, and a text view using the console which I have no idea how to do), has two controllers (the user can click the button where they want to play, or they can use the keys 1-9 on the keyboard to choose their position), and is to be played between a human and the computer.

It's not much, but here's what I have so far:

  Module Module1
Const intMAX_ROWS As Integer = 2
Const intMAX_COL As Integer = 2
Public gameArray(intMAX_ROWS, intMAX_COL) As String

Button1.Text = gameArray(0,0) 
Button2.Text = gameArray(0,1)
Button3.Text = gameArray(0,2)
Button4.Text = gameArray(1,0)
Button5.Text = gameArray(1,1)
Button6.Text = gameArray(1,2)
Button7.Text = gameArray(2,0)
Button8.Text = gameArray(2,1)
Button9.Text = gameArray(2,2)

End Module

I am getting an error on all of the Button.Text lines saying

Declaration expected

Any ideas on how to fix that?

Any help or suggestions would be greatly appreciated.


Solution

  • For the program to compile the statements where you assign values to buttons need to be inside a function:

    Sub SetButtons()
        Button1.Text = gameArray(0, 0)
        Button2.Text = gameArray(0, 1)
        Button3.Text = gameArray(0, 2)
        Button4.Text = gameArray(1, 0)
        Button5.Text = gameArray(1, 1)
        Button6.Text = gameArray(1, 2)
        Button7.Text = gameArray(2, 0)
        Button8.Text = gameArray(2, 1)
        Button9.Text = gameArray(2, 2)
    End Sub
    

    As you need 2 views, a GUI and a text view, I'd recommend ending up with 3 projects:

    • a TicTacToe library for the game logic (to be shared)
    • a WinForms or WPF application for the GUI view (that references the library)
    • a Console application for the text view (that references the library)

    Here's an example of drawing a board in a console application:

    Dim board(3, 3) As Char
    ' Set a O in the middle
    board(1, 1) = "O"
    ' Set an X at the bottom right
    board(2, 2) = "X"
    ' Show board
    Console.WriteLine(board(0, 0) + "|" + board(1, 0) + "|" + board(2, 0))
    Console.WriteLine("-----")
    Console.WriteLine(board(0, 1) + "|" + board(1, 1) + "|" + board(2, 1))
    Console.WriteLine("-----")
    Console.WriteLine(board(0, 2) + "|" + board(1, 2) + "|" + board(2, 2))
    

    which gives:

     | |
    -----
     |O|
    -----
     | |X
    

    For a little inspiration on the GUI side, here's a short Silverlight sample (written in F#): Tic-Tac-Toe