Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

jtalerico

macrumors 6502
Nov 23, 2005
358
0
I realize this code could be sketchy... But you could modify it to work for you. I have it currently working and checking the top row to see if they are all the same...

Code:
  static int[][] MoveHistory = new int[3][3];
 
 
  static  class MoveHandler implements ActionListener     //######     
  {
    public void actionPerformed(ActionEvent event)
   
    {
      String whichButton;                       
      whichButton = event.getActionCommand(); 
      
      if (whichButton.equals("1"))                                                                                 
      { one.setText(player); 
       if (player.equals ("x")) MoveHistory[0][0] = 1;
                           else MoveHistory[0][0] = 2;
      }
      this.check();
      if (whichButton.equals("2")) 
      { two.setText(player); 
        if (player.equals ("x")) MoveHistory[0][1] = 1;
                            else MoveHistory[0][1] = 2;
      }
       this.check();                     
       if (whichButton.equals("3"))                                                                                
      { three.setText(player); 
       if (player.equals ("x")) MoveHistory[0][2] = 1;
                           else MoveHistory[0][2] = 2;
      }
      this.check();
       if (whichButton.equals("4"))                                                                                
      { four.setText(player); 
       if (player.equals ("x")) MoveHistory[1][0] = 1;
                           else MoveHistory[1][0] = 2;
      }
      this.check();
       if (whichButton.equals("5"))                                                                                
      { five.setText(player); 
       if (player.equals ("x")) MoveHistory[1][1] = 1;
                           else MoveHistory[1][1] = 2;
      }
      this.check();
       if (whichButton.equals("6"))                                                                                
      { six.setText(player); 
       if (player.equals ("x")) MoveHistory[1][2] = 1;
                           else MoveHistory[1][2] = 2;
      }
      this.check();
       if (whichButton.equals("7"))                                                                                
      { seven.setText(player); 
       if (player.equals ("x")) MoveHistory[2][0] = 1;
                           else MoveHistory[2][0] = 2;
      }
      this.check();
       if (whichButton.equals("8"))                                                                                
      { eight.setText(player); 
       if (player.equals ("x")) MoveHistory[2][1] = 1;
                           else MoveHistory[2][1] = 2;
      }
      this.check();
       if (whichButton.equals("9"))                                                                                
      { nine.setText(player); 
       if (player.equals ("x")) MoveHistory[2][2] = 1;
                           else MoveHistory[2][2] = 2;
      }
      this.check();
                                                                               
      nine.setText(player);
      
      if (whichButton.equals("x"))                                                                                 
      { JOptionPane.showMessageDialog( null, "click again"); // ****
      }
      if (whichButton.equals("o"))                                                                                 
      { JOptionPane.showMessageDialog( null, "click again");
      }
               
      
     
     
     if (player == "o" )
      player = "x";
      else player = "o";
     int x=0;
     for (int a=0;a<3;a++)
     System.out.print(MoveHistory[a][x]);
     System.out.println();
     x++;
    
    }  
  public void check(){
    for(int i=0; i<3; i++){
        if(MoveHistory[i][0]==MoveHistory[i][1] && MoveHistory[i][1]==MoveHistory[i][2]){
            if(MoveHistory[i][0] == 1){
                JOptionPane.showMessageDialog(null, "X Wins");
                break;
            }
            if(MoveHistory[i][0] == 2){
                JOptionPane.showMessageDialog(null, "O Wins");
                break;
            }
        }
    }
  }
}
 

jtalerico

macrumors 6502
Nov 23, 2005
358
0
the_insider said:
many thanks jtalerico. im working on it now

Sure thing. I might also suggest that you add a JMenuBar that has a newGame() method attached to it, and a exit() method.
 

MacMan93

macrumors member
May 10, 2006
58
0
This might be a little complex for your needs but look in:
yuor HD/Developer/Examples/Java/Applets/TicTacToe/

It uses graphical X and O's but I guess it should help you out a little. :)
 

the_insider

