Tic Tac Toe Assignment
Hi, I'm brand new to your website this is my first post. I am currently in a Computer Science class and extremely new to Java. Our teacher gave us an assignment in Java (Eclipse) for Tic Tac Toe. I have the interface built already with Player One being X's and Player Two being O's and everything seems to work out but I have a major problem. When I get a player with 3 in a row I need a line to pop and for a message signify the winner. I have absolutely no idea on how to do this. So if there is anyone out there that would like to give me some guidance I would be greatly appreciated. I will just post my code below. Thank you very much.
package mmr.ics3m1.tictac;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
public class tictactoe extends javax.swing.JFrame {
private JLabel lblPlayer1;
private JLabel lblPlayer2;
private AbstractAction actionButtonPressed4;
private AbstractAction actionExit;
private JButton butExit;
private AbstractAction actionButtonPressed9;
private AbstractAction actionButtonPressed8;
private AbstractAction actionButtonPressed7;
private AbstractAction actionButtonPressed6;
private AbstractAction actionButtonPressed5;
private AbstractAction actionButtonPressed3;
private AbstractAction actionButtonPressed2;
private AbstractAction actionButtonPressed;
private JButton butCell;
private JButton butCell2;
private JButton butCell3;
private JButton butCell4;
private JButton butCell5;
private JButton butCell6;
private JButton butCell7;
private JButton butCell8;
private JButton butCell9;
private Boolean blnPlayer1=true;
* Auto-generated main method to display this JFrame
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tictactoe inst = new tictactoe();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
public tictactoe() {
super();
initGUI();
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
lblPlayer1 = new JLabel();
getContentPane().add(lblPlayer1);
lblPlayer1.setText("Player One=X");
lblPlayer1.setBounds(28, 17, 110, 36);
lblPlayer1.setFont(new java.awt.Font("Segoe UI",3,12));
lblPlayer2 = new JLabel();
getContentPane().add(lblPlayer2);
lblPlayer2.setText("Player Two=O");
lblPlayer2.setBounds(245, 24, 83, 19);
lblPlayer2.setFont(new java.awt.Font("Segoe UI",3,12));
butCell = new JButton();
getContentPane().add(butCell);
getContentPane().add(getButCell2());
getContentPane().add(getButCell3());
getContentPane().add(getButCell4());
getContentPane().add(getButCell5());
getContentPane().add(getButCell6());
getContentPane().add(getButCell7());
getContentPane().add(getButCell8());
getContentPane().add(getButCell9());
getContentPane().add(getButExit());
butCell.setText("?");
butCell.setBounds(28, 65, 59, 40);
butCell.setAction(getActionButtonPressed(butCell));
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
private AbstractAction getActionButtonPressed(final JButton pcell) {
if(actionButtonPressed == null) {
actionButtonPressed = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell.setText("X");
blnPlayer1=false;
else{
pcell.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed;
private JButton getButCell2() {
if(butCell2 == null) {
butCell2 = new JButton();
butCell2.setText("?");
butCell2.setBounds(150, 65, 59, 40);
butCell2.setAction(getActionButtonPressed2(butCell2));
return butCell2;
private AbstractAction getActionButtonPressed2(final JButton pcell2) {
if(actionButtonPressed2 == null) {
actionButtonPressed2 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell2.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell2.setText("X");
blnPlayer1=false;
else{
pcell2.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed2;
return actionButtonPressed;
private JButton getButCell3() {
if(butCell3 == null) {
butCell3 = new JButton();
butCell3.setText("?");
butCell3.setBounds(269, 65, 59, 40);
butCell3.setAction(getActionButtonPressed3(butCell3));
return butCell3;
private JButton getButCell4() {
if(butCell4 == null) {
butCell4 = new JButton();
butCell4.setText("?");
butCell4.setBounds(28, 116, 59, 40);
butCell4.setAction(getActionButtonPressed4(butCell4));
return butCell4;
private JButton getButCell5() {
if(butCell5 == null) {
butCell5 = new JButton();
butCell5.setText("?");
butCell5.setBounds(149, 116, 59, 40);
butCell5.setAction(getActionButtonPressed5(butCell5));
return butCell5;
private JButton getButCell6() {
if(butCell6 == null) {
butCell6 = new JButton();
butCell6.setText("?");
butCell6.setBounds(269, 116, 59, 40);
butCell6.setAction(getActionButtonPressed6(butCell6));
return butCell6;
private JButton getButCell7() {
if(butCell7 == null) {
butCell7 = new JButton();
butCell7.setText("?");
butCell7.setBounds(28, 161, 59, 40);
butCell7.setAction(getActionButtonPressed7(butCell7));
return butCell7;
private JButton getButCell8() {
if(butCell8 == null) {
butCell8 = new JButton();
butCell8.setText("?");
butCell8.setBounds(149, 161, 59, 40);
butCell8.setAction(getActionButtonPressed8(butCell8));
return butCell8;
private JButton getButCell9() {
if(butCell9 == null) {
butCell9 = new JButton();
butCell9.setText("?");
butCell9.setBounds(269, 161, 59, 40);
butCell9.setAction(getActionButtonPressed9(butCell9));
return butCell9;
private AbstractAction getActionButtonPressed3(final JButton pcell3) {
if(actionButtonPressed3 == null) {
actionButtonPressed3 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell3.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell3.setText("X");
blnPlayer1=false;
else{
pcell3.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed3;
private AbstractAction getActionButtonPressed4(final JButton pcell4) {
if(actionButtonPressed4 == null) {
actionButtonPressed4 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell4.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell4.setText("X");
blnPlayer1=false;
else{
pcell4.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed4;
private AbstractAction getActionButtonPressed5(final JButton pcell5) {
if(actionButtonPressed5 == null) {
actionButtonPressed5 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell5.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell5.setText("X");
blnPlayer1=false;
else{
pcell5.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed5;
private AbstractAction getActionButtonPressed6(final JButton pcell6) {
if(actionButtonPressed6 == null) {
actionButtonPressed6 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell6.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell6.setText("X");
blnPlayer1=false;
else{
pcell6.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed6;
private AbstractAction getActionButtonPressed7(final JButton pcell7) {
if(actionButtonPressed7 == null) {
actionButtonPressed7 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell7.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell7.setText("X");
blnPlayer1=false;
else{
pcell7.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed7;
private AbstractAction getActionButtonPressed8(final JButton pcell8) {
if(actionButtonPressed8 == null) {
actionButtonPressed8 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell8.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell8.setText("X");
blnPlayer1=false;
else{
pcell8.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed8;
private AbstractAction getActionButtonPressed9(final JButton pcell9) {
if(actionButtonPressed9 == null) {
actionButtonPressed9 = new AbstractAction("?", null) {
public void actionPerformed(ActionEvent evt) {
if (pcell9.getText()=="?")
//set square to X or O
if (blnPlayer1){
pcell9.setText("X");
blnPlayer1=false;
else{
pcell9.setText("O");
blnPlayer1=true;
else
System.out.println("already taken");
return actionButtonPressed9;
private JButton getButExit() {
if(butExit == null) {
butExit = new JButton();
butExit.setText("Exit");
butExit.setBounds(328, 231, 56, 33);
butExit.setAction(getActionExit());
return butExit;
private AbstractAction getActionExit() {
if(actionExit == null) {
actionExit = new AbstractAction("Exit", null) {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
return actionExit;
}
Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
http://forum.java.sun.com/help.jspa?sec=formatting
When I get a player with 3 in a row I need a line to pop and for a message signify the winner. Use a JOptionPane. Read the JOptionPane API and you will find a link to the Swing tutorial on "How to Use Dialogs".
Similar Messages
-
I need help on a Tic Tac Toe game I am making for a class. I had finished a "2 Player" version and my instructor wants me to simulate a computer "AI" now. I cannot figure out what I'm doing wrong. The order of precedence is this:
1. X moves first (the player)
2. Computer moves to win.
3. If it can't win, it moves to block a win
4. If it can't block a win, it moves to the best possible spot to set up a win.
I think my problems are with several methods, but I cannot figure out what I'm doing wrong. Every time I look at my code, it just makes "sense". I think my problems could probably be found in 4 methods, setButtonText(), findOpen(), findBestOpen() and tempCheck(). I would like hints or maybe if I could get a second look at it for me.
public class VangTicTacToe extends javax.swing.JFrame {
private boolean isX;
private int turnCount;
private boolean gameWon;
private boolean isTemp;
/** Creates new form VangTicTacToe */
public VangTicTacToe() {
initComponents();
resetGame();
isX = true;
turnCount = 0;
private void checkWinner(String pressedButton){
//an multi-dimensional array of winning combinations
JButton[][] winningCombos = {{oneJButton, twoJButton,
threeJButton}, {oneJButton, fourJButton,
sevenJButton}, {oneJButton, fiveJButton, nineJButton},
{twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
String buttonPressed = pressedButton;
//loops and determines if any of the possible winning combinations have been
//met for X and displays output accordingly
for(JButton[] row : winningCombos){
for(JButton button : row){
if(button.getText().equals(buttonPressed)){
gameWon = true;
else{
gameWon = false;
break;
}//end inner for
if(gameWon == true && isTemp == false){
for(JButton button : row){
button.setBackground(Color.green);
}//end inner for
if(pressedButton.equals("X"))
outputJLabel.setText("Congratulations! Player 1 (\"X\") Wins!");
else
outputJLabel.setText("Sorry, computer wins.");
disableButtons();
break;
}//end if
else{
continue;//go to next outer loop and keep searching
}//end outer for
}//end method checkWinner
private void setButtonText(JButton buttonPressed){
if(isX == true){
buttonPressed.setText("X");
isX = false;
checkWinner("X");
outputJLabel.setText("Computer's turn");
isTemp = true; //sets isTemp to true so that the test is temporary
findOpen();//calls findOpen to start computer move
//disable the button so it cannot be pressed again
buttonPressed.setEnabled(false);
//increment the turn count number
turnCount++;
if(turnCount == 9)
outputJLabel.setText("Cats Game! You both are losers!");
}//end method setText
//the following 3 methods are for a computer move
//find next open space
private void findOpen(){
//array of buttons
JButton[] buttons = {oneJButton, twoJButton, threeJButton, fourJButton,
fiveJButton, sixJButton, sevenJButton, eightJButton, nineJButton};
//moves through array of buttons and looks for empty. If empty,
//it calls temporary select method.
for (int count = 0; count < buttons.length; count++){
if(buttons[count].getText().isEmpty())
tempCheck(buttons[count]);
}//end for loop
//if gameWon is false, call findBestButton to find the best open spot
if(gameWon == false){
findBestButton();
}//end method findOpen
private void findBestButton(){
//an multi-dimensional array of winning combinations
JButton[][] winningCombos = {{oneJButton, twoJButton,
threeJButton}, {oneJButton, fourJButton,
sevenJButton}, {oneJButton, fiveJButton, nineJButton},
{twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
boolean placeO = false;
int buttonCount = 0;
for(JButton[] row : winningCombos){
for(JButton button : row){
if(button.getText().equals("O") || button.getText().equals("")){
placeO = true;
else{
placeO = false;
buttonCount = 0;
if(placeO == true){
++buttonCount;
else{
break;
if(buttonCount == 3 && placeO == true){
button.setText("O");
}//end inner for
if(placeO == true){
isX = true;
break;
else{
continue;
}//end outer for
}//end method findBestButton
//checks if temp move would win
private void tempCheck(JButton tempButton){
//temporarily assigns "O" to a square and checks if it wins
tempButton.setText("O");
checkWinner("O");
if(gameWon == true){//if it wins then set temp to false and call
isTemp = false;//checkWinner();
checkWinner("0");
else{
tempButton.setText("");//else, set buttonText to empty
}//end if
if(gameWon == false){//if gameWon is false, check if "X" would win
tempButton.setText("X");
isTemp = true;
checkWinner("X");
if(gameWon == true){//if x is going to win,
tempButton.setText("O");//block the player from winning
else{
tempButton.setText("X");
}//end method tempCheck()
}touandcim wrote:
I click to make "X"'s (the player's move). X appears but O never does, although a button is highlighted. If I keep pressing the buttons, all X's appear until the last move, when an "O" appears.I don't know if it's the problem, but
checkWinner("0");looks suspicious. (2nd invocation in your tempCheck() method).
Your program seems awfully brittle. How would you do it if you had a 4 x 4 board? Or 5 x 5?
Also, your 'winningCombos' array is repeated everywhere it's used. There's no need for that; just make it an instance variable/constant.
Winston -
Help with Tic Tac Toe program....
I am writing a tic tac toe program, and I have already put the 9 boxes onto the screen so that it looks like the Tic Tac Toe board.
My first box looks something like this:
Rectangle2D.Double box1 = new Rectangle2D.Double(0, 0, 100, 100);
g2.draw(box1);
I want assign a number to the 9 boxes so it looks like this:
123
456
789
And I want to know how am I suppose to assign a number to a box, so that when the number is pressed it will put an "X" or "O"(depending on whose turn it is).
P.S. If you already made a Tic Tac Toe progaram can you post it so I will have an idea of what you did. thx.I'd hate to post the whole thing, but if you don't have access to it, here it goes:
* @(#)TicTacToe.java 1.6 01/12/03
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.*;
import java.applet.*;
* A TicTacToe applet. A very simple, and mostly brain-dead
* implementation of your favorite game! <p>
* In this game a position is represented by a white and black
* bitmask. A bit is set if a position is ocupied. There are
* 9 squares so there are 1<<9 possible positions for each
* side. An array of 1<<9 booleans is created, it marks
* all the winning positions.
* @version 1.2, 13 Oct 1995
* @author Arthur van Hoff
* @modified 04/23/96 Jim Hagen : winning sounds
* @modified 02/10/98 Mike McCloskey : added destroy()
public
class TicTacToe extends Applet implements MouseListener {
* White's current position. The computer is white.
int white;
* Black's current position. The user is black.
int black;
* The squares in order of importance...
final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
* The winning positions.
static boolean won[] = new boolean[1 << 9];
static final int DONE = (1 << 9) - 1;
static final int OK = 0;
static final int WIN = 1;
static final int LOSE = 2;
static final int STALEMATE = 3;
* Mark all positions with these bits set as winning.
static void isWon(int pos) {
for (int i = 0 ; i < DONE ; i++) {
if ((i & pos) == pos) {
won[i] = true;
* Initialize all winning positions.
static {
isWon((1 << 0) | (1 << 1) | (1 << 2));
isWon((1 << 3) | (1 << 4) | (1 << 5));
isWon((1 << 6) | (1 << 7) | (1 << 8));
isWon((1 << 0) | (1 << 3) | (1 << 6));
isWon((1 << 1) | (1 << 4) | (1 << 7));
isWon((1 << 2) | (1 << 5) | (1 << 8));
isWon((1 << 0) | (1 << 4) | (1 << 8));
isWon((1 << 2) | (1 << 4) | (1 << 6));
* Compute the best move for white.
* @return the square to take
int bestMove(int white, int black) {
int bestmove = -1;
loop:
for (int i = 0 ; i < 9 ; i++) {
int mw = moves;
if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
int pw = white | (1 << mw);
if (won[pw]) {
// white wins, take it!
return mw;
for (int mb = 0 ; mb < 9 ; mb++) {
if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
int pb = black | (1 << mb);
if (won[pb]) {
// black wins, take another
continue loop;
// Neither white nor black can win in one move, this will do.
if (bestmove == -1) {
bestmove = mw;
if (bestmove != -1) {
return bestmove;
// No move is totally satisfactory, try the first one that is open
for (int i = 0 ; i < 9 ; i++) {
int mw = moves[i];
if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
return mw;
// No more moves
return -1;
* User move.
* @return true if legal
boolean yourMove(int m) {
if ((m < 0) || (m > 8)) {
return false;
if (((black | white) & (1 << m)) != 0) {
return false;
black |= 1 << m;
return true;
* Computer move.
* @return true if legal
boolean myMove() {
if ((black | white) == DONE) {
return false;
int best = bestMove(white, black);
white |= 1 << best;
return true;
* Figure what the status of the game is.
int status() {
if (won[white]) {
return WIN;
if (won[black]) {
return LOSE;
if ((black | white) == DONE) {
return STALEMATE;
return OK;
* Who goes first in the next game?
boolean first = true;
* The image for white.
Image notImage;
* The image for black.
Image crossImage;
* Initialize the applet. Resize and load images.
public void init() {
notImage = getImage(getCodeBase(), "images/not.gif");
crossImage = getImage(getCodeBase(), "images/cross.gif");
addMouseListener(this);
public void destroy() {
removeMouseListener(this);
* Paint it.
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.black);
int xoff = d.width / 3;
int yoff = d.height / 3;
g.drawLine(xoff, 0, xoff, d.height);
g.drawLine(2*xoff, 0, 2*xoff, d.height);
g.drawLine(0, yoff, d.width, yoff);
g.drawLine(0, 2*yoff, d.width, 2*yoff);
int i = 0;
for (int r = 0 ; r < 3 ; r++) {
for (int c = 0 ; c < 3 ; c++, i++) {
if ((white & (1 << i)) != 0) {
g.drawImage(notImage, c*xoff + 1, r*yoff + 1, this);
} else if ((black & (1 << i)) != 0) {
g.drawImage(crossImage, c*xoff + 1, r*yoff + 1, this);
* The user has clicked in the applet. Figure out where
* and see if a legal move is possible. If it is a legal
* move, respond with a legal move (if possible).
public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
switch (status()) {
case WIN:
case LOSE:
case STALEMATE:
play(getCodeBase(), "audio/return.au");
white = black = 0;
if (first) {
white |= 1 << (int)(Math.random() * 9);
first = !first;
repaint();
return;
// Figure out the row/column
Dimension d = getSize();
int c = (x * 3) / d.width;
int r = (y * 3) / d.height;
if (yourMove(c + r * 3)) {
repaint();
switch (status()) {
case WIN:
play(getCodeBase(), "audio/yahoo1.au");
break;
case LOSE:
play(getCodeBase(), "audio/yahoo2.au");
break;
case STALEMATE:
break;
default:
if (myMove()) {
repaint();
switch (status()) {
case WIN:
play(getCodeBase(), "audio/yahoo1.au");
break;
case LOSE:
play(getCodeBase(), "audio/yahoo2.au");
break;
case STALEMATE:
break;
default:
play(getCodeBase(), "audio/ding.au");
} else {
play(getCodeBase(), "audio/beep.au");
} else {
play(getCodeBase(), "audio/beep.au");
public void mousePressed(MouseEvent e) {
public void mouseClicked(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
public void mouseExited(MouseEvent e) {
public String getAppletInfo() {
return "TicTacToe by Arthur van Hoff"; -
I wrote a Tic tac toe program in net beans aka Java and i wanna know how to get it on my geocities website.
P.S
There are 10 dukes dollars assigned, help would be appreciatedOtherwise I could become dramatically de-incented.Yes, student85, and what about poor Laszlo in thread http://forum.java.sun.com/thread.jspa?threadID=5170840
He's an old man who walks with a cane and you can't spare him a duke! -
3d project cube shaped tic tac toe
with java3d could i build the following?
I'm looking to make a 3d 4X4X4 cube for playing a game of tic tac toe.
i want the 3d cube to have hot spots on it, where a click of the mouse would assign an x or o in that location.
is this possible?Sorta like:
http://www.cs.bris.ac.uk/Teaching/Resources/COMSM0105/J3D/Examples/FourByFour/fbf.html
source:
http://www.cs.bris.ac.uk/Teaching/Resources/COMSM0105/J3D/Examples/FourByFour/
This is an example that comes with the java 3d libraries. -
Tic tac toe 3x3 multiplaye​r game
How can i build a tic tac toe game in labview
What im interested in is the following
1) A 3x3 multiplayer game
2) A boolean to move left in the tictactoe grid and another to move down
3) A boolean array to display the grid an another string array to show the X and O's
4) A boolean to confirm player's choice
5) A way to choose whether player 1 or player 2 begins
6) A way to show which player wins or loses, or if it is a draw.
Thank You in Advance
I appreciate your helpSome of your classmates with the same assignment already asked this quesiton. Why don't you do a quick search before starting a new thread?
LabVIEW Champion . Do more with less code and in less time . -
Does anyone know of an open-source implementation of Tic-Tac-Toe using Graphs? I'm reading through Michael Mann's Data Structures and Other Objects Using Java book and in chapter 14, he briefly mentions the use of directed graphs in implementing a game of Tic Tac Toe. I'm interested in seeing how one would implement something of this sort (and no, it's not a homework assignment).
If someone would be kind enough as to post a link to a site that offers mini-java applications, along with code that novice developers such as myself can traverse, please do so.
Thanks in advance.As an added though, there's really no need to for each node to keep track of incoming connections, only outgoing ones. What I, personally would do is keep an array of 8 outgoing connections, one for each direction. If no connection was there, then that element in the array would be null. If a connection was there, then that element would be an edge connecting to another node, or the other node itself (depending on whether or not you explicitly implemented 'edges' in your graph).
That way, you could do something like:
Node s = getOneOfTheEdgeNodes();
boolean hasWinner = false;
try {
for (int i = 0; i < 8; i ++) {
if (s.getOutgoing(i).getNode().getOutgoing(i).getNode() != null) {
hasWinner = true;
break;
} catch (NullPointerException npx) {
// No winner.
if (hasWinner)
System.out.println(s.getPlayer() + " has won");Yeah, that's a shitty example, but hopefully you get my drift.
Jason -
Help in swing app. tic tac toe
Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
import java.awt.*; //import
import javax.swing.*; //import
import java.awt.event.*; //import
import java.awt.Rectangle; //import
import java.awt.Font; //import
import javax.swing.BorderFactory; //import
import javax.swing.border.TitledBorder; //import
import java.awt.Color; //import
public class TicTacToeFrame extends JFrame implements ActionListener {
public TicTacToeFrame() {
try { //try the following
jbInit();
} catch (Exception ex) { // exit on [X]
ex.printStackTrace(); //exit and print errors
int xWon = 0; //counting how many times O has won
int oWon = 0; //counting how many times X has one
double i = 0; // loop variable to determine turn
public void actionPerformed(ActionEvent e) {
String turn = "null"; //current turn
String notTurn = "null"; //not current turn
newGameBUT.setEnabled(false); //disable new game button
if (i % 2 == 0) { // for determining who's turn it is
turn = "X"; // X's turn when counter is even
notTurn = "O"; //notTurn used to show who's turn it is in turnTF
if (i % 2 != 0) { // for determining who's turn it is
turn = "O"; // O's turn when counter is odd
notTurn = "X"; //notTurn used to show who's turn it is in turnTF
turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
if (e.getSource() == sqOneBUT) { //disable and print X or O to button
sqOneBUT.setText(turn); //printing players symbol
sqOneBUT.setEnabled(false); //disabling button
if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
sqTwoBUT.setText(turn); //printing players symbol
sqTwoBUT.setEnabled(false); //disabling button
if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
sqThreeBUT.setText(turn); //printing players symbol
sqThreeBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFourBUT) { //disable and print X or O to button
sqFourBUT.setText(turn); //printing players symbol
sqFourBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
sqFiveBUT.setText(turn); //printing players symbol
sqFiveBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSixBUT) { //disable and print X or O to button
sqSixBUT.setText(turn); //printing players symbol
sqSixBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
sqSevenBUT.setText(turn); //printing players symbol
sqSevenBUT.setEnabled(false); //disabling button
if (e.getSource() == sqEightBUT) { //disable and print X or O to button
sqEightBUT.setText(turn); //printing players symbol
sqEightBUT.setEnabled(false); //disabling button
if (e.getSource() == sqNineBUT) { //disable and print X or O to button
sqNineBUT.setText(turn); //printing players symbol
sqNineBUT.setEnabled(false); //disabling button
String sqOne = sqOneBUT.getText(); // Strings to read to find winner
String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
String sqFour = sqFourBUT.getText(); // Strings to read to find winner
String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
String sqSix = sqSixBUT.getText(); // Strings to read to find winner
String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
String sqEight = sqEightBUT.getText(); // Strings to read to find winner
String sqNine = sqNineBUT.getText(); // Strings to read to find winner
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
//horizontal, top, o wins
if (sqOne == "O") { //checking too see if player O has won
if (sqFour == "O") {
if (sqSeven == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
//vertical, left, o wins
if (sqOne == "O") { //checking too see if player O has won
if (sqTwo == "O") {
if (sqThree == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top left to bottom right, o wins
if (sqOne == "O") {
if (sqFive == "O") { //checking too see if player O has won
if (sqNine == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, mid, o wins
if (sqTwo == "O") { //checking too see if player O has won
if (sqFive == "O") {
if (sqEight == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, bottom, o wins
if (sqThree == "O") { //checking too see if player O has won
if (sqSix == "O") {
if (sqNine == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top right to bottom left, o wins
if (sqThree == "O") { //checking too see if player O has won
if (sqFive == "O") {
if (sqSeven == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//horizontal, top, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqFour == "X") {
if (sqSeven == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
//vertical, left, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqTwo == "X") {
if (sqThree == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top left to bottom right, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqNine == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, mid, x wins
if (sqTwo == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqEight == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, bottom, x wins
if (sqThree == "X") { //checking too see if player X has won
if (sqSix == "X") {
if (sqNine == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top right to bottom left, x wins
if (sqThree == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqSeven == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
String wins = turnTF.getText(); //Reading who won to print win winTF
if (wins.equals("X wins!")) { //if X wins
xWon++; //adding 1 to X's amount of wins
String xWonString = Integer.toString(xWon); //converting to String
xWinsTF.setText(xWonString); //displaying # of wins
newGameBUT.setEnabled(true); //enable new game button
if (wins.equals("O wins!")) { //if O wins
oWon++; //adding 1 to O's amount of wins
String oWonString = Integer.toString(oWon); //converting to String
oWinsTF.setText(oWonString); //displaying # of wins
newGameBUT.setEnabled(true); //enable new game button
if (e.getSource() == newGameBUT) {
i++; // turn switch
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
this.getContentPane().setBackground(Color.darkGray);
sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
sqTwoBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
sqFourBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
sqFiveBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
sqSixBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
sqOneBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
sqEightBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
sqNineBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
sqSevenBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqOneBUT.addActionListener(this);
sqTwoBUT.addActionListener(this);
sqThreeBUT.addActionListener(this);
sqFourBUT.addActionListener(this);
sqFiveBUT.addActionListener(this);
sqSixBUT.addActionListener(this);
sqSevenBUT.addActionListener(this);
sqEightBUT.addActionListener(this);
sqNineBUT.addActionListener(this);
newGameBUT.addActionListener(this);
sqThreeBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
turnTF.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
turnTF.setEditable(false);
turnTF.setText("X goes first");
turnTF.setHorizontalAlignment(SwingConstants.CENTER);
turnTF.setBounds(new Rectangle(2, 346, 346, 35));
oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 18));
oWinsTF.setEditable(false);
oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 18));
xWinsTF.setEditable(false);
xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.PLAIN, 16));
oWinsLBL.setForeground(Color.white);
oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
oWinsLBL.setText("O wins:");
oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.PLAIN, 16));
xWinsLBL.setForeground(Color.white);
xWinsLBL.setDisplayedMnemonic('0');
xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
xWinsLBL.setText("X wins:");
xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 14));
newGameBUT.setText("New Game");
this.getContentPane().add(sqFourBUT);
this.getContentPane().add(sqThreeBUT);
this.getContentPane().add(sqTwoBUT);
this.getContentPane().add(sqOneBUT);
this.getContentPane().add(sqFiveBUT);
this.getContentPane().add(sqSixBUT);
this.getContentPane().add(sqNineBUT);
this.getContentPane().add(sqEightBUT);
this.getContentPane().add(sqSevenBUT);
this.getContentPane().add(turnTF);
this.getContentPane().add(xWinsLBL);
this.getContentPane().add(xWinsTF);
this.getContentPane().add(oWinsLBL);
this.getContentPane().add(oWinsTF);
this.getContentPane().add(newGameBUT);
sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
JButton sqTwoBUT = new JButton();
JButton sqThreeBUT = new JButton();
JButton sqFourBUT = new JButton();
JButton sqFiveBUT = new JButton();
JButton sqSixBUT = new JButton();
JButton sqOneBUT = new JButton();
JButton sqEightBUT = new JButton();
JButton sqNineBUT = new JButton();
JButton sqSevenBUT = new JButton();
JTextField turnTF = new JTextField();
JTextField oWinsTF = new JTextField();
JTextField xWinsTF = new JTextField();
JLabel oWinsLBL = new JLabel();
JLabel xWinsLBL = new JLabel();
JButton newGameBUT = new JButton();
}This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
if (e.getSource() == sqOneBUT) { //disable and print X or O to button
sqOneBUT.setText(turn); //printing players symbol
sqOneBUT.setEnabled(false); //disabling button
if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
sqTwoBUT.setText(turn); //printing players symbol
sqTwoBUT.setEnabled(false); //disabling button
if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
sqThreeBUT.setText(turn); //printing players symbol
sqThreeBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFourBUT) { //disable and print X or O to button
sqFourBUT.setText(turn); //printing players symbol
sqFourBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
sqFiveBUT.setText(turn); //printing players symbol
sqFiveBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSixBUT) { //disable and print X or O to button
sqSixBUT.setText(turn); //printing players symbol
sqSixBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
sqSevenBUT.setText(turn); //printing players symbol
sqSevenBUT.setEnabled(false); //disabling button
if (e.getSource() == sqEightBUT) { //disable and print X or O to button
sqEightBUT.setText(turn); //printing players symbol
sqEightBUT.setEnabled(false); //disabling button
if (e.getSource() == sqNineBUT) { //disable and print X or O to button
sqNineBUT.setText(turn); //printing players symbol
sqNineBUT.setEnabled(false); //disabling button
String sqOne = sqOneBUT.getText(); // Strings to read to find winner
String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
String sqFour = sqFourBUT.getText(); // Strings to read to find winner
String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
String sqSix = sqSixBUT.getText(); // Strings to read to find winner
String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
String sqEight = sqEightBUT.getText(); // Strings to read to find winner
String sqNine = sqNineBUT.getText(); // Strings to read to find winner -
hey all,
i am having problems creating a tic tac toe program. the program should create a board with NxN spaces, where N is obtained through user input.
I created a fully working program that does a 3x3 board, checks for diagonal, vertical, horizontal wins and also allows 1 vs computer or 2 players play, but i am struggling with the NxN board.
here is the code of what i have, can anyone point me in the right direction? all help is appreciated! please keep it simple as possible as i am just learning java!!
import java.util.Scanner;
import java.util.Random;
public class NoughtsCrosses
static final String PLAYER1 = "X";
static final String PLAYER2 = "O";
static final String EMPTY = "�";
static String[][] board = new String[][];
static int turn = 0;
static public void makeBoard(int boardSize)
for (int x = 0; x < boardSize; x++)
for (int y = 0; y < boardSize; y++)
board[x][y] = new String(EMPTY);
static public void playComputer()
Scanner scan = new Scanner(System.in);
Random generator = new Random();
int move;
printBoard();
System.out.println();
do {
if(turn%2 == 0)
System.out.println("Player 1, place your X");
System.out.print("Make a Move: ");
move = scan.nextInt();
else
System.out.print("Computer, place your O: ");
move = generator.nextInt(10);
System.out.println(move);
getMove(move);
System.out.println();
printBoard();
System.out.println();
} while(winner().equals(EMPTY) && turn < 9);
if (winner().equals(EMPTY))
System.out.println("The Game s a DRAW!");
else
System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
static public void playHuman()
Scanner scan = new Scanner(System.in);
printBoard();
System.out.println();
do {
if(turn%2 == 0)
System.out.println("Player 1, place your X");
else
System.out.println("Player 2, place your O");
System.out.print("Make a Move: ");
int move = scan.nextInt();
getMove(move);
System.out.println();
printBoard();
System.out.println();
} while(winner().equals(EMPTY) && turn < 9);
if (winner().equals(EMPTY))
System.out.println("The Game s a DRAW!");
else
System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
static public void getMove(int move)
int row = move/3;
int col = move%3;
if (board[row][col].equals(EMPTY))
board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
turn++;
else
System.out.println("OCCUPIED FIELD! TRY AGAIN!");
static public void printBoard()
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if(y == 0)
System.out.print(" ");
System.out.print(board[x][y]);
if(y < 2)
System.out.print(" | ");
System.out.println();
if(x < 2)
System.out.println(" ---|---|---");
static public String winner()
for (int i = 0; i < board.length; i++)
/** check horizontally */
if (board[0].equals(board[i][1]) && board[i][0].equals(board[i][2]))
if (!board[i][0].equals(EMPTY))
return board[i][0];
/** check vertically */
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]))
if (!board[0][i].equals(EMPTY))
return board[0][i];
/** check diagonally */
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]))
if (!board[0][0].equals(EMPTY))
return board[0][0];
if (board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]))
if (!board[0][2].equals(EMPTY))
return board[0][2];
return EMPTY;
static public void main(String[] args)
Scanner scan = new Scanner(System.in);
int boardSize;
System.out.println();
System.out.println("Welcome to Tic Tac Toe!");
System.out.println("�����������������������");
System.out.println("How big should the board be?");
boardSize = scan.nextInt();
makeBoard(boardSize);
int players = 0;
do{
System.out.println("How many players?");
System.out.println("1 (vs. Computer) or 2 (vs. another player)?");
players = scan.nextInt();
System.out.println();
}while(players < 1 || players > 2);
if (players == 1)
playComputer();
else
playHuman();well, i figured out how to do it all, thanks to the TREMENDOUS amount of help here...lol...
i just have one more (minor problem)...
i can't get an algorithm working to see if the two diagonals are occupied by x's or o's (see if someone won diagonally)
to check horizontally & vertically on an NxN board, i use following code:
int count = 0;
/** check horizontally */
for (int i = 0; i < myBoard.length; i++)
for (int j = 0; j < myBoard.length-1; j++)
if (myBoard[0].equals(myBoard[i][j+1]) && !myBoard[i][0].equals(EMPTY))
count++;
if (count >= myBoard.length-1)
return myBoard[i][0];
count = 0;
count = 0;
/** check vertically */
for (int i = 0; i < myBoard.length; i++)
for (int j = 0; j < myBoard.length-1; j++)
if (myBoard[j][0].equals(myBoard[j+1][i]) && !myBoard[0][i].equals(EMPTY))
count++;
if (count >= myBoard.length-1)
return myBoard[0][i];
count = 0;
now i was messing around ALOT and couldn't figure out how to get the diagonals showing! this is what i came up with:
count =0;
for (int j = 1; j < myBoard.length; j++)
if (myBoard[0][0].equals(myBoard[j][j]) && !myBoard[0][0].equals(EMPTY))
count++;
System.out.println(count);
if (count >= myBoard.length)
return myBoard[0][0];
count = 0;
for (int j = myBoard.length-1; j >= 0; j--)
if (myBoard[0][myBoard.length-1].equals(myBoard[j][j]) && !myBoard[0][myBoard.length-1].equals(EMPTY))
count++;
System.out.println(count);
if (count >= myBoard.length)
return myBoard[0][myBoard.length-1];
count = 0; -
A Tic Tac Toe board is represented as an array of 9 chars. Write a program that will allow two users to play tic tac toe. The player should ask for moves alternately from players X and O. The program is too dumb to check whether anyone has won or lost and just stops after 9 turns. The program should display the game position as follows after each move.
The output should be somewhat as follows:
Choose a spot (1 to 9) for X: 1
X || ||
|| ||
|| ||
Basically i have to do this. I was wondering if anyone could lead me in the right direction please?class TicTacToe {
// instance variables
// constructor(s)
// method(s)
public static void main(String[] args) {
new TicTacToe();
}There you go. I got you started. Now all you need to do is finish. -
I have this code so far and it won't compile, and I don't know how to fix it, can anyone help me?
import java.awt.*;
import javax.swing.*;
public class TicTacToe extends JFrame{
public void main (String [] args){
TicTacToe t3 = new TicTacToe();
t3.setSize(400, 400);
t3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t3.setLayout(new GridLayout(3,3));
JButton NW = new JButton("");
JButton N = new JButton("");
JButton NE = new JButton("");
JButton W = new JButton("");
JButton C = new JButton("");
JButton E = new JButton("");
JButton SW = new JButton("");
JButton S = new JButton("");
JButton SE = new JButton("");
t3.add(NW);
NW.addActionListener(new PressedButton());
t3.add(N);
N.addActionListener(new PressedButton());
t3.add(NE);
NE.addActionListener(new PressedButton());
t3.add(W);
W.addActionListener(new PressedButton());
t3.add(C);
C.addActionListener(new PressedButton());
t3.add(E);
E.addActionListener(new PressedButton());
t3.add(SW);
SW.addActionListener(new PressedButton());
t3.add(S);
SW.addActionListener(new PressedButton());
t3.add(SE);
SE.addActionListener(new PressedButton());
t3.setVisible(true);
public class PressedButton implements ActionListener{
public void actionPerformed(ActionEvent e){
JButton button = (JButton)e.getSource();
if (O turn){
button.setText("O");
}else{
button.setText("X");
private class checkEndgame{
private void checkEndgame(){
for (final int[] winChance : TicTacToe.winChances) {
if (this.checkVictory(winChance)) {
final String winner = this.turn.equals("X") ? "O" : "X";
JOptionPane.showMessageDialog(this.frame, winner + " won the game!",
"Game Over", JOptionPane.INFORMATION_MESSAGE);
this.reset();
return;
Does anyone notice any errors that i might have over looked?
thanksOk scratch out that entire code, i started over and it still won't compile.
import java.awt.*;
import javax.swing.*;
import java.awt.event;
public class TicTacToe implements ActionListener{
private int[][] winCombinations = new int[][]{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{1, 4, 7}, {2, 5, 8}, {3, 6, 9},
{1, 5, 9}, {3, 5, 7}
private JFrame window = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[10];
private int count = 0;
private String letter = "";
private boolean win = false;
public class PressedButton{
public void actionPerformed(ActionEvent a) {
count++;
if(count % 2 == 0){
letter = "O";
} else {
letter = "X";
for(int t=1; t<=9; t++){
if(a.getSource() == buttons[t]){
buttons[t].setText(letter);
buttons[t].setEnabled(false);
for(int i=0; i<=7; i++){
if( buttons[winCombinations[t][0]].getText() == buttons[winCombinations[t][1]].getText() &&
buttons[winCombinations[t][1]].getText() == buttons[winCombinations[t][2]].getText() &&
buttons[winCombinations[t][0]].getText() != ""){
win = true;
if(win == true){
JOptionPane.showMessageDialog(null, letter + " wins the game!");
System.exit(0);
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null, "The game was a tie!");
System.exit(0);
the error message says that I still need a "}" on line 49 which is the line after the last bracket that I have, I put one there and it still shows up an error message, what do I do? -
Need some help with Tic Tac Toe game
hey. hope u guys can help me out...
having a problem with my tic tac toe program...
i have 2 problems.
1) got the "X" and "O" to appear using a flag(teacher didn't explain)
using code like this
if (jb == button[0]){
if (flag==0)
button[0].setText("X");
else
button[0].setText("O");
//toggle
flag = (flag==0)?1:0;
my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
2) found this code in javascript online and i want to do what it does in java code
if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
alert("You Win!");
reset();
how would i do that?
thanks for the help.ok here's my code:
//TTT.java
import javax.swing.*;
import java.awt.*;
import java .awt.event.*;
public class TTT extends JFrame
implements WindowListener, ActionListener
private JFrame frFirst;
private Container cnFirst,cnSecond;
private JButton button[]=new JButton[9];
private JButton btnNewGame,btnExit;
private FlowLayout southLayout;
private JPanel southPanel;
private int flag;
public TTT()
frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
cnFirst=frFirst.getContentPane();
cnFirst.setLayout (new GridLayout (4,4));
cnFirst.setBackground(Color.green);
for(int i=0;i<button.length;i++)
button[i] = new JButton();
cnFirst.add(button);
flag=0;
southPanel = new JPanel ();
btnNewGame = new JButton ("New Game");
southPanel.add (btnNewGame);
btnExit = new JButton ("EXIT");
southPanel.add (btnExit);
frFirst.add (southPanel,BorderLayout.SOUTH);
frFirst.setLocation(200, 200);
frFirst.setSize(400,400);
frFirst.setResizable(false);
frFirst.setVisible(true);
this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// listeners
frFirst.addWindowListener(this);
button[0].addActionListener(this);
button[1].addActionListener(this);
button[2].addActionListener(this);
button[3].addActionListener(this);
button[4].addActionListener(this);
button[5].addActionListener(this);
button[6].addActionListener(this);
button[7].addActionListener(this);
button[8].addActionListener(this);
btnNewGame.addActionListener (this);
btnExit.addActionListener (this);
//define methods of WindowListener
public void windowOpened(WindowEvent we)
public void windowClosing(WindowEvent we)
System.exit(0);
public void windowClosed(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowActivated(WindowEvent we)
public void windowDeactivated(WindowEvent we)
public void actionPerformed(ActionEvent ae)
//making the X and O to appear on JButtons
Object obj = ae.getSource();
if (obj instanceof JButton){
JButton jb = (JButton)obj;
if (jb == button[0])
if (flag==0)
button[0].setText("X");
else
button[0].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[1])
if (flag==0)
button[1].setText("X");
else
button[1].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[2])
if (flag==0)
button[2].setText("X");
else
button[2].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[3])
if (flag==0)
button[3].setText("X");
else
button[3].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[4])
if (flag==0)
button[4].setText("X");
else
button[4].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[5])
if (flag==0)
button[5].setText("X");
else
button[5].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[6])
if (flag==0)
button[6].setText("X");
else
button[6].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[7])
if (flag==0)
button[7].setText("X");
else
button[7].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[8])
if (flag==0)
button[8].setText("X");
else
button[8].setText("O");
//toggle
flag = (flag==0)?1:0;
//New Game To Reset
if (ae.getSource () == btnNewGame)
/* String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
String YES;
if (text == YES)
JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
else{
add code to reset game
//Exit Button to Exit
if (ae.getSource () == btnExit)
JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
this.setVisible(false);
System.exit(0);
} //end of if instanceof
public static void main(String[]args)
//instantiate GUI
new TTT(); -
hi, I've created my code and for the tic tac toe grid but I dont know how to make it look like a grid (i.e
1 2 3
4 5 6
7 8 9)
it has came out as "123X56789" "X" meaning a number has taken up a cross.
can anyone help??
heres the code of the grid........
// GAMEINTERFACE
public class GameInterface extends MyPrint
private String theGrid;
final static char NOUGHT='O', CROSS='X';
public GameInterface()
theGrid = "?123456789";
public void pictureBoard(String theGrid)
for(int i = 1; i<theGrid.length(); i++)
int hit = i%3;
if(hit!=0)
myPrint(Character.toString((theGrid.charAt(i))));
else
myPrint(Character.toString((theGrid.charAt(i))));
public void play(char cell, boolean playTurn)
char noughtCross = ' ';
if(playTurn = true)
noughtCross = CROSS;
else if(playTurn = false)
noughtCross = NOUGHT;
if('1'<=cell || cell<='9')
theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(CROSS) + theGrid.substring(theGrid.indexOf(cell)+1);
else if('1'<=cell || cell<='9')
theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(NOUGHT) + theGrid.substring(theGrid.indexOf(cell)+1);
public String display()
return theGrid;
Plus how do i create a 'O' in the output as 'X' appears for the 2 players playing.
this will be very appreciated.
many thanks
Davejust tried that warnerja, it doesnt work either.
it has to be linked to this other class(program below)
//GAME
public class Game extends MyPrint
GameInterface gameInterface;
String s = "?123456789";
Player player1;
Player player2;
public Game() // Constructor
public void makeMove()
gameInterface = new GameInterface ();
player1 = new Player ();
player2 = new Player ();
myPrintln("Enter name of player");
String FP = c.input.readString();
myPrintln(FP, SYSTEM);
myPrintln("Enter name of other player");
String SP = c.input.readString();
myPrintln(SP, SYSTEM);
gameInterface.pictureBoard(s);
myPrintln("");
//boolean whoWon=false;
int loop = 0;
while(loop<=6)
player1.setName(FP);
myPrintln(player1.getName() + " (X) to play");
myPrintln("Enter move by selecting number from grid");
myPrintln("or 0 to draw");
char name1 = c.input.readChar();
name1 = c.input.readChar();
boolean playTurn = true;
gameInterface.play(name1, true);
gameInterface.pictureBoard(gameInterface.display());
myPrintln("");
//if(checkWin(gameInt.display()))
// whoWon=true;
// break;
player2.setName(SP);
myPrintln(player2.getName() + " (O) to play");
myPrintln("Enter move by selecting number from grid");
myPrintln("or 0 to draw");
char name2 = c.input.readChar();
name2 = c.input.readChar();
playTurn = false;
gameInterface.play(name2, false);
gameInterface.pictureBoard(gameInterface.display());
myPrintln("");
//if(checkWin(gameInt.display()))
// whoWon=true;
// break;
loop++;
} -
Gui tris (tic tac toe)
Hi,
i am trying to create the tris game in java (maybe you know this game as tic tac toe). I created windows and the alghoritm to play. But now i have the problem to create the board. My idea is to create a board with nine clickable cells, the player clicks on the cell he wants (if it's free), then the computer plays and so on...but i don't have the knowledges of making complex graphic things in java. How can I do?ok, and how can i manage the player's click?MouseListener on the JLabel.
remember
also that when the player clicks, the program must
draw a symbol (x or o depending from the choice of
player). how can i do all this things? For a noob
like me this is very difficultRead the tutorials. I'm not going to explain to you how to create your app if you can read it up yourself. -
Why do I keep getting the following errors in a very simple, basic TIC TAC TOE program? Any help would be greatly appreciated. Thanks.
C:\Class\Teresa\TicTacToe017.java:114: 'else' without 'if'
else if (board[turnRow - 1][turnCol - 1] == 'X'
^
C:\Class\Teresa\TicTacToe017.java:185: 'else' without 'if'
else // Next player's turn
^
C:\Class\Teresa\TicTacToe017.java:39: cannot resolve symbol
symbol : method call ()
location: class TicTacToe017
call();
^
C:\Class\Teresa\TicTacToe017.java:145: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
C:\Class\Teresa\TicTacToe017.java:165: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
C:\Class\Teresa\TicTacToe017.java:181: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
6 errors
Tool completed with exit code 1
Here is my code so far.
File name: TicTacToe.java
A class to play TicTacToe.
Entries cannot be changed once they are entered.
Written by: Lew Rakocy
email address: [email protected]
Date: 9/2/00
Changes: 03/13/2003 Made comments like text examples.
Added code to display board after win and draw.
public class TicTacToe017
// Use a 3 X 3 (two-dimensional) array for the game board.
private static char[][] board = new char[3][3];
private static char turn;
private static int row; // Loop controls to
private static int col; // display the board
private static int turnRow; // User input to
private static int turnCol; // select move
private static boolean entryError;
private static boolean anotherGame = true;
private static char repeat; // User input: y or Y to repeat
private static int entryCount = 0; // Game ends when board is full
// (when entryCount = 9);
public static void main(String[] args)
while(anotherGame)
newGame();
while(!winner())
//WRITE THE METHOD CALL TO DISPLAY THE "BOARD" HERE
call();
System.out.println("This is the game board.");
//WRITE THE METHOD CALL FOR THE "PLAY" OF THE GAME HERE
System.out.print("Welcome to Teresa's Tic Tac Toe!");
System.out.println("Another game? Enter Y or y for yes.");
repeat = SavitchIn.readLineNonwhiteChar();
//WRITE THE IF/ELSE STATEMENT TO PLAY ANOTHER GAME HERE
if ((repeat == 'Y') || (repeat == 'y'))
System.out.println("Play another game.");
else
System.out.println("End of game. Thanks for playing.");
//WRITE THE HEADER FOR THE writeBoard METHOD HERE
System.out.println("-----------------");
System.out.println("|R\\C| 1 | 2 | 3 |");
System.out.println("-----------------");
for(row = 0; row < 3; ++row)
System.out.println("| " + (row + 1)
+ " | " + board[row][0]
+ " | " + board[row][1]
+ " | " + board[row][2]
+ " |");
System.out.println("-----------------");
private static void getMove()
entryError = true; // Will change to false if valid row
// and column numbers are entered.
while(entryError)
System.out.println();
System.out.println(turn + "'s turn.");
System.out.println("Where do what your " + turn + " placed?");
System.out.println(
"Please enter row number and column number"
+ " separated by a space.");
System.out.println();
turnRow = SavitchIn.readInt();
turnCol = SavitchIn.readInt();
System.out.println("You have entered row #" + turnRow);
System.out.println(" and column #" + turnCol);
// Check for proper range (1, 2, or 3)
//WRITE THE IF STATEMENT HERE FOR AN INVALID ENTRY
if (board[turnRow - 1][turnCol - 1] > 3)
System.out.println("Invalid entry: try again.");
System.out.println(
"Row & column numbers must be either 1, 2, or 3.");
// Check to see if it is already occupied
// Adjust turnRow and turnCol for 0-numbering in array
else if (board[turnRow - 1][turnCol - 1] == 'X'
|| board[turnRow - 1][turnCol - 1] == 'O')
System.out.println("That cell is already taken.");
System.out.println("Please make another selection.");
else // Valid entry
entryError = false;
System.out.println("Thank you for your selection.");
board[turnRow - 1][turnCol - 1] = turn;
++entryCount;
private static boolean winner()
// Row checks
for(row = 0; row < 3; ++row)
if(board[row][0] == turn)
if(board[row][1] == turn)
if(board[row][2] == turn)
System.out.println();
System.out.println (turn + " IS THE WINNER!!!");
writeBoard();
return true;
// WRITE A FOR LOOP FOR THE COLUMN CHECKS HERE
// WRITE A FOR LOOP FOR THE DIAGONAL CHECKS HERE
if(board[0][2] == turn)
if(board[1][1] == turn)
if(board[2][0] == turn)
System.out.println();
System.out.println (turn + " IS THE WINNER!!!");
writeBoard();
return true;
// These lines execute only if there is no winner.
// End game if board is full
//WRITE THE IF STATEMENT TO CHECK IF THE BOARD IS FULL
if (entryCount == 9)
System.out.println();
System.out.println("Draw: no winner and board is full.");
writeBoard();
return true;
else // Next player's turn
//WRTITE THE IF/ELSE STATEMENT FOR THE NEXT PLAYER'S TURN
return false;
private static void newGame()
System.out.println();
System.out.println("New Game: X goes first.");
turn = 'O'; // Turn will change to X when winner() is called
// Clear the board
for(row = 0; row < 3; ++row)
for(col = 0; col < 3; ++col)
board[row][col] = ' ';
entryCount = 0;
System.out.println();the "else without if" means that you have an else statement that wasn't attached to an if statement. In your case, it seems to be because you had multiple statements following an if statement, and you didn't enclose them in a single block.
The "cannot resolve symbol" means that you referred to something that wasn't defined. Either it's your code, and you forgot to define it, or you were referring to someone else's code, in which case you probably forgot an import statement, or you're using their code incorrectly.
Maybe you are looking for
-
I cannot export my iMove 11 films as before! New MacBook Pro Retina, same old mts-files
I have been using iMove on my old MacBook Pro for a long time, having trouble with ScreenFlow but never with iMovie. Until now. I manahed the actual project, making it as I use to. I went to "mediabläddrare", whatever that is in snglish, under "Share
-
I have successfully uploaded over 7300 to itunes. These songs have been acquired in multiple facets such as downloading, and burning from cd, etc. However, the last two albums I have tried to upload to itunes by dragging or by adding folder itunes ac
-
Problem with bapi to create purchase requisition
I got a requirement that to upload details of procurement into Z table with a temporary PR. Could u please suggest the procedure or bapi to upload datainto Z table. Regards
-
OutputLabes, values in selectOneChoice are appearing twice in the jspx page
Hi All, In a Jspx Page, there are two menu tabs. Each Tab has a PanelForm and each panelform has certain components. By default the first panelform in the first tab will be shown on page load and while clicking on second tab, the second panelform wil
-
Software Update does not keep packages.
When using Software Update, there is a choice to Download and Install Package. The help info, says that this will be kept in the Downloads folder, (as are downloads from Safari). Selecting Download and Install Package from the menu, which starts the