Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Tic Tac Toe game - winning logic not working.

    Hi,
    I am writing a Tis Tac Toe program for me Java Course. But can't seem to get the winning logic working. Any help is appreciated.

    I have a ClickableBox.java(to make a box which can be clicked), TicTacToeBox.java(draws 'x' and 'o') and TicTacToeGame.java(an applet which has gamelogic and winning logic)

    The code for TicTacToeGame.java is as follows:

    Java Code:
    import java.applet.Applet;
    import java.awt.Button;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    
    public class TicTacToeGame extends Applet {
      private final int START_X = 20;
      private final int START_Y = 40;
      private final int ROWS = 3;
      private final int COLS = 3; 
      private final int BOX_WIDTH = 40;
      private final int BOX_HEIGHT = 40;
      private char player='X';
      private int selectorSwitch = 1;
      private int count,var;
      private int[][] pos = new int[3][3];
     
      private TicTacToeBox boxes[][];
       
      private Button resetButton;
      
      public void init()
      {
        boxes = new TicTacToeBox[ROWS][COLS];
            
       resetButton = new Button("New Game");
       for(int row = 0; row < boxes.length; row ++) {
         for(int col = 0; col < boxes[row].length; col++) {
           pos[row][col] = 0;
         }
         }
       
       
       resetButton.addActionListener(new ActionListener() {
         
         public void actionPerformed(ActionEvent e) {
           
           buildBoxes();
           repaint();       
         }
       }
       );
        add(resetButton);
        buildBoxes();
        
        
        
        resize(400,400);
    
      }
      
      public void paint(Graphics g) {
    
        if (selectorSwitch%2 == 1)
        {       
          
          player = 'X'; 
          g.drawString("Current Player: " + player, 20, 280);
                    
        }
               
        else 
        {        
        
          player = 'O';  
          g.drawString("Current Player: " + player, 20, 280);
         
        } 
        
        
        
        for(int row = 0; row < boxes.length; row ++) {
            for(int col = 0; col < boxes[row].length; col++) {
              if(boxes[row][col].isClicked()) {
                gameLogic(boxes[row][col]);
                  
                  if (player == 'X')
                  {
                              
                      pos[row][col] = 1;
                  }
                  if (player == 'O')
                    {
                     
                      pos[row][col] = 4;
                    }
                  
                           
                  System.out.println("pos[][]:" + pos[row][col]+ "row: "+ row + "col: " + col);
                  
                  checkWin(row,col,pos[row][col]);
                  
               
               }
               }
                }
    
    
        //loop through the boxes and draw them.
        for (int row = 0; row < boxes.length; row++) {
         for (int col = 0; col < boxes[row].length; col++) {
         boxes[row][col].draw(g);
         }
        }
        }
    
          
       
    
    
      private void removeMouseListeners() {
        for(int row = 0; row < boxes.length; row ++) {
            for(int col = 0; col < boxes[row].length; col++) {
                removeMouseListener(boxes[row][col]);
            }
        }
    }
    
      
      private void buildBoxes() {
     
       count = 0;
     //  winCount =0;
        selectorSwitch = 1;
        
        removeMouseListeners();
        for(int row = 0; row < boxes.length; row++) {
          for(int col = 0; col < boxes[row].length; col++) {
         //   pos[row][col] = 0;
              boxes[row][col] = 
                new TicTacToeBox(START_X + col * BOX_WIDTH,
                                 START_Y + row * BOX_HEIGHT,
                                 BOX_WIDTH,
                                 BOX_HEIGHT,
                                 this);
              addMouseListener(boxes[row][col]);
          }
        }
        
      }//end of buildBoxes()
    
    
      public void gameLogic(TicTacToeBox box) {
       
        
        if (box.getImmutable() == false) {
          if (selectorSwitch%2 == 1) {
            
            box.setPlayer(true);
            box.setImmutable(true); 
            count++;
            System.out.println("Test place game logic,count:" + count);
            }
          else { 
           
            box.setPlayer(false); 
            box.setImmutable(true);
            count++;
            System.out.println("Test place game logic, count:" + count);
            }  
          selectorSwitch++;  
          }    
        }
        
      
      private void checkWin(int row,int col,int n)
      {
        
        
        if (count >4)
        {
          
          if((pos[row][0]+pos[row][1]+pos[row][2]==n*3)||(pos[0][col]+pos[1][col]+pos[2][col]==n*3))
          {
          //  System.out.println("Test place loop 1" + "winCount:"+winCount + "count:"+count);
            count = n;
                    
          }
          else
          {
            if((pos[0][0]+pos[1][1]+pos[2][2]==n*3)||(pos[2][0]+pos[1][1]+pos[0][2]==n*3))
            {
           //   System.out.println("Test place loop 2" +"winCount:"+winCount + "count:"+count);
              count = n;
             
            }
            else
            {
              if(count == 9)
              {
              //  System.out.println("Test place loop 3" + "winCount:"+winCount + "count:"+count);
                count = 0;
                declare("Neither player won! Please start a new game.",this.getGraphics()); 
                
              }
         
            }
          }
          
       
          if(count==1||count==0)
          {  //When either first player wins or a Draw occurs.
          //  System.out.println("Test place loop 4" + "winCount:"+winCount + "count:"+count);  
            if((count==1)) 
                  declare("Player " + player+ " Wins! Please start a new game.",this.getGraphics());
            if(count==0)
                  declare("The Game is a Draw!Please start a new game.",this.getGraphics());
          }
          
          else
          {
          //  System.out.println("Test place loop 5" + "winCount:"+winCount + "count:"+count);
              if(count==4)
              {   // When 2nd player wins.
                  declare("Player" + player+ " Wins!Please start a new game.",this.getGraphics());
              }
    
          }
    
          
        }
       
          
      }//end of checkWin
     
      private void declare(String status,Graphics g)
      {
        g.drawString(status, 20, 320);
      }
      
    
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    When you say it "isn't working", what exactly do you mean? Does it work for certain cases? What does it do instead of what you expect?

    Have you traced through this with a debugger, or at least added some print statements, to figure out what's going on?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    Yes, its working for certain cases. Its mostly working for 'x' moves. But even if in certain cases 'x' , is not the winner, it prints that it is the winner. And for 'o', its mostly not working. I have tried with the print statement to debug, but can't figure it out.

    Other java codes that I am using are:
    ClickableBox.java
    Java Code:
    import java.awt.event.MouseAdapter;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.Container;
    
    
    public class ClickableBox extends MouseAdapter {
      private int x,y,width,height;
      private Color borderColor, backColor,oldColor;
      private boolean drawBorder, clicked;
      private Container parent;
      
      
      public ClickableBox(int x,int y,int width, int height, Container parent) 
      {
        
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height; 
        this.parent = parent;
        
      }
      
      public void draw(Graphics g) {
        oldColor = g.getColor();
        g.setColor(Color.WHITE);
        g.fillRect(x, y, width, height);
        g.setColor(Color.BLACK);
            g.drawRect(x, y, width, height);
       
        g.setColor(oldColor);
    }
    
     public void mouseReleased(MouseEvent e)
     {
       if(x<e.getX() && e.getXOnScreen()< x+ width
         && y< e.getY() && e.getY() < y+height) {
         clicked = true;
         parent.repaint();
       }
     }
     
     public boolean isClicked() {
       return clicked;
    }
    
    public void setClicked(boolean clicked) {
       this.clicked = clicked;
    }
    
    
      
      public int getX() {
        return x;
      }
    
      public void setX(int x) {
        this.x = x;
      }
    
      public int getY() {
        return y;
      }
    
      public void setY(int y) {
        this.y = y;
      }
    
      public int getWidth() {
        return width;
      }
    
      public void setWidth(int width) {
        this.width = width;
      }
    
      public int getHeight() {
        return height;
      }
    
      public void setHeight(int height) {
        this.height = height;
      }
    
      public Color getBorderColor() {
        return borderColor;
      }
    
      public void setBorderColor(Color borderColor) {
        this.borderColor = borderColor;
      }
    
      public Color getBackColor() {
        return backColor;
      }
    
      public void setBackColor(Color backColor) {
        this.backColor = backColor;
      }
    
      public Color getOldColor() {
        return oldColor;
      }
    
      public void setOldColor(Color oldColor) {
        this.oldColor = oldColor;
      }
    
      public boolean isDrawBorder() {
        return drawBorder;
      }
    
      public void setDrawBorder(boolean drawBorder) {
        this.drawBorder = drawBorder;
      }
    
    
    }
    and TicTacToeBox.java is as follows:
    Java Code:
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    
    
    public class TicTacToeBox extends ClickableBox {
    
      private boolean mask;
      private Color maskColor;
      Container parent;
      private boolean player,immutable;
      private int var=1;
     
      
      
      public TicTacToeBox(int x, int y, int width, int height, Container parent) {
        super(x, y, width, height,parent);
        this.parent = parent;
      }
      
      public void draw(Graphics g) {
        super.draw(g);
       if(isClicked())
       {
         if(this.player == true) {
           
          // var = 1;
          // System.out.println("var =1" +var);
           g.setColor(Color.GREEN.darker());
           g.drawString("X", getX()+ getWidth()/2,getY()+getHeight()/2);
           return;
          
       }
         else
           if(this.player == false)
        {
         //  var = 4;
         //  System.out.println("var =4" +var);
          g.setColor(Color.RED);
          g.drawString("O", getX()+ getWidth()/2,getY()+getHeight()/2);
          return;
        }
       }
    }
     
     public boolean getPlayer()
      {     
        return player;
        
      }            
      
      public void setPlayer(boolean which)
      {     
        player = which;
      }      
      
      public int getVar()
      {     
        return var;
        
      }            
      
      public void setVar(int what)
      {     
        var = what;
      }      
    
      public boolean getImmutable() 
      {      
        return immutable;
      }              
      
      public void setImmutable(boolean flag) 
      {       
        immutable = flag;     
        
      }
      
     
      
    
    }

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Tic Tac Toe game - winning logic not working.

    There are no print statements in there.
    We aren't going to run this for you.
    You need to do some of the work and show us the result.
    If you put println()s in there then show us that code and the output, compared with the output you would have expected.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    Well, I have System.out.println in the TicTacToeGame.java . I deleted most of it out , so that the code doesn't become to long . I still have some in there which I have commented out. What I have not done before is , shown you the output.

    I will show you two cases here:
    Tic Tac Toe game - winning logic not working.-case1.gifTic Tac Toe game - winning logic not working.-case2.gif

    First case:works as expected

    Second case: the code doesn't work as expected

    As you can see, I have done lot of work myself. Thank you for your feedback anyway.

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    So now it's your job to figure out why it isn't working in that case. Trace through the logic with that case in mind, and see how it's arriving at the conclusion that X won. Debugging and print statements should help with this process.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    Good Morning. Hope you had a great weekend.

    Thank you so much for your reply. Its really helpful. I didn't know that print statement can be so helpful.

  8. #8
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    I am still looking for a more constructive reply. If anybody has any other suggestions?

  9. #9
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    Why are you using ints in your array? You're adding them up, which doesn't make sense as a win condition, since several combinations can lead to the same total.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    When initially I was writing the logic, adding the integer to get a winning combination made sense and hence I went ahead with it. But later on when it was not working for some cases I had the same doubt . So I went ahead and googled and saw several places it has been coded like this (meaning using init combination). Then, I got little confused and staretd to think that it must be something in my code that was not right and hence decided to create a thread as I was unable to figure out.

    So what would be your suggestion to get to winning combination?

  11. #11
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    How do you determine a winner without a computer? Do you come up with some system involving integer values for symbols and some kind of formula to determine the winner? I sure don't!
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  12. #12
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    I am trying to create a Tic Tac Toe game that two players can play. For testing purposes I am playing the moves for both the players. No I didn't come up with any formula or anything of that sort. I am trying to keep it simple, so that I can understand the basic, before trying something really complicated.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Tic Tac Toe game - winning logic not working.

    Quote Originally Posted by Mikki View Post
    I am still looking for a more constructive reply. If anybody has any other suggestions?
    Without at least some sign you have attempted to debug this I'm not going to look at a code dump.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    What makes you think I din't debug it? I am here to learn something and am not looking to cut corners. After spending a whole day trying to figure out where I was going wrong, I decided to create this thread and because I was getting little frustrated. Maybe its something very silly, but I thought maybe a second pair of eye can help me work it out.

  15. #15
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    Quote Originally Posted by Mikki View Post
    No I didn't come up with any formula or anything of that sort. I am trying to keep it simple, so that I can understand the basic, before trying something really complicated.
    You're assigning integer values to the X and O symbols, adding them up, and assigning some meaning to the totals. That's a formula, and it's a lot more complicated than how I assume you check for a win without a computer.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  16. #16
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    okay if you call that a formula, then I did use one. If that's complicated then how would you check for a win?

  17. #17
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    Quote Originally Posted by Mikki View Post
    okay if you call that a formula, then I did use one. If that's complicated then how would you check for a win?
    How do you check for a win without a computer?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  18. #18
    Mikki is offline Member
    Join Date
    Jun 2012
    Posts
    16
    Rep Power
    0

    Default Re: Tic Tac Toe game - winning logic not working.

    The logic that I have tried to use is

    For the two players, i am using a selectorSwitch, which is initially set to 1. Then in the gamesLogic method, if (selectorSwitch%2 == 1), then its the first player (first player is X) else second player.

    If the player is 'X' then array pos[][] = 1 and if the player is 'O' then pos[][] = 4.
    With these value I call the checkWin method.
    In checkWin I have the eight possible winning combination for which the value will either be 3*1 or 3*4 . If that's the case then depending on whether its 1 or 4, the message is displayed.

  19. #19
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,956
    Rep Power
    8

    Default Re: Tic Tac Toe game - winning logic not working.

    Is that really how you figure out whether somebody won a game of tic-tac-toe, when you're playing with a piece of paper and a pencil?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Tic Tac Toe game - winning logic not working.

    Quote Originally Posted by Mikki View Post
    What makes you think I din't debug it?
    Because you haven't shown it here. You could have debugged it, but we haven't seen it.
    The reason I asked for you to put println() calls in there is so you could produce some debug output that would give some idea of where this thing is going wrong, without having to step through your code.

    Anyway, I'll leave you in Kevins capable hands.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Page 1 of 2 12 LastLast

Similar Threads

  1. Game using swings not working
    By humanbeing in forum Java Gaming
    Replies: 7
    Last Post: 10-06-2010, 03:04 PM
  2. Logic not working
    By Prajin in forum AWT / Swing
    Replies: 1
    Last Post: 07-19-2010, 07:54 PM
  3. Game Help.working on it for days,.
    By xSkittlesx in forum Java Applets
    Replies: 12
    Last Post: 05-31-2010, 03:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •