SlideShare a Scribd company logo
1 of 15
Download to read offline
Need help writing the code for a basic java tic tac toe game
// Tic-Tac-Toe: Complete the FIX-ME's to have a working version of Tic-Tac-Toe.
// Note: the basis of the game is a two-dimensional 'board' array, with 3 rows
// and 3 columns. A value of +1 indicates an 'X' on the board; and a value of
// -1 indicates an 'O'
// Group Member names:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.*;
public class TicTacToe implements ActionListener{
// FIX ME #5: set CPU_PAUSE to true when ready to play
final boolean CPU_PAUSE = true; // does the CPU pause to think?
JButton [][] buttons = new JButton[3][3];
int [][] board = new int[3][3];
JLabel status = new JLabel("Player's turn", JLabel.CENTER);
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
Timer timer = null;
// draw X or O depending on 'x' values
void refresh(int [][] x) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (x[i][j] == 1) {
buttons[i][j].setForeground(Color.blue);
buttons[i][j].setText("X");
} else if (x[i][j] == -1) {
buttons[i][j].setForeground(Color.pink);
buttons[i][j].setText("O");
} else {
buttons[i][j].setText(" ");
}
}
}
}
boolean have_winner(int checkVal) {
boolean winner = false;
// FIX ME #1: if there are three 'checkVal' values in-a-row across,
// then set 'winner' to true
// FIX ME #2: if there are three 'checkVal' values in-a-row vertically,
// then set 'winner' to true
int checkSum = 0;
if (checkSum == 3 * checkVal){
winner = true;
}
// FIX ME #3: if there are three 'checkVal' values in-a-row diagonally,
// then set 'winner' to true
return winner;
}
boolean playerMove(ActionEvent e) {
JButton btn = (JButton) e.getSource();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (btn.equals(buttons[i][j])) {
if (board[i][j] != 0) {
return false;
}
board[i][j] = 1;
refresh(board);
return true;
}
}
}
return false;
}
boolean board_is_full() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) return false;
}
}
return true;
}
ActionListener refreshListener = new ActionListener(){
int delayCount = 0;
public void actionPerformed(ActionEvent event){
delayCount++;
if (delayCount > 5) {
delayCount = 0;
timer.stop();
enableButtons(false);
}
if (delayCount % 2 == 0) {
refresh(board);
} else {
int [][] x = new int[3][3];
refresh(x);
}
}
};
void enableButtons(boolean enable) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setEnabled(enable);
}
}
}
ActionListener computerMove = new ActionListener(){
public void actionPerformed(ActionEvent event){
/* FIX ME #4: The computer moves by placing an 'O' on the board
* (i.e.), assigning a -1 to a valid element of the board array
* The computer can play randomly, by randomly selecting a
* row and column to play in, and repeating until a valid (empty)
* spot on the board is found. Optionally, the computer can
* play strategically, though this is more challenging.
*/
System.out.println("The computer's move...");
// refresh board and set up for player's move
// DO NOT CHANGE THESE STATEMENTS!
refresh(board);
status.setText("Player's Move");
enableButtons(true);
if (have_winner(-1)) {
winning_board(-1);
} else {
status.setText("Player's Move");
}
enableButtons(true);
}
};
ActionListener newGame = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("newGame");
// FIX ME #6: set each value of the 'board' to 0
refresh(board);
enableButtons(true);
status.setText("Player's turn");
status.setForeground(Color.black);
}
};
void winning_board(int val) {
if (val == 1) {
status.setText("PLAYER WINS!");
status.setForeground(Color.blue);
} else if (val == -1) {
status.setText("COMPUTER WINS!");
status.setForeground(Color.pink);
}
timer = new Timer(500, refreshListener);
timer.setRepeats(true);
timer.start();
}
ActionListener onClick = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (timer != null && timer.isRunning()) {
timer.stop();
}
int delay = 0;
if (CPU_PAUSE) delay = 1000;
boolean player = playerMove(e);
if (player) {
if (have_winner(1)) {
winning_board(1);
return;
}
else if (board_is_full()) {
status.setText("IT'S A TIE!");
return;
}
status.setText("Computer is thinking...");
enableButtons(false);
Timer timer = new Timer(delay, computerMove);
timer.setRepeats(false);
timer.start();
} else {
System.out.println("No move ");
}
}
};
TicTacToe(){
labelPanel.setLayout(new GridLayout(2,3));
for (int i = 0; i < 6; i++) {
if (i!=1) {
labelPanel.add(new JLabel());
} else {
status.setText("Player's move...");
labelPanel.add(status);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j] = new JButton(" ");
buttons[i][j].setFont(new Font("Arial", Font.BOLD, 50));
buttons[i][j].addActionListener(onClick);
buttonPanel.add(buttons[i][j]);
}
}
buttonPanel.setLayout(new GridLayout(3,3));
frame.setSize(700,300);
frame.add(labelPanel, BorderLayout.SOUTH);
frame.add(buttonPanel, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates a menubar for a JFrame
JMenuBar menuBar = new JMenuBar();
// Define and add two drop down menu to the menubar
JMenu fileMenu = new JMenu("File");
JMenuItem newGameItem = new JMenuItem("New Game");
newGameItem.addActionListener(newGame);
fileMenu.add(newGameItem);
menuBar.add(fileMenu);
// Add the menubar to the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
refresh(board);
}
public static void main(String[] args) {
new TicTacToe();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Solution
// Tic-Tac-Toe: Complete the FIX-ME's to have a working version of Tic-Tac-Toe.
// Note: the basis of the game is a two-dimensional 'board' array, with 3 rows
// and 3 columns. A value of +1 indicates an 'X' on the board; and a value of
// -1 indicates an 'O'
// Group Member names:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.*;
public class TicTacToe implements ActionListener{
// FIX ME #5: set CPU_PAUSE to true when ready to play
final boolean CPU_PAUSE = true; // does the CPU pause to think?
JButton [][] buttons = new JButton[3][3];
int [][] board = new int[3][3];
JLabel status = new JLabel("Player's turn", JLabel.CENTER);
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
Timer timer = null;
// draw X or O depending on 'x' values
void refresh(int [][] x) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (x[i][j] == 1) {
buttons[i][j].setForeground(Color.blue);
buttons[i][j].setText("X");
} else if (x[i][j] == -1) {
buttons[i][j].setForeground(Color.pink);
buttons[i][j].setText("O");
} else {
buttons[i][j].setText(" ");
}
}
}
}
boolean have_winner(int checkVal) {
boolean winner = false;
// FIX ME #1: if there are three 'checkVal' values in-a-row across,
// then set 'winner' to true
for (int i = 0; i < 3; i++) {
if (board[i][0]==checkVal && board[i][1]==checkVal && board[i][2]==checkVal){
winner=true;
}
}
// FIX ME #2: if there are three 'checkVal' values in-a-row vertically,
// then set 'winner' to true
for (int i = 0; i < 3; i++) {
if (board[0][i]==checkVal && board[1][i]==checkVal && board[2][i]==checkVal){
winner=true;
}
}
// FIX ME #3: if there are three 'checkVal' values in-a-row diagonally,
// then set 'winner' to true
if (board[0][0]==checkVal && board[1][1]==checkVal && board[2][2]==checkVal){
winner=true;
}
if (board[0][2]==checkVal && board[1][1]==checkVal && board[2][0]==checkVal){
winner=true;
}
return winner;
}
boolean playerMove(ActionEvent e) {
JButton btn = (JButton) e.getSource();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (btn.equals(buttons[i][j])) {
if (board[i][j] != 0) {
return false;
}
board[i][j] = 1;
refresh(board);
return true;
}
}
}
return false;
}
boolean board_is_full() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) return false;
}
}
return true;
}
ActionListener refreshListener = new ActionListener(){
int delayCount = 0;
public void actionPerformed(ActionEvent event){
delayCount++;
if (delayCount > 5) {
delayCount = 0;
timer.stop();
enableButtons(false);
}
if (delayCount % 2 == 0) {
refresh(board);
} else {
int [][] x = new int[3][3];
refresh(x);
}
}
};
void enableButtons(boolean enable) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setEnabled(enable);
}
}
}
ActionListener computerMove = new ActionListener(){
public void actionPerformed(ActionEvent event){
/* FIX ME #4: The computer moves by placing an 'O' on the board
* (i.e.), assigning a -1 to a valid element of the board array
* The computer can play randomly, by randomly selecting a
* row and column to play in, and repeating until a valid (empty)
* spot on the board is found. Optionally, the computer can
* play strategically, though this is more challenging.
*/
mainloop:
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
if(!(board[i][j]==1 || board[i][j]==-1)){
board[i][j] = -1;
buttons[i][j].setForeground(Color.pink);
buttons[i][j].setText("O");
break mainloop;
}
}
}
System.out.println("The computer's move...");
// refresh board and set up for player's move
// DO NOT CHANGE THESE STATEMENTS!
refresh(board);
status.setText("Player's Move");
enableButtons(true);
if (have_winner(-1)) {
winning_board(-1);
} else {
status.setText("Player's Move");
}
enableButtons(true);
}
};
ActionListener newGame = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("newGame");
// FIX ME #6: set each value of the 'board' to 0
refresh(board);
enableButtons(true);
status.setText("Player's turn");
status.setForeground(Color.black);
}
};
void winning_board(int val) {
if (val == 1) {
status.setText("PLAYER WINS!");
status.setForeground(Color.blue);
} else if (val == -1) {
status.setText("COMPUTER WINS!");
status.setForeground(Color.pink);
}
timer = new Timer(500, refreshListener);
timer.setRepeats(true);
timer.start();
}
ActionListener onClick = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (timer != null && timer.isRunning()) {
timer.stop();
}
int delay = 0;
if (CPU_PAUSE) delay = 1000;
boolean player = playerMove(e);
if (player) {
if (have_winner(1)) {
winning_board(1);
return;
}
else if (board_is_full()) {
status.setText("IT'S A TIE!");
return;
}
status.setText("Computer is thinking...");
enableButtons(false);
Timer timer = new Timer(delay, computerMove);
timer.setRepeats(false);
timer.start();
} else {
System.out.println("No move ");
}
}
};
TicTacToe(){
labelPanel.setLayout(new GridLayout(2,3));
for (int i = 0; i < 6; i++) {
if (i!=1) {
labelPanel.add(new JLabel());
} else {
status.setText("Player's move...");
labelPanel.add(status);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j] = new JButton(" ");
buttons[i][j].setFont(new Font("Arial", Font.BOLD, 50));
buttons[i][j].addActionListener(onClick);
buttonPanel.add(buttons[i][j]);
}
}
buttonPanel.setLayout(new GridLayout(3,3));
frame.setSize(700,300);
frame.add(labelPanel, BorderLayout.SOUTH);
frame.add(buttonPanel, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates a menubar for a JFrame
JMenuBar menuBar = new JMenuBar();
// Define and add two drop down menu to the menubar
JMenu fileMenu = new JMenu("File");
JMenuItem newGameItem = new JMenuItem("New Game");
newGameItem.addActionListener(newGame);
fileMenu.add(newGameItem);
menuBar.add(fileMenu);
// Add the menubar to the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
refresh(board);
}
public static void main(String[] args) {
new TicTacToe();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

More Related Content

Similar to Java Tic-Tac-Toe Game Code Help

i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino Giuseppe Modarelli
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduinomonksoftwareit
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docxKomlin1
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfinfo430661
 
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfimport tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfpreetajain
 
19012011102_Nayan Oza_Practical-7_AI.pdf
19012011102_Nayan Oza_Practical-7_AI.pdf19012011102_Nayan Oza_Practical-7_AI.pdf
19012011102_Nayan Oza_Practical-7_AI.pdfNayanOza
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfsales98
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfaakarcreations1
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 
import java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfimport java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfannaipowerelectronic
 
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfbadshetoms
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfatulkapoor33
 

Similar to Java Tic-Tac-Toe Game Code Help (17)

i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduino
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfimport tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
 
19012011102_Nayan Oza_Practical-7_AI.pdf
19012011102_Nayan Oza_Practical-7_AI.pdf19012011102_Nayan Oza_Practical-7_AI.pdf
19012011102_Nayan Oza_Practical-7_AI.pdf
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
import java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfimport java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdf
 
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdf
 

More from hainesburchett26321

Write an identity in terms of sines and cosines to simplify it. The .pdf
Write an identity in terms of sines and cosines to simplify it.  The .pdfWrite an identity in terms of sines and cosines to simplify it.  The .pdf
Write an identity in terms of sines and cosines to simplify it. The .pdfhainesburchett26321
 
What is a sampling distribution Describe the similarities between t.pdf
What is a sampling distribution Describe the similarities between t.pdfWhat is a sampling distribution Describe the similarities between t.pdf
What is a sampling distribution Describe the similarities between t.pdfhainesburchett26321
 
What is the easiest to memorize the order of all the Eras and their .pdf
What is the easiest to memorize the order of all the Eras and their .pdfWhat is the easiest to memorize the order of all the Eras and their .pdf
What is the easiest to memorize the order of all the Eras and their .pdfhainesburchett26321
 
What is stock split How is it equivalent to paying a dividendS.pdf
What is stock split How is it equivalent to paying a dividendS.pdfWhat is stock split How is it equivalent to paying a dividendS.pdf
What is stock split How is it equivalent to paying a dividendS.pdfhainesburchett26321
 
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdf
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdfUnderstanding Risk Terms and DefinitionsSolutionWhat is Risk.pdf
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdfhainesburchett26321
 
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdf
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdfThomas Townsend has an embarrassing criminal past. In 1985, he was c.pdf
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdfhainesburchett26321
 
The lymphatic system is composed of all of the following except lymph.pdf
The lymphatic system is composed of all of the following except lymph.pdfThe lymphatic system is composed of all of the following except lymph.pdf
The lymphatic system is composed of all of the following except lymph.pdfhainesburchett26321
 
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdf
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdfSurgeons have sometimes cut the corpus callosum as a treatment for w.pdf
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdfhainesburchett26321
 
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdfhainesburchett26321
 
Recall that E. coli can grow in glucose-salts medium, which contains .pdf
Recall that E. coli can grow in glucose-salts medium, which contains .pdfRecall that E. coli can grow in glucose-salts medium, which contains .pdf
Recall that E. coli can grow in glucose-salts medium, which contains .pdfhainesburchett26321
 
Random samples of 200 men, all retired were classified according to .pdf
Random samples of 200 men, all retired were classified according to .pdfRandom samples of 200 men, all retired were classified according to .pdf
Random samples of 200 men, all retired were classified according to .pdfhainesburchett26321
 
Question Hello, I need some assistance in writing a java pr...Hel.pdf
Question Hello, I need some assistance in writing a java pr...Hel.pdfQuestion Hello, I need some assistance in writing a java pr...Hel.pdf
Question Hello, I need some assistance in writing a java pr...Hel.pdfhainesburchett26321
 
Please help I think the answer is B, but Im not too sure.A. Amni.pdf
Please help I think the answer is B, but Im not too sure.A. Amni.pdfPlease help I think the answer is B, but Im not too sure.A. Amni.pdf
Please help I think the answer is B, but Im not too sure.A. Amni.pdfhainesburchett26321
 
Inventory is recorded at what value on the balance Sheet Inven.pdf
Inventory is recorded at what value on the balance Sheet Inven.pdfInventory is recorded at what value on the balance Sheet Inven.pdf
Inventory is recorded at what value on the balance Sheet Inven.pdfhainesburchett26321
 
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdf
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdfIf you are monitoring a 1 V source on an oscilloscope and the scope m.pdf
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdfhainesburchett26321
 
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdf
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdfIf Emery has $1,700 to invest at 7 per year compounded monthly, how .pdf
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdfhainesburchett26321
 
Identify and discuss features of organizations managers need to know.pdf
Identify and discuss features of organizations managers need to know.pdfIdentify and discuss features of organizations managers need to know.pdf
Identify and discuss features of organizations managers need to know.pdfhainesburchett26321
 
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdf
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdfhe first photosynthetic organisms to oxygenate the Earth’s atmospher.pdf
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdfhainesburchett26321
 
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdf
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdffollowing concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdf
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdfhainesburchett26321
 
Explain how the structure and function are linked together for the f.pdf
Explain how the structure and function are linked together for the f.pdfExplain how the structure and function are linked together for the f.pdf
Explain how the structure and function are linked together for the f.pdfhainesburchett26321
 

More from hainesburchett26321 (20)

Write an identity in terms of sines and cosines to simplify it. The .pdf
Write an identity in terms of sines and cosines to simplify it.  The .pdfWrite an identity in terms of sines and cosines to simplify it.  The .pdf
Write an identity in terms of sines and cosines to simplify it. The .pdf
 
What is a sampling distribution Describe the similarities between t.pdf
What is a sampling distribution Describe the similarities between t.pdfWhat is a sampling distribution Describe the similarities between t.pdf
What is a sampling distribution Describe the similarities between t.pdf
 
What is the easiest to memorize the order of all the Eras and their .pdf
What is the easiest to memorize the order of all the Eras and their .pdfWhat is the easiest to memorize the order of all the Eras and their .pdf
What is the easiest to memorize the order of all the Eras and their .pdf
 
What is stock split How is it equivalent to paying a dividendS.pdf
What is stock split How is it equivalent to paying a dividendS.pdfWhat is stock split How is it equivalent to paying a dividendS.pdf
What is stock split How is it equivalent to paying a dividendS.pdf
 
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdf
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdfUnderstanding Risk Terms and DefinitionsSolutionWhat is Risk.pdf
Understanding Risk Terms and DefinitionsSolutionWhat is Risk.pdf
 
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdf
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdfThomas Townsend has an embarrassing criminal past. In 1985, he was c.pdf
Thomas Townsend has an embarrassing criminal past. In 1985, he was c.pdf
 
The lymphatic system is composed of all of the following except lymph.pdf
The lymphatic system is composed of all of the following except lymph.pdfThe lymphatic system is composed of all of the following except lymph.pdf
The lymphatic system is composed of all of the following except lymph.pdf
 
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdf
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdfSurgeons have sometimes cut the corpus callosum as a treatment for w.pdf
Surgeons have sometimes cut the corpus callosum as a treatment for w.pdf
 
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf
5 of 12 Incorrect Sapling Learning assify these items according to wh.pdf
 
Recall that E. coli can grow in glucose-salts medium, which contains .pdf
Recall that E. coli can grow in glucose-salts medium, which contains .pdfRecall that E. coli can grow in glucose-salts medium, which contains .pdf
Recall that E. coli can grow in glucose-salts medium, which contains .pdf
 
Random samples of 200 men, all retired were classified according to .pdf
Random samples of 200 men, all retired were classified according to .pdfRandom samples of 200 men, all retired were classified according to .pdf
Random samples of 200 men, all retired were classified according to .pdf
 
Question Hello, I need some assistance in writing a java pr...Hel.pdf
Question Hello, I need some assistance in writing a java pr...Hel.pdfQuestion Hello, I need some assistance in writing a java pr...Hel.pdf
Question Hello, I need some assistance in writing a java pr...Hel.pdf
 
Please help I think the answer is B, but Im not too sure.A. Amni.pdf
Please help I think the answer is B, but Im not too sure.A. Amni.pdfPlease help I think the answer is B, but Im not too sure.A. Amni.pdf
Please help I think the answer is B, but Im not too sure.A. Amni.pdf
 
Inventory is recorded at what value on the balance Sheet Inven.pdf
Inventory is recorded at what value on the balance Sheet Inven.pdfInventory is recorded at what value on the balance Sheet Inven.pdf
Inventory is recorded at what value on the balance Sheet Inven.pdf
 
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdf
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdfIf you are monitoring a 1 V source on an oscilloscope and the scope m.pdf
If you are monitoring a 1 V source on an oscilloscope and the scope m.pdf
 
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdf
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdfIf Emery has $1,700 to invest at 7 per year compounded monthly, how .pdf
If Emery has $1,700 to invest at 7 per year compounded monthly, how .pdf
 
Identify and discuss features of organizations managers need to know.pdf
Identify and discuss features of organizations managers need to know.pdfIdentify and discuss features of organizations managers need to know.pdf
Identify and discuss features of organizations managers need to know.pdf
 
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdf
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdfhe first photosynthetic organisms to oxygenate the Earth’s atmospher.pdf
he first photosynthetic organisms to oxygenate the Earth’s atmospher.pdf
 
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdf
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdffollowing concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdf
following concepts from Johnsons book in Ch. 1, Ch. 2 or Ch. 3-- w.pdf
 
Explain how the structure and function are linked together for the f.pdf
Explain how the structure and function are linked together for the f.pdfExplain how the structure and function are linked together for the f.pdf
Explain how the structure and function are linked together for the f.pdf
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

Java Tic-Tac-Toe Game Code Help

  • 1. Need help writing the code for a basic java tic tac toe game // Tic-Tac-Toe: Complete the FIX-ME's to have a working version of Tic-Tac-Toe. // Note: the basis of the game is a two-dimensional 'board' array, with 3 rows // and 3 columns. A value of +1 indicates an 'X' on the board; and a value of // -1 indicates an 'O' // Group Member names: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.*; public class TicTacToe implements ActionListener{ // FIX ME #5: set CPU_PAUSE to true when ready to play final boolean CPU_PAUSE = true; // does the CPU pause to think? JButton [][] buttons = new JButton[3][3]; int [][] board = new int[3][3]; JLabel status = new JLabel("Player's turn", JLabel.CENTER); JFrame frame = new JFrame(); JPanel buttonPanel = new JPanel(); JPanel labelPanel = new JPanel(); Timer timer = null; // draw X or O depending on 'x' values void refresh(int [][] x) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) {
  • 2. if (x[i][j] == 1) { buttons[i][j].setForeground(Color.blue); buttons[i][j].setText("X"); } else if (x[i][j] == -1) { buttons[i][j].setForeground(Color.pink); buttons[i][j].setText("O"); } else { buttons[i][j].setText(" "); } } } } boolean have_winner(int checkVal) { boolean winner = false; // FIX ME #1: if there are three 'checkVal' values in-a-row across, // then set 'winner' to true // FIX ME #2: if there are three 'checkVal' values in-a-row vertically, // then set 'winner' to true int checkSum = 0; if (checkSum == 3 * checkVal){ winner = true; } // FIX ME #3: if there are three 'checkVal' values in-a-row diagonally, // then set 'winner' to true return winner; }
  • 3. boolean playerMove(ActionEvent e) { JButton btn = (JButton) e.getSource(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (btn.equals(buttons[i][j])) { if (board[i][j] != 0) { return false; } board[i][j] = 1; refresh(board); return true; } } } return false; } boolean board_is_full() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == 0) return false; } } return true; } ActionListener refreshListener = new ActionListener(){ int delayCount = 0; public void actionPerformed(ActionEvent event){ delayCount++; if (delayCount > 5) { delayCount = 0; timer.stop(); enableButtons(false); }
  • 4. if (delayCount % 2 == 0) { refresh(board); } else { int [][] x = new int[3][3]; refresh(x); } } }; void enableButtons(boolean enable) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { buttons[i][j].setEnabled(enable); } } } ActionListener computerMove = new ActionListener(){ public void actionPerformed(ActionEvent event){ /* FIX ME #4: The computer moves by placing an 'O' on the board * (i.e.), assigning a -1 to a valid element of the board array * The computer can play randomly, by randomly selecting a * row and column to play in, and repeating until a valid (empty) * spot on the board is found. Optionally, the computer can * play strategically, though this is more challenging. */ System.out.println("The computer's move..."); // refresh board and set up for player's move // DO NOT CHANGE THESE STATEMENTS! refresh(board); status.setText("Player's Move"); enableButtons(true);
  • 5. if (have_winner(-1)) { winning_board(-1); } else { status.setText("Player's Move"); } enableButtons(true); } }; ActionListener newGame = new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("newGame"); // FIX ME #6: set each value of the 'board' to 0 refresh(board); enableButtons(true); status.setText("Player's turn"); status.setForeground(Color.black); } }; void winning_board(int val) { if (val == 1) { status.setText("PLAYER WINS!"); status.setForeground(Color.blue); } else if (val == -1) { status.setText("COMPUTER WINS!"); status.setForeground(Color.pink); } timer = new Timer(500, refreshListener); timer.setRepeats(true); timer.start();
  • 6. } ActionListener onClick = new ActionListener() { public void actionPerformed(ActionEvent e) { if (timer != null && timer.isRunning()) { timer.stop(); } int delay = 0; if (CPU_PAUSE) delay = 1000; boolean player = playerMove(e); if (player) { if (have_winner(1)) { winning_board(1); return; } else if (board_is_full()) { status.setText("IT'S A TIE!"); return; } status.setText("Computer is thinking..."); enableButtons(false); Timer timer = new Timer(delay, computerMove); timer.setRepeats(false); timer.start(); } else { System.out.println("No move "); } } }; TicTacToe(){
  • 7. labelPanel.setLayout(new GridLayout(2,3)); for (int i = 0; i < 6; i++) { if (i!=1) { labelPanel.add(new JLabel()); } else { status.setText("Player's move..."); labelPanel.add(status); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { buttons[i][j] = new JButton(" "); buttons[i][j].setFont(new Font("Arial", Font.BOLD, 50)); buttons[i][j].addActionListener(onClick); buttonPanel.add(buttons[i][j]); } } buttonPanel.setLayout(new GridLayout(3,3)); frame.setSize(700,300); frame.add(labelPanel, BorderLayout.SOUTH); frame.add(buttonPanel, BorderLayout.NORTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Creates a menubar for a JFrame JMenuBar menuBar = new JMenuBar(); // Define and add two drop down menu to the menubar JMenu fileMenu = new JMenu("File"); JMenuItem newGameItem = new JMenuItem("New Game"); newGameItem.addActionListener(newGame);
  • 8. fileMenu.add(newGameItem); menuBar.add(fileMenu); // Add the menubar to the frame frame.setJMenuBar(menuBar); frame.setVisible(true); refresh(board); } public static void main(String[] args) { new TicTacToe(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } } Solution // Tic-Tac-Toe: Complete the FIX-ME's to have a working version of Tic-Tac-Toe. // Note: the basis of the game is a two-dimensional 'board' array, with 3 rows // and 3 columns. A value of +1 indicates an 'X' on the board; and a value of // -1 indicates an 'O' // Group Member names: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem;
  • 9. import javax.swing.*; public class TicTacToe implements ActionListener{ // FIX ME #5: set CPU_PAUSE to true when ready to play final boolean CPU_PAUSE = true; // does the CPU pause to think? JButton [][] buttons = new JButton[3][3]; int [][] board = new int[3][3]; JLabel status = new JLabel("Player's turn", JLabel.CENTER); JFrame frame = new JFrame(); JPanel buttonPanel = new JPanel(); JPanel labelPanel = new JPanel(); Timer timer = null; // draw X or O depending on 'x' values void refresh(int [][] x) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (x[i][j] == 1) { buttons[i][j].setForeground(Color.blue); buttons[i][j].setText("X"); } else if (x[i][j] == -1) { buttons[i][j].setForeground(Color.pink); buttons[i][j].setText("O"); } else { buttons[i][j].setText(" "); } } } } boolean have_winner(int checkVal) { boolean winner = false; // FIX ME #1: if there are three 'checkVal' values in-a-row across, // then set 'winner' to true for (int i = 0; i < 3; i++) { if (board[i][0]==checkVal && board[i][1]==checkVal && board[i][2]==checkVal){ winner=true;
  • 10. } } // FIX ME #2: if there are three 'checkVal' values in-a-row vertically, // then set 'winner' to true for (int i = 0; i < 3; i++) { if (board[0][i]==checkVal && board[1][i]==checkVal && board[2][i]==checkVal){ winner=true; } } // FIX ME #3: if there are three 'checkVal' values in-a-row diagonally, // then set 'winner' to true if (board[0][0]==checkVal && board[1][1]==checkVal && board[2][2]==checkVal){ winner=true; } if (board[0][2]==checkVal && board[1][1]==checkVal && board[2][0]==checkVal){ winner=true; } return winner; } boolean playerMove(ActionEvent e) { JButton btn = (JButton) e.getSource(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (btn.equals(buttons[i][j])) { if (board[i][j] != 0) { return false; } board[i][j] = 1; refresh(board); return true; } } } return false;
  • 11. } boolean board_is_full() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == 0) return false; } } return true; } ActionListener refreshListener = new ActionListener(){ int delayCount = 0; public void actionPerformed(ActionEvent event){ delayCount++; if (delayCount > 5) { delayCount = 0; timer.stop(); enableButtons(false); } if (delayCount % 2 == 0) { refresh(board); } else { int [][] x = new int[3][3]; refresh(x); } } }; void enableButtons(boolean enable) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { buttons[i][j].setEnabled(enable); } } } ActionListener computerMove = new ActionListener(){ public void actionPerformed(ActionEvent event){
  • 12. /* FIX ME #4: The computer moves by placing an 'O' on the board * (i.e.), assigning a -1 to a valid element of the board array * The computer can play randomly, by randomly selecting a * row and column to play in, and repeating until a valid (empty) * spot on the board is found. Optionally, the computer can * play strategically, though this is more challenging. */ mainloop: for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ if(!(board[i][j]==1 || board[i][j]==-1)){ board[i][j] = -1; buttons[i][j].setForeground(Color.pink); buttons[i][j].setText("O"); break mainloop; } } } System.out.println("The computer's move..."); // refresh board and set up for player's move // DO NOT CHANGE THESE STATEMENTS! refresh(board); status.setText("Player's Move"); enableButtons(true); if (have_winner(-1)) { winning_board(-1); } else { status.setText("Player's Move"); } enableButtons(true); } }; ActionListener newGame = new ActionListener() { public void actionPerformed(ActionEvent e) {
  • 13. System.out.println("newGame"); // FIX ME #6: set each value of the 'board' to 0 refresh(board); enableButtons(true); status.setText("Player's turn"); status.setForeground(Color.black); } }; void winning_board(int val) { if (val == 1) { status.setText("PLAYER WINS!"); status.setForeground(Color.blue); } else if (val == -1) { status.setText("COMPUTER WINS!"); status.setForeground(Color.pink); } timer = new Timer(500, refreshListener); timer.setRepeats(true); timer.start(); } ActionListener onClick = new ActionListener() { public void actionPerformed(ActionEvent e) { if (timer != null && timer.isRunning()) { timer.stop(); } int delay = 0; if (CPU_PAUSE) delay = 1000; boolean player = playerMove(e); if (player) { if (have_winner(1)) { winning_board(1); return; } else if (board_is_full()) { status.setText("IT'S A TIE!");
  • 14. return; } status.setText("Computer is thinking..."); enableButtons(false); Timer timer = new Timer(delay, computerMove); timer.setRepeats(false); timer.start(); } else { System.out.println("No move "); } } }; TicTacToe(){ labelPanel.setLayout(new GridLayout(2,3)); for (int i = 0; i < 6; i++) { if (i!=1) { labelPanel.add(new JLabel()); } else { status.setText("Player's move..."); labelPanel.add(status); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { buttons[i][j] = new JButton(" "); buttons[i][j].setFont(new Font("Arial", Font.BOLD, 50)); buttons[i][j].addActionListener(onClick); buttonPanel.add(buttons[i][j]); } } buttonPanel.setLayout(new GridLayout(3,3)); frame.setSize(700,300); frame.add(labelPanel, BorderLayout.SOUTH); frame.add(buttonPanel, BorderLayout.NORTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  • 15. // Creates a menubar for a JFrame JMenuBar menuBar = new JMenuBar(); // Define and add two drop down menu to the menubar JMenu fileMenu = new JMenu("File"); JMenuItem newGameItem = new JMenuItem("New Game"); newGameItem.addActionListener(newGame); fileMenu.add(newGameItem); menuBar.add(fileMenu); // Add the menubar to the frame frame.setJMenuBar(menuBar); frame.setVisible(true); refresh(board); } public static void main(String[] args) { new TicTacToe(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }