Lost Password?

Go Back   CodeCall Programming Forum > Software Development > Tutorials > Java Tutorials

Unregistered, Check out the Coder Battles in the Announcement and Game forums.

Java Tutorials Tutorials and Code for Java

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #11 (permalink)  
Old 06-02-2007, 12:50 AM
Bigbag101 Bigbag101 is offline
Newbie
 
Join Date: Jun 2007
Posts: 2
Credits: 0
Rep Power: 0
Bigbag101 is on a distinguished road
Default

Sidewinder | Please use [php], [code] and [quote] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

Still regarding the image instead of text, it still does not appear to be working. If you could be so kind, can you please show me how to setIcon using the code.



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

public cl*** TicTacToeV2 implements ActionListener {
	/*Instance Variables*/
	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 JFrame window = new JFrame("Tic-Tac-Toe");
	private JButton buttons[] = new JButton[9];
	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=0; i<=8; i++){
		buttons[i] = new JButton();
		window.add(buttons[i]);
		buttons[i].addActionListener(this);
	}
	
	/*Make The Window Visible*/
	window.setVisible(true);
	}
	
	/**
	 When an object is clicked, perform an action.
	 @param a action event object
	 */
	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*/
		 JButton pressedButton = (JButton)a.getSource(); 
		 pressedButton.setText(letter);
		 pressedButton.setEnabled(false);
		
		/*Determine who won*/
		for(int i=0; i<=7; i++){
			if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && 
				buttons[winCombinations[i][1]].getText().equals(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();
	}
}
Sidewinder | Please use [php], [code] and [quote] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

Last edited by John; 06-02-2007 at 10:57 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 06-02-2007, 11:04 AM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 20
Posts: 3,237
Last Blog:
Passwords
Credits: 877
Rep Power: 20
John has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud of
Send a message via AIM to John Send a message via MSN to John
Default

From the looks of it, you've made no changes to my code. Show me what you did and I will help.

Have you looked at the Javadocs?

Java Platform 1.2 Beta 4 API Specification: Cl*** JButton
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 10-25-2007, 10:25 AM
The Midnighter The Midnighter is offline
Newbie
 
Join Date: Oct 2007
Posts: 14
Credits: 0
Rep Power: 0
The Midnighter is on a distinguished road
Default Hmm...

I'm having trouble creating a working win function, so I googled it.. and here I am.

I know this thread is meretriciously old, but I really need this help lol.
Here's my current code:

Code:
package tictactoe;