macrumors regular
Original poster
Apr 20, 2005
177
0
USA / UK
I managed to setup the check for rows, columns, and diagonals. I was wondering if anyone wanted to give me a few pointers, of what i could continue to add to this program.. maybe some simple GUI, or some A.I.. any ideas?
Code:
import java.awt.*;                           
import java.awt.event.*;                     
import javax.swing.*; 
import javax.swing.JOptionPane;                       

public class TicTacToe
{

	                            
  static JFrame calcFrame;                   
  static Container calcPane;                                                             
  static MoveHandler operation;             
  static ClearHandler clearOperation;         
  static JButton one;
  static JButton two;
  static JButton three;
  static JButton four;
  static JButton five;
  static JButton six;
  static JButton seven;
  static JButton eight;
  static JButton nine;                     
  static String player = "x";
  static int[][] MoveHistory = new int[3][3];
 
 
  static  class MoveHandler implements ActionListener     //######     
  {
    public void actionPerformed(ActionEvent event)
   
 {
      String whichButton;                       
      whichButton = event.getActionCommand(); 
      
      if (whichButton.equals("1"))                                                                                 
      { one.setText(player); 
       if (player.equals ("x")) MoveHistory[0][0] = 1;
                           else MoveHistory[0][0] = 2;
      }
      this.check();
      if (whichButton.equals("2")) 
      { two.setText(player); 
        if (player.equals ("x")) MoveHistory[0][1] = 1;
                            else MoveHistory[0][1] = 2;
      }
       this.check();                     
       if (whichButton.equals("3"))                                                                                
      { three.setText(player); 
       if (player.equals ("x")) MoveHistory[0][2] = 1;
                           else MoveHistory[0][2] = 2;
      }
      this.check();
       if (whichButton.equals("4"))                                                                                
      { four.setText(player); 
       if (player.equals ("x")) MoveHistory[1][0] = 1;
                           else MoveHistory[1][0] = 2;
      }
      this.check();
       if (whichButton.equals("5"))                                                                                
      { five.setText(player); 
       if (player.equals ("x")) MoveHistory[1][1] = 1;
                           else MoveHistory[1][1] = 2;
      }
      this.check();
       if (whichButton.equals("6"))                                                                                
      { six.setText(player); 
       if (player.equals ("x")) MoveHistory[1][2] = 1;
                           else MoveHistory[1][2] = 2;
      }
      this.check();
       if (whichButton.equals("7"))                                                                                
      { seven.setText(player); 
       if (player.equals ("x")) MoveHistory[2][0] = 1;
                           else MoveHistory[2][0] = 2;
      }
      this.check();
       if (whichButton.equals("8"))                                                                                
      { eight.setText(player); 
       if (player.equals ("x")) MoveHistory[2][1] = 1;
                           else MoveHistory[2][1] = 2;
      }
      this.check();
       if (whichButton.equals("9"))                                                                                
      { nine.setText(player); 
       if (player.equals ("x")) MoveHistory[2][2] = 1;
                           else MoveHistory[2][2] = 2;
      }
      this.check();
                                                                               
      nine.setText(player);
      
      if (whichButton.equals("x"))                                                                                 
      { JOptionPane.showMessageDialog( null, "click again"); // ****
      }
      if (whichButton.equals("o"))                                                                                 
      { JOptionPane.showMessageDialog( null, "click again");
      }
               
      
     
     
     if (player == "o" )
      player = "x";
      else player = "o";
     int x=0;
     for (int a=0;a<3;a++)
     System.out.print(MoveHistory[a][x]);
     System.out.println();
     x++;
    
    }  
  public void check(){
    for(int i=0; i<3; i++){
        if(MoveHistory[i][0]==MoveHistory[i][1] && MoveHistory[i][1]==MoveHistory[i][2]){
            if(MoveHistory[i][0] == 1){
                JOptionPane.showMessageDialog(null, "X Wins");
                break;
            }
            if(MoveHistory[i][0] == 2){
                JOptionPane.showMessageDialog(null, "O Wins");
                break;
            }
        }
    }
  }
}
  
  static class ClearHandler implements ActionListener 
  {
    public void actionPerformed(ActionEvent event)
   
