Visual Basic: Create an application that simulates a tic tac toe game. The form
ID: 3872187 • Letter: V
Question
Visual Basic: Create an application that simulates a tic tac toe game. The form uses 9 large labels to display the x's and o's. The application should use a two dimensional integer array to simulate the game board in memory. When the user clicks the "New Game" button the application should step throguh the array storing a random number of 0 to 1 in each element. The numer 0 represent the letter o and the number 1 reprsents the letter x. The form should then be updated to display the gameboard. The application should display a message indicating whether "x wins" or "o wins" or "tie".
Note: Since it is a simulation and random x's and o's fill the board there could be two winners or no winner both which would be considered a tie.
This is the code I have so far but I am not sure if the logic is correct. I think the problem lies in the checkForWin function as I am getting false conditons:
Public Class Form1
Dim game(2, 2) As Integer
Const intMAX_ROW As Integer = 2
Const intMAX_COL As Integer = 2
Dim rand As New Random
Dim intRow As Integer
Dim intCol As Integer
'CheckForWin function to check for a valid winner.
Public Function CheckForWin(value As Integer) As Boolean
Dim hasWin As Boolean
'Check each row
For intRow As Integer = 0 To intMAX_ROW
hasWin = True
For intCol As Integer = 0 To intMAX_COL
If game(intRow, intCol) <> value Then
hasWin = False
End If
Next
Next
'Check each column
For intCol As Integer = 0 To intMAX_COL
hasWin = True
For intRow As Integer = 0 To intMAX_ROW
If game(intCol, intRow) <> value Then
hasWin = False
End If
Next
Next
'Check diagonal top right to bottom left
For intRow As Integer = 0 To intMAX_ROW
hasWin = True
If game(intRow, intRow) <> value Then
hasWin = False
End If
Next
'Check diagonal top left to bottom right
For intRow As Integer = 0 To intMAX_ROW
hasWin = True
If game(intRow, intRow) <> value Then
hasWin = False
End If
Next
If hasWin = True Then Return True
Return False
End Function
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close the form
Me.Close()
End Sub
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click
'Randomly fill array with a value of 0 or 1
For intRow As Integer = 0 To 2
For intCol As Integer = 0 To 2
Dim n As Integer = rand.Next(2)
game(intRow, intCol) = n
Next
Next
'Determine if an X or O will be the text by the random value placed in the subscript.
If game(0, 0) = 1 Then
lbl1.Text = "X"
Else
lbl1.Text = "O"
End If
If game(0, 1) = 1 Then
lbl2.Text = "X"
Else
lbl2.Text = "O"
End If
If game(0, 2) = 1 Then
lbl3.Text = "X"
Else
lbl3.Text = "O"
End If
If game(1, 0) = 1 Then
lbl4.Text = "X"
Else
lbl4.Text = "O"
End If
If game(1, 1) = 1 Then
lbl5.Text = "X"
Else
lbl5.Text = "O"
End If
If game(1, 2) = 1 Then
lbl6.Text = "X"
Else
lbl6.Text = "O"
End If
If game(2, 0) = 1 Then
lbl7.Text = "X"
Else
lbl7.Text = "O"
End If
If game(2, 1) = 1 Then
lbl8.Text = "X"
Else
lbl8.Text = "O"
End If
If game(2, 2) = 1 Then
lbl9.Text = "X"
Else
lbl9.Text = "O"
End If
'Call CheckForWin function to determine if game is a tie or a player won.
Dim winnerO As Boolean = CheckForWin(0) 'check for an O's winner by value 0
Dim winnerX As Boolean = CheckForWin(3) 'check for an X's winner by value 3
If winnerO = True And winnerX = True Then
lblMessage.Text = "Tie game!"
ElseIf winnerO = False And winnerX = False Then
lblMessage.Text = "Tie game!"
ElseIf winnerO = True And winnerX = False Then
lblMessage.Text = "O wins!"
ElseIf winnerX = True And winnerO = False Then
lblMessage.Text = "X wins!"
End If
End Sub
End Class
Explanation / Answer
Player 'X', enter your move (row[1-3] column[1-3]): 2 2
| |
-----------
| X |
-----------
| |
Player 'O', enter your move (row[1-3] column[1-3]): 1 1
O | |
-----------
| X |
-----------
| |
Player 'X', enter your move (row[1-3] column[1-3]): 1 3
O | | X
-----------
| X |
-----------
| |
Player 'O', enter your move (row[1-3] column[1-3]): 3 1
O | | X
-----------
| X |
-----------
O | |
Player 'X', enter your move (row[1-3] column[1-3]): 2 2
This move at (2,2) is not valid. Try again...
Player 'X', enter your move (row[1-3] column[1-3]): 2 3
O | | X
-----------
| X | X
-----------
O | |
Player 'O', enter your move (row[1-3] column[1-3]): 2 1
O | | X
-----------
O | X | X
-----------
O | |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class TTTGraphics2P extends JFrame {
public static final int ROWS = 3;
public static final int COLS = 3;
public static final int CELL_SIZE = 100;
public static final int CANVAS_WIDTH = CELL_SIZE * COLS;
public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
public static final int GRID_WIDTH = 8;
public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2;
public static final int CELL_PADDING = CELL_SIZE / 6;
public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2;
public static final int SYMBOL_STROKE_WIDTH = 8;
public enum GameState {
PLAYING, DRAW, CROSS_WON, NOUGHT_WON
}
private GameState currentState;
public enum Seed {
EMPTY, CROSS, NOUGHT
}
private Seed currentPlayer;
private Seed[][] board ;
private DrawCanvas canvas;
private JLabel statusBar;
public TTTGraphics2P() {
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
int rowSelected = mouseY / CELL_SIZE;
int colSelected = mouseX / CELL_SIZE;
if (currentState == GameState.PLAYING) {
if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
&& colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
board[rowSelected][colSelected] = currentPlayer;
updateGame(currentPlayer, rowSelected, colSelected);
currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS;
}
} else {
] initGame();
}
// Refresh the drawing canvas
repaint();
}
});
statusBar = new JLabel(" ");
statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(statusBar, BorderLayout.PAGE_END);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("Tic Tac Toe");
setVisible(true);
board = new Seed[ROWS][COLS];
initGame();
}
/** Initialize the game-board contents and the status */
public void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = Seed.EMPTY;
}
}
currentState = GameState.PLAYING;
currentPlayer = Seed.CROSS;
}
public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
if (hasWon(theSeed, rowSelected, colSelected)) {
currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
} else if (isDraw()) {
currentState = GameState.DRAW;
}
}
public boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == Seed.EMPTY) {
return false;
}
}
}
return true;
}
public boolean hasWon(Seed theSeed, int rowSelected, int colSelected) {
return (board[rowSelected][0] == theSeed
&& board[rowSelected][1] == theSeed
&& board[rowSelected][2] == theSeed
|| board[0][colSelected] == theSeed
&& board[1][colSelected] == theSeed
&& board[2][colSelected] == theSeed
|| rowSelected == colSelected
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed
|| rowSelected + colSelected == 2
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}
class DrawCanvas extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
g.setColor(Color.LIGHT_GRAY);
for (int row = 1; row < ROWS; ++row) {
g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF,
CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH);
}
for (int col = 1; col < COLS; ++col) {
g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0,
GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH);
}
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
int x1 = col * CELL_SIZE + CELL_PADDING;
int y1 = row * CELL_SIZE + CELL_PADDING;
if (board[row][col] == Seed.CROSS) {
g2d.setColor(Color.RED);
int x2 = (col + 1) * CELL_SIZE - CELL_PADDING;
int y2 = (row + 1) * CELL_SIZE - CELL_PADDING;
g2d.drawLine(x1, y1, x2, y2);
g2d.drawLine(x2, y1, x1, y2);
} else if (board[row][col] == Seed.NOUGHT) {
g2d.setColor(Color.BLUE);
g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
}
}
}
if (currentState == GameState.PLAYING) {
statusBar.setForeground(Color.BLACK);
if (currentPlayer == Seed.CROSS) {
statusBar.setText("X's Turn");
} else {
statusBar.setText("O's Turn");
}
} else if (currentState == GameState.DRAW) {
statusBar.setForeground(Color.RED);
statusBar.setText("It's a Draw! Click to play again.");
} else if (currentState == GameState.CROSS_WON) {
statusBar.setForeground(Color.RED);
statusBar.setText("'X' Won! Click to play again.");
} else if (currentState == GameState.NOUGHT_WON) {
statusBar.setForeground(Color.RED);
statusBar.setText("'O' Won! Click to play again.");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TTTGraphics2P();
}
});
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.