r/javahelp • u/Cityman • May 29 '17
No help really needed. Just thought I'd share the Tic Tac Toe game that people on this sub helped me build. I hope you guys enjoy it and if you do see something that code be streamlined better or coded in a better-practice way, I'm all ears.
There are a few things that are coded a little awkwardly. It's due to a bug or two I was experiencing. These are mentioned in the comments. If you see a better way and there are no comments, please do mention that.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class TicTacToe extends JFrame {
private JPanel contentPane;
private JTextField txtPlayerX;
private JTextField txtPlayerO;
private JTextField txtxPoints;
private JTextField txtoPoints;
private String[] gameBoard = new String[9];
private String turn = "X";
private JButton btn1x1;
private JButton btn1x2;
private JButton btn1x3;
private JButton btn2x1;
private JButton btn2x2;
private JButton btn2x3;
private JButton btn3x1;
private JButton btn3x2;
private JButton btn3x3;
private JFrame frame;
private int xScore;
private int oScore;
private String won;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TicTacToe frame = new TicTacToe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* When the Reset button is pressed. Clears the board and creates a new game where the
* loser of the previous game goes first.
*/
public void Reset(){
if(won != null){
if(won.equals("X")){
turn = "O";
}else if(won.equals("O")){
turn = "X";
}
}
Arrays.fill(gameBoard, null);
btn1x1.setText(null);
btn1x2.setText(null);
btn1x3.setText(null);
btn2x1.setText(null);
btn2x2.setText(null);
btn2x3.setText(null);
btn3x1.setText(null);
btn3x2.setText(null);
btn3x3.setText(null);
}
/**
* Determines whose turn it is.
*/
public void nextTurn(){
if (turn.equalsIgnoreCase("X")){
turn = "O";
}else{
turn = "X";
}
}
/**
* Putting an 'X' or 'O' in the clicked box and what happens afterwards.
*
* @param btn. The box on the board that was clicked.
* @param i. The location of gameBoard[] that corresponds to the box clicked.
* @param turn. Whether an X or and O gets placed in the box and array location.
*/
public void markSquare(JButton btn, int i, String turn){
while(gameBoard[i] == null){
if(this.turn.equalsIgnoreCase("X")){
btn.setForeground(Color.RED);
}else{
btn.setForeground(Color.BLUE);
}
gameBoard[i] = this.turn;
btn.setText(gameBoard[i]);
nextTurn();
winGame();
}
}
/**
* Giving the winner of the round a point. Turn is set to null to prevent more letters
* being added after a winner is declared. The String won is set due to an error
* that was causing the program to automatically click the winning box at the start of
* the next round for the losing side.
*
* i.e. if box 2x3 won the game for 'X', the moment after the game reset, the program
* would automatically select box 2x3 for 'O' and that would count as O's turn.
*
* @param winner. The player that won the round.
*/
public void addPoint(String winner){
if(winner.equalsIgnoreCase("X")){
xScore++;
txtxPoints.setText(String.valueOf(xScore));
won = "X";
}else if(winner.equalsIgnoreCase("O")){
oScore++;
txtoPoints.setText(String.valueOf(oScore));
won = "O";
}
turn = null;
}
/**
* How the game can be won.
*/
public void winGame(){
if(gameBoard[0] == gameBoard[1] && gameBoard[1] == gameBoard[2] && gameBoard[0] != null){
JOptionPane.showMessageDialog(frame, gameBoard[0] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[0]);
}
if(gameBoard[3] == gameBoard[4] && gameBoard[4] == gameBoard[5] && gameBoard[3] != null){
JOptionPane.showMessageDialog(frame, gameBoard[3] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[3]);
}
if(gameBoard[6] == gameBoard[7] && gameBoard[7] == gameBoard[8] && gameBoard[6] != null){
JOptionPane.showMessageDialog(frame, gameBoard[6] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[6]);
}
if(gameBoard[0] == gameBoard[3] && gameBoard[3] == gameBoard[6] && gameBoard[0] != null){
JOptionPane.showMessageDialog(frame, gameBoard[0] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[0]);
}
if(gameBoard[1] == gameBoard[4] && gameBoard[4] == gameBoard[7] && gameBoard[1] != null){
JOptionPane.showMessageDialog(frame, gameBoard[1] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[1]);
}
if(gameBoard[2] == gameBoard[5] && gameBoard[5] == gameBoard[8] && gameBoard[2] != null){
JOptionPane.showMessageDialog(frame, gameBoard[2] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[2]);
}
if(gameBoard[0] == gameBoard[4] && gameBoard[4] == gameBoard[8] && gameBoard[0] != null){
JOptionPane.showMessageDialog(frame, gameBoard[0] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[0]);
}
if(gameBoard[2] == gameBoard[4] && gameBoard[4] == gameBoard[6] && gameBoard[2] != null){
JOptionPane.showMessageDialog(frame, gameBoard[2] + " wins", "Tic Tac Toe",
JOptionPane.INFORMATION_MESSAGE);
addPoint(gameBoard[2]);
}
}
/**
* Create the frame.
*/
public TicTacToe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1200, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 2));
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 5, 2, 2));
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
btn1x1 = new JButton("");
btn1x1.setFont(new Font("Tahoma", Font.BOLD, 92));
btn1x1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn1x1, 0, turn);
}
});
panel_1.add(btn1x1, BorderLayout.CENTER);
JPanel panel_2 = new JPanel();
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_2);
panel_2.setLayout(new BorderLayout(0, 0));
btn1x2 = new JButton("");
btn1x2.setFont(new Font("Tahoma", Font.BOLD, 92));
btn1x2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn1x2, 1, turn);
}
});
panel_2.add(btn1x2, BorderLayout.CENTER);
JPanel panel_3 = new JPanel();
panel_3.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
btn1x3 = new JButton("");
btn1x3.setFont(new Font("Tahoma", Font.BOLD, 92));
btn1x3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn1x3, 2, turn);
}
});
panel_3.add(btn1x3, BorderLayout.CENTER);
JPanel panel_4 = new JPanel();
panel_4.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
txtPlayerX = new JTextField();
txtPlayerX.setHorizontalAlignment(SwingConstants.CENTER);
txtPlayerX.setText("Player X:");
txtPlayerX.setFont(new Font("Tahoma", Font.BOLD, 45));
panel_4.add(txtPlayerX, BorderLayout.CENTER);
txtPlayerX.setColumns(10);
JPanel panel_7 = new JPanel();
panel_7.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_7);
panel_7.setLayout(new BorderLayout(0, 0));
txtxPoints = new JTextField();
txtxPoints.setText("0");
txtxPoints.setHorizontalAlignment(SwingConstants.CENTER);
txtxPoints.setFont(new Font("Tahoma", Font.BOLD, 50));
panel_7.add(txtxPoints, BorderLayout.CENTER);
txtxPoints.setColumns(10);
JPanel panel_5 = new JPanel();
panel_5.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
btn2x1 = new JButton("");
btn2x1.setFont(new Font("Tahoma", Font.BOLD, 92));
btn2x1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn2x1, 3, turn);
}
});
panel_5.add(btn2x1, BorderLayout.CENTER);
JPanel panel_8 = new JPanel();
panel_8.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_8);
panel_8.setLayout(new BorderLayout(0, 0));
btn2x2 = new JButton("");
btn2x2.setFont(new Font("Tahoma", Font.BOLD, 92));
btn2x2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn2x2, 4, turn);
}
});
panel_8.add(btn2x2, BorderLayout.CENTER);
JPanel panel_9 = new JPanel();
panel_9.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_9);
panel_9.setLayout(new BorderLayout(0, 0));
btn2x3 = new JButton("");
btn2x3.setFont(new Font("Tahoma", Font.BOLD, 92));
btn2x3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn2x3, 5, turn);
}
});
panel_9.add(btn2x3, BorderLayout.CENTER);
JPanel panel_6 = new JPanel();
panel_6.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
txtPlayerO = new JTextField();
txtPlayerO.setHorizontalAlignment(SwingConstants.CENTER);
txtPlayerO.setFont(new Font("Tahoma", Font.BOLD, 45));
txtPlayerO.setText("Player O:");
panel_6.add(txtPlayerO, BorderLayout.CENTER);
txtPlayerO.setColumns(10);
JPanel panel_10 = new JPanel();
panel_10.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_10);
panel_10.setLayout(new BorderLayout(0, 0));
txtoPoints = new JTextField();
txtoPoints.setHorizontalAlignment(SwingConstants.CENTER);
txtoPoints.setText("0");
txtoPoints.setFont(new Font("Tahoma", Font.BOLD, 50));
panel_10.add(txtoPoints, BorderLayout.CENTER);
txtoPoints.setColumns(10);
JPanel panel_11 = new JPanel();
panel_11.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_11);
panel_11.setLayout(new BorderLayout(0, 0));
btn3x1 = new JButton("");
btn3x1.setFont(new Font("Tahoma", Font.BOLD, 92));
btn3x1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn3x1, 6, turn);
}
});
panel_11.add(btn3x1, BorderLayout.CENTER);
JPanel panel_12 = new JPanel();
panel_12.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_12);
panel_12.setLayout(new BorderLayout(0, 0));
btn3x2 = new JButton("");
btn3x2.setFont(new Font("Tahoma", Font.BOLD, 92));
btn3x2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn3x2, 7, turn);
}
});
panel_12.add(btn3x2, BorderLayout.CENTER);
JPanel panel_13 = new JPanel();
panel_13.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_13);
panel_13.setLayout(new BorderLayout(0, 0));
btn3x3 = new JButton("");
btn3x3.setFont(new Font("Tahoma", Font.BOLD, 92));
btn3x3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markSquare(btn3x3, 8, turn);
}
});
panel_13.add(btn3x3, BorderLayout.CENTER);
JPanel panel_14 = new JPanel();
panel_14.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_14);
panel_14.setLayout(new BorderLayout(0, 0));
JButton btnReset = new JButton("RESET");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Reset();
}
});
btnReset.setFont(new Font("Tahoma", Font.BOLD, 35));
panel_14.add(btnReset, BorderLayout.CENTER);
JPanel panel_15 = new JPanel();
panel_15.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.add(panel_15);
panel_15.setLayout(new BorderLayout(0, 0));
JButton btnExit = new JButton("EXIT");
btnExit.addActionListener(new ActionListener() {
private JFrame frame;
public void actionPerformed(ActionEvent e) {
frame = new JFrame("Exit");
if(JOptionPane.showConfirmDialog(frame, "Do you want to quit?", "Tic Tac Toe",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION){
System.exit(0);
}
}
});
btnExit.setFont(new Font("Tahoma", Font.BOLD, 35));
panel_15.add(btnExit, BorderLayout.CENTER);
}}
5
u/salty_gamer_cat_69 May 29 '17
https://gist.github.com is a better place to share your code snippets and link them here :)
→ More replies (1)
3
May 30 '17 edited May 30 '17
A few tips
You can create a JButton array to reduce the size of your code. This also allows you to use loops to loop through repetitive tasks, such as setting jbutton text to null. You can almost halve the length of your code just by looping through repetitive tasks.
//This will create 99 buttons and apply font and add an actionlistener to then. JButton[] jb = new JButton[99]; for(int i=0;i<99;i++) { jb[i]=new JButton(); jb[i].addActionListener(this); jb[i].setFont(blah blah); }Ternary operators are useful for simple conditions such as the one used in nextTurn()
turn = turn.equals('X') ? 'O' : 'X';You could use GridLayout to arrange buttons in a simple grid. With GridLayout(5,3), you can simply add buttons/panels to the frame, and it should arrange it automatically.
You can use a single actionperformed for every button
void test() { JButton j1 = new JButton(); JButton j2 = new JButton(); j1.addActionListener(this); j2.addActionListener(this); } void actionPerformed(ActionEvent e) { JButton tmp = (JButton)e; //cast actionevent to jbutton markSquare(tmp, index,turn); }
A few core changes that might simplify your code, but requires you to rewrite large portions of the program.
Since there are only 2 players, you can represent the current player by using a boolean value. This simplifies player switching and makes the code easier to read. Only use 'X' and 'O' values, when you are settings the text of a button.
boolean player = false; //false = player 1(X), true = player 2(O), player 1 by default player=!player //change current player jbutton1.setText( player? "X" : "O" ); //set text to X if current player is 1, else set text to OThe method to check the win state is brute force, but works. Every problem can be solved more efficiently. Keep looking for better solutions :)
7
u/Synapse_1 May 29 '17
Just skimming through the code tells me that there is a lot of code repetition going on. Most of it would be solved with a simple method, like for example "getPanel(...)". But I think it's really great that you share something complete, something that you made yourself. I look forward to your next program! :)