import javax.swing.JButton;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public cl*** TicTacToeForm extends javax.swing.JFrame implements ActionListener
{
    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 String turn = "";
    private String config[] = new String[10];
    private boolean win = false;
    private int count = 0;
    
    public TicTacToeForm()
    {
        initComponents();
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
        jButton3.addActionListener(this);
        jButton4.addActionListener(this);
        jButton5.addActionListener(this);
        jButton6.addActionListener(this);
        jButton7.addActionListener(this);
        jButton8.addActionListener(this);
        jButton9.addActionListener(this);
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents()
    {
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();

        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TicTacToe");
        setName("jFrame");
        jButton2.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton2ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 75, 70));

        jButton3.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton3ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 10, 75, 70));

        jButton4.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton4ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 75, 70));

        jButton5.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton5ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 90, 75, 70));

        jButton6.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton6ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 90, 75, 70));

        jButton1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton1ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 75, 70));

        jButton7.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton7ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 75, 70));

        jButton8.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton8ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 170, 75, 70));

        jButton9.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton9ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 75, 70));

        pack();
    }// </editor-fold>                        
    
    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton9.setText(turn);
        jButton9.setEnabled(false);
        config[9] = turn;
    }                                        
    
    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton8.setText(turn);
        jButton8.setEnabled(false);
        config[8] = turn;
    }                                        
    
    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton7.setText(turn);
        jButton7.setEnabled(false);
        config[7] = turn;
    }                                        
    
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton6.setText(turn);
        jButton6.setEnabled(false);
        config[6] = turn;
    }                                        
    
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton5.setText(turn);
        jButton5.setEnabled(false);
        config[5] = turn;
    }                                        
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton4.setText(turn);
        jButton4.setEnabled(false);
        config[4] = turn;
    }                                        
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton3.setText(turn);
        jButton3.setEnabled(false);
        config[3] = turn;
    }                                        
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton2.setText(turn);
        jButton2.setEnabled(false);
        config[2] = turn;
    }                                        
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton1.setText(turn);
        jButton1.setEnabled(false);
        config[1] = turn;
    }                                        
    
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new TicTacToeForm().setVisible(true);
            }
        });
    }
    
    public boolean checkWinner()
    {
        for(int i=0; i<=7; i++)
        {
            if( config[winCombinations[i][0]].equals(config[winCombinations[i][1]]) &&
                    config[winCombinations[i][1]].equals(config[winCombinations[i][2]]) &&
                    config[winCombinations[i][0]] != "")
            {
                win = true;
            }
        }
        return win;
    }
    
    public void actionPerformed(ActionEvent a)
    {
        count++;
        
        if(count %2 == 0)
        {
            turn = "O";
        }
        else
        {
            turn = "X";
        }
        
    }
    
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    // End of variables declaration                   
}
Right now, my checkWinner(); function doesn't work at all, I tried to adapt a few ideas from this thread, but it didn't help a whole lot.
Any help is appreciated.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 10-25-2007, 12:41 PM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 20
Posts: 3,237
Last Blog:
Passwords
Credits: 877
Rep Power: 20
John has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud of
Send a message via AIM to John Send a message via MSN to John
Default

Well there is 3 things I noticed.
1) You used a crappy IDE to generate your code, use a descent IDE like eclipse and write every line of code yourself and it wont look like fecal matter.

2) Your config array starts at 1 and goes to 9, yet winCombinations[][] only only checks an array from 0 to 8.

3) checkWinner() is never called...
__________________
CodeCall Blog | CodeCall Wiki | Shareware | Linux Forum | My Blog
Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 11-07-2007, 01:29 PM
phenoma phenoma is offline
Newbie
 
Join Date: Nov 2007
Posts: 5
Credits: 0
Rep Power: 0
phenoma is on a distinguished road
Default hi

Sidewinder | Please use [php], [code] and [highlight...] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

I know its been a year for the java tutotrial,but I need ur help! can u help me add:
1. A new Game button that starts a new game
2.A running score showing the number of games won by each player(X or O).
in my tic tac toe program?