    {
                           
                  
     }
  }

				    

				    
  public static void main(String[] args)
  {
    operation = new MoveHandler();        
    clearOperation = new ClearHandler();     
                             
   one = new JButton("1");
   two = new JButton("2");
   three = new JButton("3");
   four = new JButton("4");
   five = new JButton("5");
   six = new JButton("6");
   seven = new JButton("7");
   eight = new JButton("8");
   nine = new JButton("9");
   
   one.addActionListener(operation);
   two.addActionListener(operation);
   three.addActionListener(operation);
   four.addActionListener(operation);
   five.addActionListener(operation);
   six.addActionListener(operation);
   seven.addActionListener(operation);
   eight.addActionListener(operation);
   nine.addActionListener(operation);
    
    calcFrame = new JFrame();
    calcFrame.setSize(300,300);
    calcFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    calcPane = calcFrame.getContentPane();
    calcPane.setLayout (new GridLayout (3,3));
    calcPane.add(one);
    calcPane.add(two);
    calcPane.add(three);
    calcPane.add(four);
    calcPane.add(five);
    calcPane.add(six);
    calcPane.add(seven);
    calcPane.add(eight);
    calcPane.add(nine);
    calcFrame.setVisible(true);
    
  }
  
  }
 

4409723

Suspended
Jun 22, 2001
2,221
0
Well it would be nice if it actually worked and didn't place a piece in the bottom right every time...

1. Make your check method a boolean so you can set a while loop to allow the game to play while there isn't a winner.

2. Your piece playing method was massive so I improved the algorithm. You want to take a number, one to nine, and then get two coordinates out of it. See attachment for chart.

For reference % is modulus (remainder) in java.


Code:
 import java.awt.*;                           
import java.awt.event.*;                     
import javax.swing.*; 
import javax.swing.JOptionPane;                       

public class TicTacToe {
    static JFrame calcFrame;                   
    static Container calcPane;                                                             
    static MoveHandler operation;                
    static JButton one;
    static JButton two;
    static JButton three;
    static JButton four;
    static JButton five;
    static JButton six;
    static JButton seven;
    static JButton eight;
    static JButton nine;                     
    static String player = "x";
    static int[][] MoveHistory = new int[3][3];
    static JButton[] buttonarray;
 
 public static void main(String[] args) {
    operation = new MoveHandler();            
                            
    buttonarray = new JButton[9];   
   one = new JButton("1");
   two = new JButton("2");
   three = new JButton("3");
   four = new JButton("4");
   five = new JButton("5");
   six = new JButton("6");
   seven = new JButton("7");
   eight = new JButton("8");
   nine = new JButton("9");
   
   one.addActionListener(operation);
   two.addActionListener(operation);
   three.addActionListener(operation);
   four.addActionListener(operation);
   five.addActionListener(operation);
   six.addActionListener(operation);
   seven.addActionListener(operation);
   eight.addActionListener(operation);
   nine.addActionListener(operation);
   
    buttonarray[0] = one;
    buttonarray[1] = two;
    buttonarray[2] = three;
    buttonarray[3] = four;
    buttonarray[4] = five;
    buttonarray[5] = six;
    buttonarray[6] = seven;
    buttonarray[7] = eight;
    buttonarray[8] = nine;
        
    calcFrame = new JFrame();
    calcFrame.setSize(300,300);
    calcFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    calcPane = calcFrame.getContentPane();
    calcPane.setLayout (new GridLayout (3,3));
    calcPane.add(one);
    calcPane.add(two);
    calcPane.add(three);
    calcPane.add(four);
    calcPane.add(five);
    calcPane.add(six);
    calcPane.add(seven);
    calcPane.add(eight);
    calcPane.add(nine);
    calcFrame.setVisible(true);
    }
    
    
 
  static  class MoveHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      String whichButton;                       
      whichButton = event.getActionCommand(); 
      int pos = Integer.parseInt(whichButton)-1;
      int x = pos/3;
      int y = pos%3;
      System.out.println(x + ", " + y);     
      if (player.equals ("x")) {
        MoveHistory[x][y] = 1;
        buttonarray[pos].setText("x");
        player = "o";
      } else {
        MoveHistory[x][y] = 2;
        buttonarray[pos].setText("o");
        player = "x";
      }
      this.check();
    }
      
      
    public void check(){
        for(int i=0; i<3; i++){
            if(MoveHistory[i][0]==MoveHistory[i][1] && MoveHistory[i][1]==MoveHistory[i][2]){
                if(MoveHistory[i][0] == 1){
                    JOptionPane.showMessageDialog(null, "X Wins");
                    break;
                }
                if(MoveHistory[i][0] == 2){
                    JOptionPane.showMessageDialog(null, "O Wins");
                    break;
                }
            }
        }
        
    }
    
}

  
}
 

Attachments

  • Picture 1.png
    Picture 1.png
    20.6 KB · Views: 102

Palad1

macrumors 6502a
Feb 24, 2004
647
0
London, UK
AS a rule of thumb, create an actionListener for each button, then refactor some code. Sharing actionlisteners gets ugly real fast.

From memory:
PHP:
myButton.addActionListener(new ActionAdapter(){
 public void actionPerformed(ActionEvent event){
   myButton.setEnabled(false);
   try{
    DoStuff();
   }finally{
    myButton.setEnabled(true);
   } 
 } 
});
 

mbabauer

macrumors regular
Feb 14, 2006
105
0
the_insider said:
and the //****

is where ive got another prob..
You should REALLY consider commenting your code better. Read up on the usage of JavaDoc.

the_insider said:
when i do get the program running, if i click on one box, it will change to an X, or an O, and if i click the same box, il get a pop up to tell the player that you have to click on another box. but after that instead of an X again, it will be an O or vice versa.
does that make any sense?

This makes sense as much as I can make sense of anyones totally uncomment brain dump. Without giving myself a migrain, I would have to say whatever code you have checking the move's validity is not halting the processing of the move. It seems to me that what you probably want to do instead is check for a valid move, throw an exception of some sort if its not, and catch it were you are doing the click, making sure you do not flip whatever bit that indicates who's move it is.

My next advice...get a decent IDE like Eclipse (man, I must have said this in 4 or 5 posts tonight). I can't STRESS enough how important a good IDE with a good debugger is. You can get Eclipse at http://www.eclipse.org.

Last, I can say that I am a Sun Certified Developer, and have been coding Java since 1.02 beta was released. My first experience with Java was in a collage class in 1995, and even the professor didn't know anything about this new language. Most of the class went like "Ok, how many thinks it works this way...ok, let try it...". So, bottom line is I have *some* experience, and I can say that several people have practically handed you the pseudo code for this...2-D array, my friend! It makes logical sense, makes the checks easier, and you don't have to keep track of anyone's moves since you have an array full of them.

Good luck

P.S. - Dont cheat. Cheaters suck, and in the end, who are you really hurting?
 

jtalerico

macrumors 6502
Nov 23, 2005
358
0
mbabauer IDEs

mbabauer -

Good call! You prefer IDEs? I do too, but it has been a recent topic/discussion on slashdot that CS people should not start off with IDE's but just have a text editor and then compile. What are you feelings on that? (I guess I could start a new thread, but it seems it could go here.
 

mbabauer

macrumors regular
Feb 14, 2006
105
0
jtalerico said:
I do too, but it has been a recent topic/discussion on slashdot that CS people should not start off with IDE's but just have a text editor and then compile. What are you feelings on that?

I think the people who think that way either dont code for a living or are too "idealistic".

Lets put it another way...say you got interested in wood working and wanted to build a small table. Should you be forced to cut down a tree, plane and saw by hand, etc? Well, you could if you wanted to be all "hard-core" like the Yankee Workshop guy, but most wood workers would suggest you get some tools. A table saw, planer, etc.

The bottom line is this. When anyone is starting out, the point of all these tasks is to learn the concepts of programming, not the language. In my own teachings (I have done some on the side), I find the students get way too hung up on the symantics. I try to tell them to "Visualize the problem, and what steps to take to solve them", but instead I get questions about IOExceptions and classpaths.

It is totally up to you, really. I know developers that STILL to this day use only a text editor and a compiler. I also know people that cant do anything without an IDE. If you forgo all the bells and whistles of the IDE, like the GUI builders and wizzards, then really all you are left with is a decent text editor, which is really how I use an IDE anyway. What it DOES give you is things like a debugger (IMHO the most important thing a flegling developer should learn) and niceties like "Auto-complete" and syntax checking.
 

jeremy.king

macrumors 603
Jul 23, 2002
5,479
1
Holly Springs, NC
mbabauer said:
I think the people who think that way either dont code for a living or are too "idealistic".

Lets put it another way...say you got interested in wood working and wanted to build a small table. Should you be forced to cut down a tree, plane and saw by hand, etc? Well, you could if you wanted to be all "hard-core" like the Yankee Workshop guy, but most wood workers would suggest you get some tools. A table saw, planer, etc.

The bottom line is this. When anyone is starting out, the point of all these tasks is to learn the concepts of programming, not the language. In my own teachings (I have done some on the side), I find the students get way too hung up on the symantics. I try to tell them to "Visualize the problem, and what steps to take to solve them", but instead I get questions about IOExceptions and classpaths.

It is totally up to you, really. I know developers that STILL to this day use only a text editor and a compiler. I also know people that cant do anything without an IDE. If you forgo all the bells and whistles of the IDE, like the GUI builders and wizzards, then really all you are left with is a decent text editor, which is really how I use an IDE anyway. What it DOES give you is things like a debugger (IMHO the most important thing a flegling developer should learn) and niceties like "Auto-complete" and syntax checking.

I disagree wholeheartedly. Learning the ins and outs of the Java environment is imperative to become a good Java programmer. Using your own experience, did you start with an IDE? Um I highly doubt it, since they really didn't even exist then.

Telling a beginner to use an IDE is like telling a 3rd grade math student to use a calculator instead of a pencil and paper - then later on in life they rely on the calculator and have no idea how to truly solve a math problem problem. Granted, I wouldn't consider writing a swing based tic tac toe app as a beginning task. A similar example is people who rely on a Word processor to teach them grammar or spelling - it seems just wrong. Or better yet, ever watch a young cashier try to make change without a register...Its funny...I digress...

It is my strong opinion that a java programmer must learn the basic concepts of javac, java, jdb, jar, javadoc, and other commands - not to mention the role of bytecode and the concept of a VM. Only after having a solid understanding of the role of those commands would I recommed and IDE so they can realize (and appreciate) how the IDE can make these tasks easier. But starting with an IDE will only lead to a more shallow understanding of Java (or any other language).

I do agree that if you can't solve problems in a systematic way, you won't get far programming in any language. Adding a dimension such as an IDE too early in the process of learning will simply cause distractions from truly learning the art of programming.

All that said, if you are just trying to get through an elective course and don't care to do programming ever again, go ahead...use an IDE.
 

Jedi128

macrumors 6502
Jul 7, 2005
274
0
New York, NY
This Tic Tac Toe thing must really be popular becuase for my post AP test time in my high school programming class we tried to build one of these apps (or applets) for fun. Mine ultimately does not work, but I tried to do a pure app and not an applet, which I think is harder. I have never used any of the swing or java.awt or java.awt.event stuff before so this was quite a challenge, especially being short on time. I just thought it was funny that I got the same project at the end of the year...
 

0s and 1s

