JAVA PROGRAMMING: For this homework, you will implement a simple Tic Tac Toe gam
ID: 3692522 • Letter: J
Question
JAVA PROGRAMMING:
For this homework, you will implement a simple Tic Tac Toe game using the Java Swing class.
The GUI will consist of a 3x3 panel of buttons representing the board as well as a status text field at the bottom that displays which player’s turn it is and whether a player has won.
Your game should support play between two players and does not need to implement any sort of artificial opponent.
Your program should contain logic that keeps track of which boxes (buttons) are currently empty or occupied with an X or an O. Once a box is occupied with an X or an O, then neither opp onent should be able to select that box. Once a player wins the game, then the status bar should display the winner.
Recall that a game is won when a player selects three boxes in a row horizontally, vertically, or diagonally. Some games end in a draw, i.e., no player wins.
As far as presentation is concerned, the X’s and O’s should be rendered in a non-default font (i.e., you must specify a font… I used Arial Bold Size 24) and must use interesting (i.e., non-default black text on gray background) colors.
Below are screenshots of a simple game I put together:
Tic Tac Toe Player 1's TurnExplanation / Answer
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
public class TicTacToe
{
public static void createAndShowGUI()
{
JFrame game = new JFrame("Tic Tac Toe");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setSize(300, 300);
// Setup a null layout, we will handle the coordinates for our drawing.
game.setLayout(null);
// Create an instance of our new drawing panel which will draw a red "X"
DrawingPanel
p.setBounds(10,10,50,50);
game.add(p);
game.setVisible(true);
}
public static void main(String [] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
}
}
}
// This class will draw our red X markers for us.
class DrawingPanel extends JPanel {
DrawingPanel () {}
public void paintComponent(Graphic)
super.paintComponent()
g.setColor (Color.RED);
g.drawLine(5, 5, getWidth() - 5, getHeight() - 5);
g.drawLine(getWidth() - 5, 5, 5, getHeight() - 5);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.