Java Code:
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.border.LineBorder;
  5.  
  6. public cl*** TicTacToe extends JApplet {
  7.   // Indicate which player has a turn, initially it is the X player
  8.   private char whoseTurn = 'X';
  9.  
  10.   // Create and initialize cells
  11.   private Cell[][] cells =  new Cell[3][3];
  12.  
  13.   // Create and initialize a status label
  14.   private JLabel jlblStatus = new JLabel("X's turn to play");
  15.  
  16.   /** Initialize UI */
  17.   public TicTacToe() {
  18.     // Panel p to hold cells
  19.     JPanel p = new JPanel(new GridLayout(3, 3, 0, 0));
  20.     for (int i = 0; i < 3; i++)
  21.       for (int j = 0; j < 3; j++)
  22.         p.add(cells[i][j] = new Cell());
  23.  
  24.     // Set line borders on the cells panel and the status label
  25.     p.setBorder(new LineBorder(Color.red, 1));
  26.     jlblStatus.setBorder(new LineBorder(Color.yellow, 1));
  27.  
  28.     // Place the panel and the label to the applet
  29.     add(p, BorderLayout.CENTER);
  30.     add(jlblStatus, BorderLayout.SOUTH);
  31.   }
  32.  
  33.   /** Determine if the cells are all occupied */
  34.   public boolean isFull() {
  35.     for (int i = 0; i < 3; i++)
  36.       for (int j = 0; j < 3; j++)
  37.         if (cells[i][j].getToken() == ' ')
  38.           return false;
  39.  
  40.     return true;
  41.   }
  42.  
  43.   /** Determine if the player with the specified token wins */
  44.   public boolean isWon(char token) {
  45.     for (int i = 0; i < 3; i++)
  46.       if ((cells[i][0].getToken() == token)
  47.           && (cells[i][1].getToken() == token)
  48.           && (cells[i][2].getToken() == token)) {
  49.         return true;
  50.       }
  51.  
  52.     for (int j = 0; j < 3; j++)
  53.       if ((cells[0][j].getToken() ==  token)
  54.           && (cells[1][j].getToken() == token)
  55.           && (cells[2][j].getToken() == token)) {
  56.         return true;
  57.       }
  58.  
  59.     if ((cells[0][0].getToken() == token)
  60.         && (cells[1][1].getToken() == token)
  61.         && (cells[2][2].getToken() == token)) {
  62.       return true;
  63.     }
  64.  
  65.     if ((cells[0][2].getToken() == token)
  66.         && (cells[1][1].getToken() == token)
  67.         && (cells[2][0].getToken() == token)) {
  68.       return true;
  69.     }
  70.  
  71.     return false;
  72.   }
  73.  
  74.   // An inner cl*** for a cell
  75.   public cl*** Cell extends JPanel {
  76.     // Token used for this cell
  77.     private char token = ' ';
  78.  
  79.     public Cell() {
  80.       setBorder(new LineBorder(Color.black, 1)); // Set cell's border
  81.       addMouseListener(new MouseListener())// Register listener
  82.     }
  83.  
  84.     /** Return token */
  85.     public char getToken() {
  86.       return token;
  87.     }
  88.  
  89.     /** Set a new token */
  90.     public void setToken(char c) {
  91.       token = c;
  92.       repaint();
  93.     }
  94.  
  95.     /** Paint the cell */
  96.     protected void paintComponent(Graphics g) {
  97.       super.paintComponent(g);
  98.  
  99.       if (token == 'X') {
  100.         g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
  101.         g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
  102.       }
  103.       else if (token == 'O') {
  104.         g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
  105.       }
  106.     }
  107.  
  108.     private cl*** MouseListener extends MouseAdapter {
  109.       /** Handle mouse click on a cell */
  110.       public void mouseClicked(MouseEvent e) {
  111.         // If cell is empty and game is not over
  112.         if (token == ' ' && whoseTurn != ' ') {
  113.           setToken(whoseTurn); // Set token in the cell
  114.  
  115.           // Check game status
  116.           if (isWon(whoseTurn)) {
  117.             jlblStatus.setText(whoseTurn + " won! The game is over");
  118.             whoseTurn = ' '; // Game is over
  119.           }
  120.           else if (isFull()) {
  121.             jlblStatus.setText("Draw! The game is over");
  122.             whoseTurn = ' '; // Game is over
  123.           }
  124.           else {
  125.             whoseTurn = (whoseTurn == 'X') ? 'O': 'X'; // Change the turn
  126.             jlblStatus.setText(whoseTurn + "'s turn")// Display whose turn
  127.           }
  128.         }
  129.       }
  130.     }
  131.   }
  132.  
  133.   /** This main method enables the applet to run as an application */
  134.   public static void main(String[] args) {
  135.     // Create a frame
  136.     JFrame frame = new JFrame("TicTacToe");
  137.  
  138.     // Create an instance of the applet
  139.     TicTacToe applet = new TicTacToe();
  140.  
  141.     // Add the applet instance to the frame
  142.     frame.add(applet, BorderLayout.CENTER);
  143.  
  144.     // Display the frame
  145.     frame.setSize(300, 300);
  146.     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  147.     frame.setVisible(true);
  148.   }
  149. }

Sidewinder | Please use [php], [code] and [highlight...] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

Last edited by John; 11-07-2007 at 01:40 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote