132k views
2 votes
In java, I am trying to create a tic-tac-toe game using java GUI. I created the board with 12 buttons. Nine of the buttons are used for the x and o. I have a start button when a user clicks on it. The game asks the user to pick x or o through JOptionPane.showInputDialog and store the user response in a variable. The issue I am having is taking that variable and creating a method that takes the user's choice and has the computer play after the user picks a button to start the game. And coding how a player would win by the getting three in a row by the buttons.

User Yulanggong
by
8.4k points

1 Answer

0 votes

Final answer:

To create a tic-tac-toe game in Java using GUI, you can start by creating the board with buttons. When the user clicks the start button, you can use JOptionPane.showInputDialog to prompt the user to select 'X' or 'O', and store their choice in a variable. To handle the computer's turn, you can create a method that generates a random number between 1 and 9, and assigns 'X' or 'O' to the corresponding button.

Step-by-step explanation:

To create a tic-tac-toe game in Java using GUI, you can start by creating the board with buttons. When the user clicks the start button, you can use JOptionPane.showInputDialog to prompt the user to select 'X' or 'O', and store their choice in a variable. To handle the computer's turn, you can create a method that generates a random number between 1 and 9, and assigns 'X' or 'O' to the corresponding button.

To check for a winning condition, you can create a method that checks each possible winning combination. For example, you can check if buttons 1, 2, and 3 are all marked with 'X' or 'O', and similar checks for other winning combinations. If a win is detected, you can use JOptionPane.showMessageDialog to display a message indicating the winner.

Remember to update the button labels and disable them after each move, so that the players cannot select the same button again. You can use an Array or ArrayList to keep track of the button states. Good luck with your game!

User Myrline
by
7.8k points