Tic tac toe game source code

Hi,
can any one give me the source code of tic tac toe game..
below is the requirement
1. Multi-Player online Tic-Tac-Toe game
2. Configurable to set from 3 to 6 sides
3. Able to create game, select a list of created open game, join the selected game
Please can i have the distributable war file...
Thanks in advance

Hi,
can any one give me the source code of tic tac toe game..
below is the requirement
1. Multi-Player online Tic-Tac-Toe game
2. Configurable to set from 3 to 6 sides
3. Able to create game, select a list of created open game, join the selected game
Please can i have the distributable war file...
Thanks in advance 

Similar Messages

  • Tic - Tac - Toe Game - Please Help!

    Hi everyone, I am attempting to create a tic - tac - toe game (O's & X's).
    I would like there to be two playing modes to the game, the first mode will be one player where the user plays against the computer. The second mode is a two - player game, where two users play, one being X's and the other being O's.
    Can anyone help me get started with this game, I know there is source code on the internet but I would rather not use this as I would like to learn as I create the game.
    Thanks Everyone

    its amazing how much code a simple game like tic-tac-toe can require.. well, only if you program the AI of the computer.. i wrote one in c++ last year, for my computer science class, and the whole class had trouble with it, mainly the AI.. a suggestion to you: write it in an object-oriented manner. i ended up writing it procedurally and in the end, it looked very bad, but it worked!
    i would prob. setup some objects like: Board (the 3x3 grid), Mark (a user mark, such as an "x" or an "o")..
    i dunno.. hope that helps some, if you need help with the AI at all.. i do have the tic-tac-toe program i wrote on my website (http://www.angelfire.com/blues/smb/ ) in the C++ section.. i used a graphics package, but the logic is all there and the code is well commented.
    anyway, ill talk to ya later, good luck,
    Steven Berardi

  • 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();

  • Need help/advice with tic tac toe game

    Hello all. I am working on a tic tac toe game. I was able to program the first 4 moves fine, but ame having trouble with moves 5 and 6 for reasons that are unknown to me. Everything complies fine, its just that the move is displayed int the wrong space (B1) instead of in B2 or B3. Also the move that is supposed to be in A1 disapppears when B2 or B3 is clicked. Also, I need advice as to how to keep the prior moves from being over written.
    At this point I ahve gone over the code on-screen, printed it out, and stared at my drawings... and I'm not having any luck. I'm sure its a small, stupid thing that I'm missing, that anyone else would easily catch. Once again, thx for all your help.
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    public class game3 extends Applet implements MouseListener{
         String move = "";
         boolean player1 = true;
         String gameBoard[][] = new String [3][3];
    public void spaceA1(Graphics g){ // MOVE IS A1
         if(gameBoard[0][0] == "X")
              g.drawString("X",65,65);
         if(gameBoard[0][0] == "O")
              g.drawString("O",65,65);
    public void spaceA2(Graphics g){ // MOVE IS A2
         if(gameBoard[0][1] == "X")
              g.drawString("X",95,65);
         if(gameBoard[0][1] == "O")
              g.drawString("O",95,65);                         
    public void spaceA3(Graphics g){ // MOVE IS A3               
         if(gameBoard[0][2] == "X")
              g.drawString("X",125,65);
         if(gameBoard[0][2] == "O")
              g.drawString("O",125,65);
    public void spaceB1(Graphics g){ // MOVE IS B1
         if(gameBoard[1][0] == "X")
              g.drawString("X",65,95);
         if(gameBoard[1][0] == "O")
              g.drawString("O",65,95);                    
    public void spaceB2(Graphics g){ // MOVE IS B2
         if(gameBoard[1][1] == "X")
              g.drawString("X",95,95);
         if(gameBoard[1][1] == "O")
              g.drawString("O",95,95);
    public void spaceB3(Graphics g){ // MOVE IS B3
         if(gameBoard[1][2] == "X")
              g.drawString("X",125,95);
         if(gameBoard[1][2] == "O")
              g.drawString("O",125,95);
    public void spaceC1(Graphics g){ // MOVE IS C1
         if(gameBoard[2][0] == "X")
              g.drawString("X",65,125);
         if(gameBoard[2][0] == "O")     
              g.drawString("O",65,125);     
    public void spaceC2(Graphics g){ // MOVE IS C2
         if(gameBoard[2][1] == "X")
              g.drawString("X",95,125);
         if(gameBoard[2][1] == "O")
              g.drawString("O",95,125);
    public void spaceC3(Graphics g){ // MOVE IS C3
         if(gameBoard[2][2] == "X")
              g.drawString("X",125,125);
         if(gameBoard[2][2] == "O")
              g.drawString("O",125,125);
    public void init(){
         addMouseListener(this);
         public void paint(Graphics g){
              g.drawString("    1       2       3", 50,45);
              g.drawString("A",40,70);
              g.drawString("B",40,100);
              g.drawString("C",40,130);
              // first row of boxes
              g.drawRect(50,50,30,30);
              g.drawRect(80,50,30,30);
              g.drawRect(110,50,30,30);
              // second row of boxes
              g.drawRect(50,80,30,30);
              g.drawRect(80,80,30,30);
              g.drawRect(110,80,30,30);
              // third row of boxes
              g.drawRect(50,110,30,30);
              g.drawRect(80,110,30,30);
              g.drawRect(110,110,30,30);
              if(move == "A1"){
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][0] = "X";
                   g.drawString("X",65,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][0] = "O";
                   g.drawString("O",65,65);
                   player1 = true;
                   return;
              } // end of A1
              else
              if(move == "A2"){
                   spaceA1(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][1] = "X";     
                   g.drawString("X",95,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][1] = "O";
                   g.drawString("O",95,65);
                   player1 = true;
                   return;
              } // end of A2
              else
              if(move == "A3"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][2] = "X";
                   g.drawString("X",125,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][2] = "O";
                   g.drawString("O",125,65);
                   player1 = true;
                   return;
              } // end of A3
              else
              if(move == "B1")
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][0] = "X";
                   g.drawString("X",65,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][0] = "O";
                   g.drawString("O",65,95);
                   player1 = true;
                   return;
              } // end of B1
              else
              if(move == "B2"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][1] = "X";
                   g.drawString("X",95,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][1] = "O";
                   g.drawString("O",95,95);
                   player1 = true;
                   return;
              } // end of B2
              else
              if(move == "B3"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][2] = "X";
                   g.drawString("X",125,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][2] = "O";
                   g.drawString("O",125,95);
                   player1 = true;
                   return;
              }// end of B3
         }// end of graphics
         public void mouseReleased(MouseEvent me){}
         public void mousePressed(MouseEvent me){}
         public void mouseDragged(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mouseClicked(MouseEvent me){
              int x = me.getX();
              int y = me.getY();
              if((x >=51) && (x<= 79) && (y >= 51) && (y <= 79)) //MOVE IS A1
                   move = "A1";
              else
              if((x >=81) && (x<=109) && (y >=51) && (y <= 79))  //MOVE IS A2
                   move = "A2";
              else
              if((x >=111) && (x<=139) && (y >=51) && (y <= 79))  //MOVE IS A3
                   move = "A3";
              else
              if((x >=51) && (x<= 79) && (y >= 81) && (y <= 109))  //MOVE IS B1
                   move = "B1";
              else
              if((x >=81) && (x<=109) && (y >=81) && (y <= 109))  //MOVE IS B2
                   move = "B2";
              else
              if((x >=111) && (x<=139) && (y >=81) && (y <= 109))  //MOVE IS B3
                   move = "B3";
              repaint();
    //<applet code = "game3.class" height =300 width=300> </applet>     

    writing a tic-tac-toe is harder than it sounds.. i wrote one last year in my computer science class.. i have it on my website, if you want to look at code. i wrote it in c++, but the logic is all that matters :)
    btw-last year, i wasnt too good of an OOP programmer, so the program is procedurely written. heres the url:
    http://www.angelfire.com/blues/smb
    also, to tell if a box is already taken, you can just add an if statement:   if ( gameBoard[selX][selY] == null )  //not taken, fill box:many people resort to a boolean matrix of the same idea, but with booleans that store which boxes are taken. i prefer the way above, saves code, memory, and makes it more understandable.
    hope it helps.

  • Tic Tac Toe game using Graphs

    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

  • Test out this Tic Tac Toe game please

    I know this is suppose to be a real java forum, but this is stripped down version of java, but it's still java. Before using real java I used this Judo. So can you guys download the stuff and play it a few times. Give me any suggestions or bug reports. This is v. 1.0 and there isn't a winner decider yet. Thanks and hope you have fun!
    You will need to download JUDO
    http://judo.sourceforge.net/#download
    Open JUDO and paste this code into it and run.
    void main () {
    String Intro = "Tic Tac Toe v 1.0 only funcutions under lower case letters.";
    String Start = "Execute y/n...";
    drawString(Intro, 150,50);
    drawString(Start, 150,70);
    String Go = "y";
    String go;
    go = readString();
    if(equal(go,Go)){
    setColor(blue);
    for(int loading = 0 ; loading < 460; loading++)
    int lpercent = loading;
    //printLine("Loading percent... "+lpercent/460+"%");
    fillRectangle(loading*1,250, 25,25);
    delay(0.01);
    String complete = "Loading Complete...";
    drawString(complete,0,235);
    //Ask what user would like [X or O]
    //get player name
    String PlayerName;
    String PlayerName2;
    printLine("Enter Player 1 name...");
    PlayerName = readString();
    printLine("Enter Player 2 name...");
    PlayerName2 = readString();
    //Recycle program loop here
    String execute = "y";
    String yes = "y";
    //While user would still like to run program
    while(equal(execute, yes)) {
    //decide player symbol
    String PlayerOne;
    String PlayerTwo;
    printLine("Select player 1 character...[x or o]");
    PlayerOne = readString();
    String O = "o";
    String X = "x";
    if(equal(PlayerOne, X) ) {
    PlayerTwo = O;
    else{
    PlayerTwo = X;
    //Printout inputed data
    printLine("Player 1 : ("+ PlayerOne +") " + PlayerName + " Player 2 : (" + PlayerTwo +") "+ PlayerName2);
    //Draw playing board
    String info = "Player 1 : ("+ PlayerOne +") " + PlayerName + " | Player 2 : (" + PlayerTwo +") "+ PlayerName2;
    //clearDrawing();
    for(int roundTime = 0 ; roundTime < 6; roundTime++) {
    setBackgroundColor(azure);
    drawString(info, 150,50);
    //horizontal lines
    setColor(black);
    drawLine(100,100, 400,100);
    drawLine(100,101, 400,101);
    drawLine(100,141, 400,141);
    drawLine(100,142, 400,142);
    drawLine(100,182, 400,182);
    drawLine(100,183, 400,183);
    //verticle lines
    drawLine(200,60, 200,223);
    drawLine(201,60, 201,223);
    drawLine(300,60, 300,223);
    drawLine(301,60, 301,223);
    //code boxed
    String a = "A";
    String b = "B";
    String c = "C";
    String d = "D";
    String one = "1";
    String two = "2";
    String three = "3";
    drawString(a, 100,80);
    drawString(b, 100,120);
    drawString(c, 100,160);
    drawString(d, 100,200);
    drawString(one, 150,230);
    drawString(two, 250,230);
    drawString(three, 350,230);
    //Let X go first then O (continue alternating)
    String pOne = PlayerName + "'s turn to move...";
    String pTwo = PlayerName2 + "'s turn to move...";
    if(equal(PlayerOne,X)) {
    drawString(pOne, 50,243);
    else{
    drawString(pTwo, 50,243);
    //ask user to make move here, then alternate character moves.
    String move;
    String move2;
    String A1 = "a1";
    String A2 = "a2";
    String A3 = "a3";
    String B1 = "b1";
    String B2 = "b2";
    String B3 = "b3";
    String C1 = "c1";
    String C2 = "c2";
    String C3 = "c3";
    String D1 = "d1";
    String D2 = "d2";
    String D3 = "d3";
    printLine("Please enter your character position player(X)...");
    move = readString();
    String CX = "X";
    String CO = "O";
    if(equal(move,A1)) {
    setColor(blue);
    drawString(CX, 42, 140,99);
    else{
    //continue program execution
    if(equal(move,A2)) {
    setColor(blue);
    drawString(CX, 42, 240,99);
    else{
    //continue program execution
    if(equal(move,A3)) {
    setColor(blue);
    drawString(CX, 42, 340,99);
    else{
    //continue program execution
    if(equal(move,B1)) {
    setColor(blue);
    drawString(CX, 42, 140,140);
    else{
    //continue program execution
    if(equal(move,B2)) {
    setColor(blue);
    drawString(CX, 42, 240,140);
    else{
    //continue program execution
    if(equal(move,B3)) {
    setColor(blue);
    drawString(CX, 42, 340,140);
    else{
    //continue program execution
    if(equal(move,C1)) {
    setColor(blue);
    drawString(CX, 42, 140,181);
    else{
    //continue program execution
    if(equal(move,C2)) {
    setColor(blue);
    drawString(CX, 42, 240,181);
    else{
    //continue program execution
    if(equal(move,C3)) {
    setColor(blue);
    drawString(CX, 42, 340,181);
    else{
    //continue program execution
    if(equal(move,D1)) {
    setColor(blue);
    drawString(CX, 42, 140,222);
    else{
    //continue program execution
    if(equal(move,D2)) {
    setColor(blue);
    drawString(CX, 42, 240,222);
    else{
    //continue program execution
    if(equal(move,D3)) {
    setColor(blue);
    drawString(CX, 42, 340,222);
    else{
    //continue program execution
    //clearDrawing();
    if(equal(PlayerOne,X)) {
    drawString(pTwo, 50,243);
    else{
    drawString(pOne, 50,243);
    //O 's movement here
    printLine("Please enter your character position player(O)...");
    move2 = readString();
    if(equal(move2,A1)) {
    setColor(red);
    drawString(CO, 42, 140,99);
    else{
    //continue program execution
    if(equal(move2,A2)) {
    setColor(red);
    drawString(CO, 42, 240,99);
    else{
    //continue program execution
    if(equal(move2,A3)) {
    setColor(red);
    drawString(CO, 42, 340,99);
    else{
    //continue program execution
    if(equal(move2,B1)) {
    setColor(red);
    drawString(CO, 42, 140,140);
    else{
    //continue program execution
    if(equal(move2,B2)) {
    setColor(red);
    drawString(CO, 42, 240,140);
    else{
    //continue program execution
    if(equal(move2,B3)) {
    setColor(red);
    drawString(CO, 42, 340,140);
    else{
    //continue program execution
    if(equal(move2,C1)) {
    setColor(red);
    drawString(CO, 42, 140,181);
    else{
    //continue program execution
    if(equal(move2,C2)) {
    setColor(red);
    drawString(CO, 42, 240,181);
    else{
    //continue program execution
    if(equal(move2,C3)) {
    setColor(red);
    drawString(CO, 42, 340,181);
    else{
    //continue program execution
    if(equal(move2,D1)) {
    setColor(red);
    drawString(CO, 42, 140,222);
    else{
    //continue program execution
    if(equal(move2,D2)) {
    setColor(red);
    drawString(CO, 42, 240,222);
    else{
    //continue program execution
    if(equal(move2,D3)) {
    setColor(red);
    drawString(CO, 42, 340,222);
    else{
    //continue program execution
    /*setBackgroundColor(azure);
    drawString(info, 150,50);
    //horizontal lines
    setColor(black);
    drawLine(100,100, 400,100);
    drawLine(100,101, 400,101);
    drawLine(100,141, 400,141);
    drawLine(100,142, 400,142);
    drawLine(100,182, 400,182);
    drawLine(100,183, 400,183);
    //verticle lines
    drawLine(200,60, 200,223);
    drawLine(201,60, 201,223);
    drawLine(300,60, 300,223);
    drawLine(301,60, 301,223);
    //code boxed
    drawString(a, 100,80);
    drawString(b, 100,120);
    drawString(c, 100,160);
    drawString(d, 100,200);
    drawString(one, 150,230);
    drawString(two, 250,230);
    */ drawString(three, 350,230);
    printLine("would you like to execute program further? Y/N");
    execute = readString();
    else{
    clearDrawing();
    String Fail = "User declined program execution...";
    drawString(Fail, 150,60);

    please format the code..
    RK

  • Help with Tic Tac Toe game.

    I have finished my entire game excpet for who wins. Anyone have some insight on how to do this?

    private boolean isRow(char arr[][],char s)
            for (int i=0;i<3;i++)
                if (arr[0]==arr[i][1] && arr[i][1]==arr[i][2])
    if (arr[i][0]==s)
    return true;
    if the condition if (arr[0]==arr[i][1] && arr[i][1]==arr[i][2]) was false so return true; won't work, and so the method is left without a return value.
    you can solve the problem by modifying this code to this:
    private boolean isRow(char arr[][],char s)
            for (int i=0;i<3;i++)
                if (arr[0]==arr[i][1] && arr[i][1]==arr[i][2])
    if (arr[i][0]==s)
    return true;
    return false;

  • Tic Tac Toe game

    Hit there!!
    Does anyone know where can I find exaples of applications whith that game?
    I've seen them somewhere that I cannot remember.
    Thanks in advance
    Maddy

    Hi
    I wrote it a long time ago, but it will give you some ideas.
    import java.awt.*;
    import java.awt.event.*;
    import java.math.*;
    public class TicTac extends Frame
         char board[][] = new char[3][3];
         int c          = 0;
         int p          = 0;
             Button bx[]  = new Button[10];
         Font f1      = new Font("System " , 1, 28);
         int t        = 0;
         boolean endOfGame;    
         MenuBar mb   = new MenuBar();
             Menu mm      = new Menu("Option");
         MenuItem mi  = new MenuItem("New Game");
    public TicTac() 
         super("  TicTacTo");   
         setLayout(null);
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}
         setBounds(60,60,159,179);
         for (int i = 0; i < 9; i++)
              bx[i] = new Button("");
              bx.setFont(f1);
              bx[i].setActionCommand(""+i);
              bx[i].setSize(50,50);
         bx[i].setForeground(Color.black);
         int x = (i - (i / 3 * 3)) * 51 + 3;
              int y = (i / 3 * 51) + 42;
         bx[i].setLocation(x,y);
    bx[i].addActionListener(new MybAction());
         add(bx[i]);
         mi.addActionListener(new MymnAction());
         mb.add(mm);
         mi.setActionCommand("ng");
         mm.add(mi);
         setMenuBar(mb);
         setVisible(true);
         requestFocus();
    public void newboard()
         t = 0;
         endOfGame = false;
         for (int i = 0; i < 3 ; i=i+1)
              for (int j = 0; j < 3; j++)
                   board[i][j] = '-';
                   bx[i*3+j].setLabel(".");
                   bx[i*3+j].setForeground(Color.black);
                   bx[i*3+j].setEnabled(true);
    public void winboard(int i, int j)
         bx[i*3+j].setForeground(Color.red);
    public void markboard(int i, int j, char tav)
         board[i][j] = tav;
         bx[i*3+ j].setLabel(""+tav);
         t = t + 1;
         if (win(3,tav,tav) == true)
         endOfGame = true;
              System.out.println("" + tav + " win");
         if (t == 9) endOfGame = true;
    public void printboard()
         for (int i = 0; i < 3 ; i=i+1)
              System.out.println(" " + board[i][0] +
         " " + board[i][1] +
                        " " + board[i][2]);
         System.out.println(" ");
    public void play(char tav)
         boolean b = false;
         int i = 0;
         int j = 0;
         if (win(2,tav,tav) == true) return;
         if (tav == 'X') if (win(2,'O',tav) == true) return;
         if (tav == 'O') if (win(2,'X',tav) == true) return;
         if (win(1,tav,tav) == true) return;
         while (b == false)
         i = (int)(Math.random() * 3);
              j = (int)(Math.random() * 3);
              if (board[i][j] == '-') b = true;
         markboard(i,j,tav);
    public void playP(char tav, int mp)
         int i = mp / 3;
         int j = (mp - (mp / 3 * 3));
         if (board[i][j] == '-')     markboard(i,j,tav);
    public boolean win(int cc, char tav,char tavp)
         int i;
         int j;
    c = 0;
         for (i = 0; i < 3 ; i=i+1)
              for (j = 0; j < 3; j++)     winc(j, board[i][j], tav);
              if (winr(cc,i,p,tavp) == true)
              if (cc == 3) for (j = 0; j < 3; j++) winboard(i,j);
                   return true;
         for (j = 0; j < 3 ; j=j+1)
              for (i = 0; i < 3; i++)     winc(i, board[i][j], tav);
              if (winr(cc,p,j,tavp) == true)
                   if (cc == 3) for (i = 0; i < 3; i++) winboard(i,j);
                   return true;
         for (i = 0; i < 3 ; i=i+1) winc(i, board[i][i], tav);
         if (winr(cc,p,p,tavp) == true)
              if (cc == 3) for (i = 0; i < 3; i++) winboard(i,i);
              return true;
         for (j = 0; j < 3 ; j=j+1) winc(j, board[2 - j][j], tav);
         if (winr(cc,2 - p,p,tavp) == true)
              if (cc == 3) for (j = 0; j < 3; j++) winboard(2 - j,j);
              return true;
         return false;
    public void winc(int pi,char tav,char tavc)
    if (tav == tavc) c = c + 1;
              else if (tav != '-') c = 99;
                   else p = pi;
    public boolean winr(int cc, int i, int j, char tav)
         if (cc == 3) if (c == 3) return true;
         if (c == cc)
              markboard(i,j,tav);
         return true;
         c = 0;
         return false;
    class MybAction implements ActionListener
    public void actionPerformed(ActionEvent be)
         String s = be.getActionCommand();
         int h = new Integer(s).intValue();
         if (endOfGame == false)
         playP('X',h);
              if (endOfGame == false) play('O');
         requestFocus();
    class MymnAction implements ActionListener
    public void actionPerformed(ActionEvent be)
         String s = mi.getActionCommand();
         if (s == "ng") newboard();
    public static void main (String[] args)
    TicTac gm = new TicTac();
         gm.newboard();

  • 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 help 

    Some 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 .

  • Tic-tac-toe multithreaded server game

    i have written the code for tic-tac-toe game partially.i am stuck at writing the code for "who is the winner"? and adding a button to start the new game ?please help me out to write the remaining?
    iam unable to attach the code now;
    Message was edited by:
    vamshijupally

    i have written the code for tic-tac-toe game
    partially.i am stuck at writing the code for "who is
    the winner"? and adding a button to start the new
    game ?please help me out to write the remaining?That question is almost impossible to answer because you didn't provide two vital pieces of information.
    1) What specific problems you're having.
    2) Relevant code.
    iam unable to attach the code now;So, you call the doctor on the phone, say, "I'm not feeling well. Please make me better. I can't come to your office or tell you anything about what's wrong with me now."

  • 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

  • Tic Tac Toe Problem

    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

  • Networked Tic Tac Toe

    I need help with making my Tic Tac Toe game networked. Is there an easy
    way to pass two ints over through a network. Heres my Code so far. I
    already have a working Tic Tac Toe. Just wanted to add Network
    Capability.
    Heres my code:
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Vector;
    import javax.swing.*;
    * This class functions as the controller for my Tic Tac Toe game.
    * @author Zosden
    * Date Due: 2/22/2008
    * @version 1.0 (22 February 2008)
    * Input: playersFile.txt is a text file to hold players information.
    * String playerXName is a temp String for input of player x's name.
    * String playerOName is a temp String for input of player O's name.
    * Output: playersFile.txt
    public class GameController
        //  Properties   //
        private GameView myView;
        private GameModel myModel;
        private Player myPlayerX;
        private Player myPlayerO;
        private File playersFile;
        private FileReader fileReader;
        private BufferedReader bufReader;
        private FileOutputStream outFileStream;
        private PrintStream p;
        private boolean myPlayerXNewPlayer = true;
        private boolean myPlayerONewPlayer = true;
        private int myPlayerXPosition;
        private int myPlayerOPosition;
        private Vector myPlayerVector = new Vector(10);
        private ServerSocket serverSocket;
        private Socket clientSocket;
        private PrintWriter out;
        private String inputLine;
        private String outputLine;
        private boolean isClient;
        private BufferedReader in;
        private String fromServer;
         * Default controller constructor.
        public GameController(Player aPlayerX, Player aPlayerO, boolean isClient)
            myPlayerX = aPlayerX;
            myPlayerO = aPlayerO;
            this.isClient = isClient;
            this.readPlayers();
            myModel = new GameModel(this);
            myView = new GameView(this);
            if(isClient)
                this.setUpClient();
                this.waitForTurn(-1 , -1);
            else
                this.setUpServer();
        private void waitForTurn(int aRow, int aCol)
            if(isClient)
                if(!(aRow == -1 || aCol == -1))
                    out.println(aRow + " " + aCol + " ");
                    System.out.println("Made Move");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    if(fromServer != null)
                        int row = fromServer.indexOf(" ");
                        int col = fromServer.indexOf(" ");
                        System.out.println(row + " " + col);
                        myModel.move(row, col);
                        break;
            else
                out.println(aRow + " " + aCol + " ");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    int row = fromServer.indexOf(" ");
                    int col = fromServer.indexOf(" ");
                    System.out.println(row + " " + col);
                    myModel.move(row, col);
                    break;
        private void setUpServer()
            serverSocket = null;
            try
                serverSocket = new ServerSocket(4444);
            catch (IOException e)
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            clientSocket = null;
            try
                clientSocket = serverSocket.accept();
            catch (IOException e)
                System.err.println("Accept failed.");
                System.exit(1);
            try
                out = new PrintWriter(clientSocket.getOutputStream(), true);
            catch (IOException e)
                e.printStackTrace();
        private void setUpClient()
            try
                clientSocket = new Socket(myPlayerO.getName(), 4444);
                out = new PrintWriter(clientSocket.getOutputStream(), true);   
            catch (UnknownHostException e)
                System.err.println("Don't know about host.");
                System.exit(1);
            catch (IOException e)
                System.err.println("Couldn't get I/O for the connection to.");
                System.exit(1);
         * Tells the model that something has been selected then
         * passes the row and col of the event.
         * pre:  a valid view, model and controller have been designated
         * post: sends aRow and aCol to move in the model class.
         * @param aRow
         * @param aCol
        public void choiceMade(Integer aRow, Integer aCol)
            myModel.move(aRow, aCol);
            this.waitForTurn(aRow, aCol);
        public void changePlayersName()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        public void changeMusic()
            myView.displayDialog();
        public void pauseMusic()
            myModel.pauseMusic();  
        public void startMusic()
            myModel.startMusic();  
        public void quitGame()
            this.writePlayers();
            System.exit(0);
         * Increments the number of wins a certain player has,
         * which is determined by the argument.
         * @param aPlayerType
        public void changeImage(int aRow, int aCol, int aPlayerType)
            myView.setMyImagePieces(aRow, aCol, aPlayerType);
        public void updateScore()
            myView.setWins();
        public void changeMessage(String aString)
            myView.changeMyMessage(aString);
         * This method writes the players name and wins into a text file in
         * order to save that information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will rewrite the entire text file
         * with all the players names.
         * </pre>
        public void writePlayers()
            if(!myPlayerXNewPlayer)
                myPlayerVector.remove(myPlayerXPosition + 1);
                myPlayerVector.insertElementAt(getPlayerXWins(),
                        myPlayerXPosition + 1);
            else
                myPlayerVector.add(getPlayerXName());
                myPlayerVector.add(getPlayerXWins());
            if(!myPlayerONewPlayer)
                myPlayerVector.remove(myPlayerOPosition + 1);
                myPlayerVector.insertElementAt(getPlayerOWins(),
                        myPlayerOPosition + 1);
            else
                myPlayerVector.add(getPlayerOName());
                myPlayerVector.add(getPlayerOWins());
                try
                    outFileStream = new FileOutputStream(playersFile);
                    p = new PrintStream(outFileStream);
                catch (IOException e)
                    e.printStackTrace();
            for(int i = 0; i < myPlayerVector.size(); i++)
                p.println(myPlayerVector.elementAt(i));
            p.close();
         * This method reads the players name and wins in a text file in
         * order to find out their information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will read the entire text file
         * with all the players names.
         * </pre>
        public void readPlayers()
            String tempName = null;
            int tempPosition = 0;
            int tempWins = 0;
            playersFile = new File("playersText.txt");
            try
                fileReader = new FileReader(playersFile);
                bufReader = new BufferedReader(fileReader);
                catch (FileNotFoundException e)
                    e.printStackTrace();
            while(true)
                tempName = null;
                try
                    tempName = bufReader.readLine();
                    if(tempName == null)
                        break;
                    myPlayerVector.insertElementAt(tempName, tempPosition);
                    if(getPlayerXName().equalsIgnoreCase(tempName))
                        myPlayerXPosition = tempPosition;
                    if(getPlayerOName().equalsIgnoreCase(tempName))
                        myPlayerOPosition = tempPosition;
                    tempPosition++;
                    try
                        tempWins = Integer.parseInt(bufReader.readLine());
                    catch(NumberFormatException e)
                        e.printStackTrace();
                    myPlayerVector.insertElementAt(tempWins, tempPosition);
                    tempPosition++;
                catch (IOException e)
                    e.printStackTrace();
                if(getPlayerXName().equalsIgnoreCase(tempName))
                    setPlayerXWins(tempWins);
                    myPlayerXNewPlayer = false;
                if(getPlayerOName().equalsIgnoreCase(tempName))
                    setPlayerOWins(tempWins);
                    myPlayerONewPlayer = false;
        public void incrementWin(int aPlayerType)
            if(aPlayerType == getPlayerOType())
                myPlayerO.incrementWins();
            if(aPlayerType == getPlayerXType())
                myPlayerX.incrementWins();
            updateScore();
        public void changePlayersNames()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        //   Accessor Methods     //
        public int getNumDraws()
            return myModel.getNumberDraws();
        public String getMessages()
            return myModel.getMessages();
        public void setMusic(Integer aSong)
            myModel.setMusic(aSong);
        public String getPlayerXName()
            return myPlayerX.getName();
        public String getPlayerOName()
            return myPlayerO.getName();
        public int getPlayerXWins()
            return myPlayerX.getNumWins();
        public int getPlayerOWins()
            return myPlayerO.getNumWins();
        public int getPlayerXType()
            return myPlayerX.getType();
        public int getPlayerOType()
            return myPlayerO.getType();
        public int getNoPlayerType()
            return myPlayerO.NO_PLAYER;
        private void setPlayerXWins(int aNumWins)
            myPlayerX.setNumWins(aNumWins);
        private void setPlayerOWins(int aNumWins)
            myPlayerO.setNumWins(aNumWins);
        private void setPlayerXName(String aName)
            myPlayerX.setName(aName);
        private void setPlayerOName(String aName)
            myPlayerO.setName(aName);
    }</div>{noformat}
    </div>

    I think I figured it out. I still have some work to do, but that part is easy. Heres the file in case anyone is interested.[TTT.Zip|http://www.mediafire.com/?wii1fn5wqom]
    If anyone knows of a better way to do this same thing please let me know

  • Tic Tac Toe with AI

    Well I'm getting ready for my second semester of Java programing and I figured I would try and get back in the swing (no pun intended) of things by creating a simple tic tac toe game. I was able to make a two player game with in a matter of hours so I figured I would try and make a one player game with AI and thats where im having some issues. Here is my code for two person tic tac toe
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToeV2 implements ActionListener {
         /*Instance Variables*/
         private int[][] winCombinations = new int[][] {
                   {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, //horizontal wins
                   {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, //virticle wins
                   {1, 5, 9}, {3, 5, 7}                //diagonal wins
         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 TicTacToeV2(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i=1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Calculate whose turn it is*/
              if(count % 2 == 0){
                   letter = "O";
              } else {
                   letter = "X";
              /*Write the letter to the button and deactivate it*/
              for(int i=1; i<=9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText(letter);
                        buttons[i].setEnabled(false);
              /*Determine who won*/
              for(int i=0; i<=7; i++){
                   if( buttons[winCombinations[i][0]].getText() == buttons[winCombinations[i][1]].getText() &&
                        buttons[winCombinations[i][1]].getText() == buttons[winCombinations[i][2]].getText() &&
                        buttons[winCombinations[i][0]].getText() != ""){
                        win = true;
              /*Show a dialog when game is over*/
              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 tie!");
                   System.exit(0);
         public static void main(String[] args){
              TicTacToeV2 starter = new TicTacToeV2();
    Now for my program with AI I'm essentially using the same code and just for clarity I removed all the code that determines who won (as it isnt needed to get the AI to work) This is what I have so far
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV3 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         public TicTacToeV3(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
         public static void main(String[] args){
              new TicTacToeV3();
    It kind of works because each time i choose a box the "computer" also chooses one, but since it is so random the chances the computer wins is very limited. I then tried to do something like this in the AI() method and it seems to be on the right track but once one of the if's are satisfied the all the AI logic stops
         public void AI(){
              //horizontal AI defencive code
              if(buttons[1].getText().equals(buttons[2].getText()) && buttons[1].getText() != ""){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if(buttons[2].getText().equals(buttons[3].getText()) && buttons[2].getText() != ""){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);
              } else if(buttons[4].getText().equals(buttons[5].getText()) && buttons[4].getText() != ""){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              } else if(buttons[5].getText().equals(buttons[6].getText()) && buttons[5].getText() != ""){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);
              } else if(buttons[7].getText().equals(buttons[8].getText()) && buttons[7].getText() != ""){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);
              } else if(buttons[8].getText().equals(buttons[9].getText()) && buttons[8].getText() != ""){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);
              } else {
                   Random x = new Random();
                   int y = 1 + x.nextInt(9);
                   if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                        AI();
                   } else {
                        buttons[y].setText("O");
                        buttons[y].setEnabled(false);
         }And basically what that does is it checks if I have two X's in a row horizontally, If I do it will place an O in the box preventing me from getting three in a row (only in horizontal rows). Of course I would iterate this over and over for all possible combinations of offensive moves and defensive moves and probably do it using a for loop but this is just some scratch code I threw together to show you my thoughts. And again my problem is once one of the conditions are satisfied it never checks the conditions again and I'm not sure why that is...
    So I'm looking for some ideas and/or some pseudo code to help me out a little.
    Thanks

    Well I did this and its a step closer to working but there is another bug and all this logic is hurting my head. Again lets say my grid is numbered like this
    1 | 2 | 3
    4 | 5 | 6
    7 | 8 | 9
    If I go 1, the computer will randomly pick a square thats not set. Lets say the computer picks 4. Now I pick 5 and the computer picks 9 because I would earn 3 in a row diagonally. Then I pick 2 and I can now win three in a row 2-5-8 or 1-2-3. The computer picks 3 because that logic is earlier in the code. BUT when I press 8 to to take the win, but the computer cheats and labels my button thats supposed to be an X as an O, so it should look like this:
    X | X | O
    O | X | 6
    7 | X | O
    but it does this
    X | X | O
    O | X | 6
    7 | O | O
    Here is the AI logic part (its mostly repetitive)
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
                else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         }Here is the entire code if you want to try it and compile it to see what im talking about in real time:
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV4 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         private boolean went = false;
         public TicTacToeV4(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
              else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         public static void main(String[] args){
              new TicTacToeV4();
    What am I doing wrong?

  • Tic-Tac-Toe [ What would you do different? ]

    I was bored so I made a simple 2-player tic-tac-toe game. I was just wondering if there was any room for improvement [other than the lack of comments]
    package tictactoe;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class TicTacToe {
         private char[] board = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9'};
         private int count = 0;
         private int location;
         private int[][] winCombinations = new int[][] {
                   {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
                   {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
                   {0, 4, 8}, {2, 4, 6}                //diagonal wins
         private InputStreamReader isr = new InputStreamReader(System.in);
         private BufferedReader br = new BufferedReader(isr);
         private boolean win = false;
         public TicTacToe(){
              while(checkWin() != true && count < 9){
                   displayBoard();
                   getInput();
                   setLocation();
                   count++;
              endGame();     
         public void displayBoard(){
              System.out.println( board[0] + " | " + board[1] + " | " + board[2]);
              System.out.println("---------");
              System.out.println( board[3] + " | " + board[4] + " | " + board[5]);
              System.out.println("---------");
              System.out.println( board[6] + " | " + board[7] + " | " + board[8]);
              System.out.println("\n");
         public void getInput(){
              System.out.print("Enter the location on the board: ");
              try {
                   //Convert the string to an integer
                   location = Integer.parseInt(br.readLine());
              } catch(Exception Error) {
                   System.out.print("You have entered an invalid number. You must enter a number between 1 and 9 inclusive. Try again.\n\n");
                   getInput();
              if(location < 1 || location > 9){
                   System.out.println("You must enter a number between 1 and 9 inclusive. Try again.\n\n");
                   getInput();
         public void setLocation(){
              if(count % 2 == 0)
                   board[location-1] = 'X';
              else
                   board[location-1] = 'O';
         public boolean checkWin(){
              for(int i=0; i<=7; i++){
                   if( board[winCombinations[0]] == board[winCombinations[i][1]] &&
                        board[winCombinations[i][1]] == board[winCombinations[i][2]]){
                        win = true;
              return win;
         public void endGame(){
              if(checkWin() != true && count == 9){
                   displayBoard();
                   System.out.println("The game is tie!");
              } else {
                   displayBoard();
                   System.out.println("\n\n" + board[location-1] + " WINS!");
              System.exit(0);
         public static void main(String args[]){
              new TicTacToe();
    Thanks.

    1. disassociate any program logic from UI so that it
    can easily be ported to a GUI such as swing>
    As for 1, are you talking about the getInput method?
    Thats the only method that associates logic with UI
    as far as I'm concerned and when it is ported into a
    GUI, the user wont have the ability to select a
    square out of range so that logic wont even exist. Is
    there any other?What I mean is can you take the core logic portion of your code and easily plug it directly to your GUI code or non-GUI code or even changed different GUI code. This can occur if the logic portion is so well encapsulated that it doesn't depend at all on the user interface. another way to put it is the core functionality of the program should not reside in the GUI class (or classes).
    Admittedly w/ 2-D tictactoe, this may not be quite so relevant.
    addendum: check out Model-view-controller on wikipedia.
    Message was edited by:
    petes1234

Maybe you are looking for

  • Open DNS and shortcuts?

    I'm not sure what's going on, but Safari 4 is not exhibiting it's usual behavior when it comes to shortcuts. Or at least I think it's shortcuts. When I used to type in "website" it would automatically go to "website.com" but now it takes me to the Op

  • Unable to create a TFS Report in Excel (via SSAS)

    Dear all, I hope this is the correct forum to ask my question about TFS and SSAS. We have a TFS2012 environment in a domain. We have installed and configured the reporting and analysis services (SQL Server 2012). Now I am trying to create a report in

  • IPod Nano 6g not syncing - Apple Mobile Device Support can't install

    i recently got iTunes working again on my computer. my grandfather wanted me to sync his old iPod Nano, so i did that and it worked fine. i then tried to sync my own iPod Nano 6g, and it gave me the error: "An iPod has been detected, but it could not

  • Windows 8 single language upgradation

    Dear All, I need to upgrade Windows 8 single language to 8.1 is there any option i can upgrade without downloading for each laptop, Because we have 10 laptops of the same where as our internet band width is low. Regards, Srinivas [email protected]

  • Safari keeps setting my cookies preference to never

    This is really odd (and recent) but occasionally I'm finding that my Cookies pref has spontaneously changed from "only from originating sites" to "never". Setting it back to the setting I want works for a while but then I'll notice that some site doe