-2

Ok guys...I'm stumped again. I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.

Any pointers? (Code is copied below).

** A few other interesting bugs I feel worth mentioning: 1) Start and Reset don't seem to work correctly 2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.

package tictactoegame;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

class TicTacToeBoard extends JFrame implements ActionListener
{
    JButton[] buttons = new JButton[10];
    boolean player1 = false, player2 = false;
    boolean[] gameSquares = {false, false, false, 
                             false, false, false, 
                             false, false, false}; 
    boolean startPlayer = false;
    int turnCount = 0;

    public TicTacToeBoard()
    {
        JFrame gameWindow = new JFrame();
        gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
        gameWindow.setSize(300,400);
        gameWindow.setVisible(true);

        JPanel gamePanel = new JPanel();
        gamePanel.setSize(300,400);
        GridLayout grid = new GridLayout(4,3);
        gamePanel.setLayout(grid);



        for(int i = 0; i < 9; i++)
        {
            buttons[i] = new JButton("");
            buttons[i].addActionListener(this);

            gamePanel.add(buttons[i]);
        }

        JButton startButton = new JButton("Start");
        startButton.addActionListener(this);
        JButton resetButton = new JButton("Reset");
        resetButton.addActionListener(this);
        JButton helpButton = new JButton("Help");
        helpButton.addActionListener(this);

        gamePanel.add(startButton);
        gamePanel.add(helpButton);        
        gamePanel.add(resetButton);

        gameWindow.add(gamePanel);
        gameWindow.pack();

        while (turnCount < 9)
        {
            gamePlay();
        }
    }

    public void gamePlay()
    {
        while(!startPlayer)
        {
            int random = randomGenerator();

            if (random%2 == 0)
            {
                player1 = true;
                JOptionPane.showMessageDialog(null, "Player is first.");
                startPlayer = true;
            }
            else if (random%2 == 1)
            {
                player2 = true;
                JOptionPane.showMessageDialog(null, "Computer is first.");
                startPlayer = true;
            }
        }

        if (player2)
        {
            int index;

            Random randomGenerator = new Random();

            index = randomGenerator.nextInt(9);

            buttons[index].doClick();

            player2 = false;
            player1 = true;

        }

    }

    public int randomGenerator()
    {
        int randomNum;

        Random randomGenerator = new Random();

        randomNum = randomGenerator.nextInt(100);

        return randomNum;
    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        Object source = e.getSource();


        if(source instanceof JButton)
        {
            JButton button = (JButton) source;

            if (button.getText() == "Start")
            {
                startPlayer = false;
                player1 = false;
                player2 = false;
                gamePlay();
            }
            else if (button.getText() == "Reset")
            {
                for(int i = 0; i < 9; i++)
                {
                    buttons[i].setText("");
                }
                startPlayer = false;
                player1 = false;
                player2 = false;
                gamePlay();
            }
            else if (button.getText() == "Help")
            {
                JOptionPane.showMessageDialog(null, "Help:\n\n" +
                        "How to play-\n" + 
                        "Select an empty square. The square will be filled with"
                       + "with your symbole, either X or O.\n" + 
                       "The game is won when either player gets three X's or"
                 + "O's in a row horizontally,\n vertically, or diagonally.");
            }
            if (button.getText() == "" && player1)
            {
                button.setText("X");
                turnCount += 1;
                player1 = false;
                player2 = true;
            }
            else if (button.getText() == "" && player2)
            {
                button.setText("O");
                turnCount+=1;
                player2 = false;
                player1 = true;
            }
            else if (button.getText() == "X" || button.getText() == "O")
            {
                if(player2 == true)
                {
                    gamePlay();
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Invalid choice. Select" 
                     + " another square.");
                }
            }
        }
    }
}

1 Answers1

-1

Check this TicTacToe Full code using the Applets...:

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    /*
     <applet code="TicTacToe.class" width="300" height="300">
     </applet>
     */
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();

public void init() {
    CURRENT_PLAYER = PLAYER1;
    lbl.setText(CURRENT_PLAYER + " Turn!");
    setLayout(new BorderLayout());
    Panel p = new Panel();
    GridLayout gl = new GridLayout(3, 3);
    p.setLayout(gl);
    setBackground(Color.BLACK);
    setForeground(Color.WHITE);
    setSize(300, 300);
    Font myFont = new Font("TimesRoman", Font.BOLD, 80);
    for (int i = 0; i < 9; i++) {
        btnarray[i] = new Button(null);
        btnarray[i].setActionCommand("" + i);
        btnarray[i].addActionListener(this);
        btnarray[i].setFont(myFont);
        btnarray[i].setBackground(Color.white);
        p.add(btnarray[i]);
    }
    add(BorderLayout.CENTER, p);
    add(BorderLayout.NORTH, lbl);
    add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    int index = Integer.parseInt(e.getActionCommand());
    btnarray[index].disable();
    if (CURRENT_PLAYER == PLAYER1) {
        btnarray[index].setLabel("X");
        CURRENT_PLAYER = PLAYER2;

    } else {
        btnarray[index].setLabel("0");
        CURRENT_PLAYER = PLAYER1;
    }
    lbl.setText(CURRENT_PLAYER + " Turn!");
    check();
}

void check() {
    String[] pattern = new String[8];
    pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
            + btnarray[2].getLabel();
    pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
            + btnarray[5].getLabel();
    pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
            + btnarray[8].getLabel();
    pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
            + btnarray[6].getLabel();
    pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
            + btnarray[7].getLabel();
    pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
            + btnarray[8].getLabel();
    pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
            + btnarray[8].getLabel();
    pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
            + btnarray[6].getLabel();
    int j = 0;

    while (j < 8) {
        char[] array = pattern[j].toCharArray();
        if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
            lbl.setText(PLAYER1 + " Wins!");
        } else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
            lbl.setText(PLAYER2 + " Wins!");
        }
        j++;
    }

}
}
Anurag Goel
  • 468
  • 10
  • 15