macrumors 6502a
Mar 7, 2004
609
100
OK, USA
Ah......memories.... :(

I remember doing this when I was a CS major.

Good luck. My TTT prog ended up looking like a Connect Four gameboard, but I somehow figured it out on the day it was due.....without any help!!! :cool:
 

mbabauer

macrumors regular
Feb 14, 2006
105
0
kingjr3 said:
I disagree wholeheartedly. Learning the ins and outs of the Java environment is imperative to become a good Java programmer. Using your own experience, did you start with an IDE? Um I highly doubt it, since they really didn't even exist then.

How is mistyping method and class names learning the Java language? I am by no means advocating the use of an GUI builder or auto-code generation tools like XDoclet and such. I am speaking directly to the ability to hit Ctrl-space and have a list of methods or class names pop up, or mousing over some code and getting a decent JavaDoc popup that explains what its trying to do.

kingjr3 said:
Telling a beginner to use an IDE is like telling a 3rd grade math student to use a calculator instead of a pencil and paper - then later on in life they rely on the calculator and have no idea how to truly solve a math problem problem. Granted, I wouldn't consider writing a swing based tic tac toe app as a beginning task. A similar example is people who rely on a Word processor to teach them grammar or spelling - it seems just wrong. Or better yet, ever watch a young cashier try to make change without a register...Its funny...I digress...

I agree, but disagree. Again, I am not advocating the "Use a tool to write the code for you method", as you would see in something like Sun Forte or even MS Visual Basic (Drag-n-code), I am simply saying Notepad is NOT the way to go. What better way to learn that your code is screwed up than to have the editor underline it in red and an error at the bottom saying "ERROR: Cannot cast a int as a float"? Also, the context of the statement was for those learning to program, not those learning to be straight-up Java developers. My the time I took my first Java course, I had almost 2 years of coding in C and C++ under my belt. I had written an assembler and a C-- compiler, and was in a class called "Operating Systems", which surprisingly enough had us writting an OS from some crazy virtual machine. At this point, I knew what a linked list was, or that most languages referenced arrays from 0. I had the basics pretty much under my belt.

kingjr3 said:
It is my strong opinion that a java programmer must learn the basic concepts of javac, java, jdb, jar, javadoc, and other commands - not to mention the role of bytecode and the concept of a VM. Only after having a solid understanding of the role of those commands would I recommed and IDE so they can realize (and appreciate) how the IDE can make these tasks easier. But starting with an IDE will only lead to a more shallow understanding of Java (or any other language).

Again, I have first-hand experience teaching people who have NEVER developed a single line of code in their lives, and I have seen first hand these people struggle with crap like classpaths and JAR files and symantic crap that really, in all honesty, has little to nothing to do with actual software development and more to do with the coding styles of the language developers. I have also seen how, when given just a rudimentary demo of an IDE (Basics, again not talking code generation and such), and taught just a tad bit of how to run a debugger, these people start to figure out problems on their own.

Using your argument, one would then be lead to thing that people should start coding in Assembler. Or, better yet, how about just handing them a Hex editor and make them write in machine code. At some point you have to abstract the languange for the user, let them figure out the logical thinking part, then throw the details back in. If they decide Java is the bee's knees, then let them take the Sun Certified Programmer test, which will sure enough test them on the usage of JAR files, class loaders, etc, etc.

Frankly, if one was going to take the approach of "learn the hard way", I would recommend starting in C, then work to C++, then Java. Thats what I did, and have come to know truely what a NullPointerException really is.

kingjr3 said:
I do agree that if you can't solve problems in a systematic way, you won't get far programming in any language. Adding a dimension such as an IDE too early in the process of learning will simply cause distractions from truly learning the art of programming.

Some of the problems I mention COULD be solved by 4th and 5th generation languages that are not so reliant on the symantecs being right.

kingjr3 said:
All that said, if you are just trying to get through an elective course and don't care to do programming ever again, go ahead...use an IDE.

One of the other things an IDE helps instill is a sense of "style". Style is one of my pet-pieves. I can't stand to see code where someone uses tabs in one place, spaces over there, etc. It would also help encourage good self documenting code, since it lays down the templates of the comments for you.


Obviously this is my $0.02 worth, and everyone is entitled to their opinion. My final point is this...if you plan to be a hard nosed developer, you should start with another language anyway. Java is a great language, but lets be honest...it lets you cut way too many corners. Memory management is one of the WORST problems I see in flegling code, and Java sorta skips right over all of that...at least until the point in which you see your very first OutOfMemoryException, that is.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.