Results 1 to 6 of 6
  1. #1
    panagip is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default game of Crosses & Naughts - problem with the menu

    Hello,
    I'm trying to create a game of Crosses & Naughts but I have a little problem with the menu. Could you please tell what's wrong with that?
    Java Code:
    /*
    |--------------------------------------------------------|
    |					   TicTacToe®	          	|
    |--------------------------------------------------------|
    |             This is the class that implements			|
    |                the main menu of the game   			|
    |--------------------------------------------------------|
    | Author: panagip                                                        |
    | Date  : May 26th 2013   					        |
    |--------------------------------------------------------|
    */
    /*-------------------------------------------------------------------------------------*/
    //importing necessary libraries
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    /*-------------------------------------------------------------------------------------*/
    //creating the main class
    public class MainMenu extends JMenuBar
    {
    	//declaring the menu
    	public JMenuBar  jmbMain        = new JMenuBar();
    	public JMenu     menuGame       = new JMenu("Game");
    	public JMenu     menuHelp       = new JMenu("Help");
    	public JMenuItem jmiNewGame     = new JMenuItem("New Game");
    	public JMenuItem jmiGameStats   = new JMenuItem("Statistics");
    	public JMenuItem jmiGameOptions = new JMenuItem("Options...");
    	public JMenuItem jmiGameQuit    = new JMenuItem("Quit");
    	public JMenuItem jmiAbout       = new JMenuItem("About TicTacToe®...");
    
    /*-------------------------------------------------------------------------------------*/
    	//creating the Constructor of the class MainMenu
    	public MainMenu()
    	{
    		try //try to process the following code
    		{
    			//creating the menu and the two main submenus
    			jmbMain.add(menuGame);
    			jmbMain.add(menuHelp);
    
    			//creating the submenu Game and all its submenus
    			menuGame.add(jmiNewGame);
    			menuGame.addSeparator();
    			menuGame.add(jmiGameStats);
    			menuGame.add(jmiGameOptions);
    			menuGame.addSeparator();
    			menuGame.add(jmiGameQuit);
    			
    			//creating the submenu Help and its submenu
    			menuHelp.add(jmiAbout);
    			
    			//setup shortcut-mnemonic characters for all the items of the menu
    			menuGame.setMnemonic('G');
    			jmiNewGame.setMnemonic('N');
    			jmiGameStats.setMnemonic('S');
    			jmiGameOptions.setMnemonic('O');
    			jmiGameQuit.setMnemonic('Q');
    			menuHelp.setMnemonic('H');
    			jmiAbout.setMnemonic('A');
    		}
    		catch(Exception e) //if there is an error capture it and display it to the user
    		{
    			//print the error on the console
    			e.printStackTrace();
    
    			//display the error to the user
                JOptionPane.showMessageDialog(this,"System error occured!\n" + e + " ", "TicTacToe® : Violation", JOptionPane.ERROR_MESSAGE);
    
    			//terminate the application and indicate exit with error on the console
    			System.exit(1);
    		}
    	}
    	//end of the Constructor for the class MainMenu
    /*-------------------------------------------------------------------------------------*/
    	//adding Action Listeners for the menu items
    	public void addActionListener(ActionListener listener)
    	{
    		jmiNewGame.addActionListener(listener);
    		jmiGameStats.addActionListener(listener);
    		jmiGameOptions.addActionListener(listener);
    		jmiGameQuit.addActionListener(listener);
    		jmiAbout.addActionListener(listener);
    	} 
    	//End addActionListener
    /*-------------------------------------------------------------------------------------*/
    } //End class MainMenu
    
    /*
    |--------------------------------------------------------|
    |					   TicTacToe®	          			 |
    |--------------------------------------------------------|
    |             This is the class that implements			 |
    |               the game of Crosses & Naughts.       	 |
    |--------------------------------------------------------|
    | Author: panagip					 |
    | Date  : May 26th 2013   								 |
    |--------------------------------------------------------|
    */
    /*-------------------------------------------------------------------------------------*/
    //importing necessary libraries
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    /*-------------------------------------------------------------------------------------*/
    //creating the main class for the game
    public class Game extends JPanel implements MouseListener
    {
    	//declaring variables
    	private JFrame frOwner = null;
    	private boolean isSingleGame; //keeping track on game type (Human vs Human OR Human vs Computer)
    	private boolean gameOver;     //keeping track on the game result (win or loss)
    	private String  player;       //keeping track of the current player
    
    	//declaring the control components
    	private Panel  board    = new Panel();       //to hold the nine cells, and all the rest components
    	private Button [][]cell = new Button [3][3]; //the cells
    
    	//these next two labels provide a border around the cells
    	private Label blankL = new Label(" ");
    	private Label blankR = new Label(" ");
    
    	//the next label provide some info
    	private Label info = new Label("Player X to start game", 1);
    
    	//the next variables are providing the game statistics
    	private int    numOfGames = 0;  //number of games played
    	private int    wins = 0;        //number of wins 
    	private int    draws = 0;       //number of draws
    	private double winPercent = 0;  //percentage of the wins
    	private double drawPercent = 0; //percentage of the draws
    	private int    playerXwin = 0;  //number of wins for X
    	private int    playerXloss = 0; //number of losses for X
    	private int    playerOwin = 0;  //number of wins for O
    	private int    playerOloss = 0; //number of losses for O
    /*-------------------------------------------------------------------------------------*/
    	//creating the Constructor of the class
    	public Game(JFrame owner, boolean bSingleG)
    	{
    		frOwner = owner;
    		isSingleGame = bSingleG;
    
    		try //try to process the following code
    		{
    			//game is not over yet
    			gameOver = false;
    
    			//player X to start the game
    			player = "X"; 
    
    			//setup the board panel as a grid table of 3 by 3
    			board.setLayout(new GridLayout(3,3)); 
    
    			//add the 9 buttons on the board panel
    			for (int i = 0; i<3; i++)
    			{
    				for (int j=0; j<3; j++)
    				{
    					cell[i][j] = new Button();          //create the buttons
    					cell[i][j].addMouseListener(this); //add action listeners to the buttons
    					board.add(cell[i][j]);              //positioning the buttons on the panel
    				}
    			}
    		}
    		catch(Exception e) //if there is an error capture it and display it to the user
    		{
    			//print the error on the console
    			e.printStackTrace();
    
    			//display the error to the user
                JOptionPane.showMessageDialog(this,"System error occured!\n" + e + " ", "TicTacToe® : Violation", JOptionPane.ERROR_MESSAGE);
    
    			//terminate the application and indicate exit with error on the console
    			System.exit(1);
    		}
    	/*-------------------------------------------------------------------------------------*/
    		//setup the layout of the panel(class TicTacToe extends JPanel)
    		setLayout(new BorderLayout());
    		
    		//positioning the components on the panel
    		add(blankR,   BorderLayout.EAST  ); //a border
    		add(board,    BorderLayout.CENTER); //the board with the cell buttons
    		add(blankL,   BorderLayout.WEST  ); //a border
    		add(info,     BorderLayout.SOUTH ); //the information label
    	}
    /*-------------------------------------------------------------------------------------*/
    	//actions happening on the game when the mouse is clicked
    	public void mouseClicked(MouseEvent e)
    	{
    		//mouse click on the cells
    		if(!gameOver) //process mouse click only if game is not over
    		{
    			for(int col=0; col<3; col++)
    			{
    				for (int row=0; row<3; row++)
    				{
    					if (e.getSource()==cell[col][row])
    					{
    						processEvent(col,row); //call method to process the event of mouse click on the buttons
    					}
     				}
    			}
    		}
    	}
    
    	public void mousePressed(MouseEvent e)
    	{
    	}
    	public void mouseReleased(MouseEvent e)
    	{
    	}
    	public void mouseEntered(MouseEvent e)
    	{
    	}
    	public void mouseExited(MouseEvent e)
    	{
    	}
    	//end mouse click actions
    /*-------------------------------------------------------------------------------------*/
    	//method to process a given button mouse click
    	private void processEvent(int col, int row)
    	{
    		//method that checks whether cells are full or not 
    		if(!fullBoard())
    		{ //if cells are not full then
    			//method that checks whether player attempts to move into an occupied cell
    			if (cell[col][row].getLabel().equals("X") || cell[col][row].getLabel().equals("O"))
    			{
    				JOptionPane.showMessageDialog(null, "This cell is already taken!!", "TicTacToe® : Warning", JOptionPane.WARNING_MESSAGE);
    			}
    			else
    			{
    				//change button label to current player
    				cell[col][row].setLabel(player);
    				//check whether these moves results in game over
    				if(hasWon(col,row)) //process game over upon a victory
    				{
    					if(player.equals("X")) //if player X win
    					{
    						//show a corresponding message to the user
    						JOptionPane.showMessageDialog(null, "Player " + player + " has won!", "TicTacToe® : Win", JOptionPane.INFORMATION_MESSAGE);
    						//increase player's X win variable value by 1
    						playerXwin++;
    						//increase player's O loss variable value by 1
    						playerOloss++;
    					}
    					else //if player O win
    					{
    						//show a corresponding message to the user
    						JOptionPane.showMessageDialog(null, "Player " + player + " has won!", "TicTacToe® : Win", JOptionPane.INFORMATION_MESSAGE);
    						//increase player's O win variable value by 1
    						playerOwin++;
    						//increase player's X loss variable value by 1
    						playerXloss++;
    					}
    					//increase the wins by 1
    					wins++;
    					//terminate game session
    					gameOver = true;
    					//ask user to start a new session
    					playAgain();
    				}
    				else//process game not over
    				{
    					//toggle player
    					if (player.equals("X"))
    					{
    						player = "O";
    					}
    					else
    					{
    						player = "X";
    					}
    					//provide the user an information who's turn is next
    					info.setText("Player " + player + " to do next move");
    				}
    			}
    		}
    		else
    		{ //if cells are full and there's not a game over occured then
    			//process game over upon a draw
    			//show a corresponding message to the user
    			JOptionPane.showMessageDialog(null, "That's a draw!", "TicTacToe® : Draw", JOptionPane.INFORMATION_MESSAGE);
    			//increase the draws by 1
    			draws++;
    			//terminate game session
    			gameOver = true;
    			//ask user to start a new session
    			playAgain();
    		}
    	}
    	//end mouse click
    /*-------------------------------------------------------------------------------------*/
    	public void NewGame()
    	{
    		if (!gameOver)
    		{
    			QuitGameInProgress();
    		}
    		else
    		{
    			gameOver  = false;
    			isSingleGame = true;
    			clearCells();
    		}
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method to process a new game session
    	private void playAgain()
    	{
    		String msgPlay = "Would you like to start a new game?";
    		String msgConf = "";
    
    		if (isSingleGame == true)
    		{
    			msgConf = "TicTacToe® : New game against Human";
    		}
    		else
    		{
    			msgConf = "TicTacToe® : New game against Computer";
    		}
    
    		int answer = JOptionPane.showConfirmDialog(null, msgPlay, msgConf, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    		if (answer == JOptionPane.YES_OPTION)
    		{
    			gameOver = false;
    			clearCells();
    		}
    		else
    		{
    			gameOver = true;
    			clearCells();
    			info.setText("To start new game go to menu Game > New...");
    		}
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method to process a new game session while a game is in progress
    	private void QuitGameInProgress()
    	{
    		if(gameOver==true)
    		{
    			gameOver = false;
    			clearCells();
    		}
    		else
    		{
    			String msgPlay = "What would you do with the game in progress?";
    			String msgConf = "TicTacToe® : New game against Human";
    			Object[] choice = { "Quit & start new game(counts as a draw in stats)", "Continue playing" };
    			Object selection = JOptionPane.showInputDialog(null, msgPlay, msgConf,
    				JOptionPane.QUESTION_MESSAGE, null, choice, choice[0]);
    				
    			if (selection == "Quit & start new game(counts as a draw in stats)")
    			{
    				gameOver = false;
    				clearCells();
    				draws++;
    			}
    			else
    			{
    				gameOver = false;
    			}
    		}
    
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method to process game termination
    	public void Quit()
    	{
    		int answer;
    		String msgQuit = "Are you certain you wish to quit?";
    		String msgQuitTitle =  "TicTacToe® : Quit";
    
    		answer = JOptionPane.showConfirmDialog(this, msgQuit, msgQuitTitle, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    		if (answer == JOptionPane.YES_OPTION)
    		{
    			gameOver = true;
    			System.exit(0);
    		}
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method to process game's about info
    	public void About()
    	{
    		String title = "TicTacToe® : About";
    		String info = "TicTacToe® is an application\nthat illustrates the game of\nCrosses & Naughts in Java.\n\n";
    		String details = "Authoring, designing,\nand programming by\npanagip\n";
    		String information = info + details;
    		JOptionPane.showMessageDialog(null, information, title, JOptionPane.INFORMATION_MESSAGE);
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method that provides game statistics
    	public void gameStats()
    	{
    		numOfGames = wins + draws;
    		if(numOfGames != 0)
    		{
    			if(wins != 0)
    			{
    				if(draws != 0)
    				{
    					winPercent =(double) Math.floor(((wins * 100) / numOfGames));
    					drawPercent =(double) Math.floor(((draws * 100) / numOfGames));
    				}
    				else
    				{
    					winPercent = 100;
    				}
    			}
    			else
    			{
    				drawPercent = 100;
    			}
    		}		
    		String title = "TicTacToe® : Game Statistics";
    		String games = "Games played  : " + numOfGames + "\n";	
    		String won = "Games won       : " + wins + "      Percentage : " + winPercent + "%\n";
    		String drawn = "Games drawn   : " + draws + "      Percentage : " + drawPercent + "%\n\n";
    		String playerX = "Player X \n                   wins : " + playerXwin + "    losses : " + playerXloss + " \n";
    		String playerO = "Player O \n                   wins : " + playerOwin + "    losses : " + playerOloss + " \n";
    		String total = games + won + drawn + playerX + playerO;
    		JOptionPane.showMessageDialog(null, total, title, JOptionPane.INFORMATION_MESSAGE);
    	}
    /*-------------------------------------------------------------------------------------*/
    	//worker method to clear cells for rematch
    	public void clearCells()
    	{
    		//set initial player for the new game
    		info.setText("Player " + player + " to start game");
    		//clear all the cells
    		for (int i = 0; i<3; i++)
    		{
    			for (int j=0; j<3; j++)
    			{
    				cell[i][j].setLabel("");
    				cell[i][j].setEnabled(true);
    			}
    		}
    	}
    /*-------------------------------------------------------------------------------------*/
       //worker method that checks whether cells are full
    	public boolean fullBoard()
    	{
    		for(int col=0 ; col<3 ; col++)
    		{
    			for(int row=0 ; row<3 ; row++)
    			{
    				if(cell[col][row].getLabel().equals(""))
    				{
    					return false;
    				}
    			}
    		}
    		return true;
        }
    /*-------------------------------------------------------------------------------------*/
    	//worker method to check if game over upon a victory
    	private boolean hasWon(int i, int j)
    	{
    		boolean won = true;
    		//check current column if all the squares are filled with the same symbol
    		for (int col=0; col<3; col++)
    		{
    			if(!cell[i][col].getLabel().equals(player))
    			{
    				won = false;
    			}
    		}
    		if (!won)
    		{
    			//check current row if all the squares are filled with the same symbol
    			won = true;
    			for(int row = 0; row<3; row++)
    			{
    				if(!cell[row][j].getLabel().equals(player))
    				{
    					won = false;
    				}
    			}
    		}
    		if(!won)
    		{
    			//check left diagonal if all the squares are filled with the same symbol
    			won = true;
    			for(int num=0; num<3; num++)
    			{
    				if(!cell[num][num].getLabel().equals(player))
    				{
    					won = false;
    				}
    			}
    		}
    		if (!won)
    		{
    			//check right diagonal if all the squares are filled with the same symbol
    			won = true;
    			for(int num = 0; num<3; num++)
    			{
    				if (!cell[2-num][num].getLabel().equals(player))
    				{
    					won = false;
    				}
    			}
    		}
    		return won;
    	}
    }
    
    /*
    |--------------------------------------------------------|
    |					   TicTacToe®	          			 |
    |--------------------------------------------------------|
    |             This is the class that implements			 |
    |              the main game of Tic Tac Toe  			 |
    |--------------------------------------------------------|
    | Author: panagip					 |
    | Date  : May 26th 2013   								 |
    |--------------------------------------------------------|
    */
    /*-------------------------------------------------------------------------------------*/
    //importing necessary libraries
    import java.util.*;
    //Graphics
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TicTacToe extends JFrame implements ActionListener
    {
    /*-------------------------------------------------------------------------------------*/
    	//Message Box buttons standards
    	final int YES_NO = 0;
    	final int OK = 1;
    
    	boolean bSingleGame = true; //false: Human vs Human || true : Human vs CPU
    	
    	MainMenu theMenu = new MainMenu();
    	
    	Game panelGame = new Game(this,	bSingleGame);
    /*-------------------------------------------------------------------------------------*/
    	//Constructor
    	public TicTacToe()
    	{
    		super("TicTacToe®");
    		setLocation(new Point(300,200));
    		//Adding menu
    		setJMenuBar(theMenu);
    
    		getContentPane().add(panelGame);
    
    		//Adding action listener to the menu
    		theMenu.addActionListener(this);
    
    		setSize(350,300);
    
    		setVisible(true);
    
    		setResizable(false);
    
    		//In order to terminate the utility
    		addWindowListener(new WindowAdapter()
    		{
    			public void windowClosing(WindowEvent e)
    			{
    				System.exit(0);
    			}
    		});
    
    	} //End construtor 
    /*-------------------------------------------------------------------------------------*/
    	//Menu Action handlerer
    	public void actionPerformed(ActionEvent e)
    	{
    		//Menu actions
    		JMenuItem itemClicked = (JMenuItem)e.getSource();
    		
    		//New game
    		if (itemClicked == theMenu.jmiNewGame)
    		{
    			panelGame.NewGame();
    		}
    
    		//Statistics
    		if (itemClicked == theMenu.jmiGameStats)
    		{
    			panelGame.gameStats();
    		}
    
    		//Options
    		if (itemClicked == theMenu.jmiGameOptions)
    		{
    			//Constructing the options dialog
    			OptionsDialog dlg = new OptionsDialog(this,	bSingleGame);
    			dlg.show();
    			if (dlg.btnClicked)
    			{
    				//If the player change the type of the game
    				//start a new game
    				bSingleGame = dlg.isSingleGame;
    				panelGame.clearCells();
    			}
    		}
    
    		//Quit
    		if (itemClicked == theMenu.jmiGameQuit)
    		{
    			panelGame.Quit();
    		}
    
    		//About
    		if (itemClicked == theMenu.jmiAbout)
    		{
    			panelGame.About();
    		}
    	}
    /*-------------------------------------------------------------------------------------*/
    	public static void main(String args[])
    	{
    		//Utility object
    		TicTacToe client = new TicTacToe();
    	} //End main
    /*-------------------------------------------------------------------------------------*/
    }
    Last edited by JosAH; 05-30-2013 at 07:29 PM. Reason: added [code] ... [/code] tags

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,801
    Rep Power
    25

    Default Re: game of Crosses & Naughts - problem with the menu

    Post moved to own thread.

    please tell what's wrong
    Can you explain what the problem is? Post what the code currently does and add an explanation of what is wrong and say what you want it to do differently.

    Please edit the post and wrap the code with code tags. See:
    BB Code List - Java Programming Forum - Learn Java Programming
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    panagip is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default Re: game of Crosses & Naughts - problem with the menu

    Quote Originally Posted by Norm View Post
    Post moved to own thread.


    Can you explain what the problem is? Post what the code currently does and add an explanation of what is wrong and say what you want it to do differently.

    Please edit the post and wrap the code with code tags. See:
    BB Code List - Java Programming Forum - Learn Java Programming
    You're right. Sorry.
    When I run the TicTacToe class the game is running as it should, but the only problem is that I cannot see the menu. What do I have to do differently?

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: game of Crosses & Naughts - problem with the menu

    Your MainMenu class is a JMenuBar but it also has a JMenuBar (jmbMain); something must be wrong there ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    panagip is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default Re: game of Crosses & Naughts - problem with the menu

    Yes!! Thanks a million!!! That was it... when I removed that JMenuBar (jmbMain), everything went ok, I can see my menu now!!!
    Thanks Jos!!!

    Kind regards,
    panagip

  6. #6
    panagip is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default Re: game of Crosses & Naughts - problem with the menu

    Hello again!! I hope that you are all fine!!

    I have one more question about my program.When I run the TicTacToe class, the application runs properly. By the time that I start the game(clicking on the buttons that are on the panel (Game panelGame = new Game(this, bSingleGame);)) and then try to access the menu(i.e clicking on Game menu) I cannot see anything at all. Could someone tell what I have done wrong??

    Kind regards,
    panagip

Similar Threads

  1. Java 2D game - creating menu
    By ultimate in forum New To Java
    Replies: 4
    Last Post: 11-18-2012, 02:29 PM
  2. Noughts And Crosses v2 problem with running
    By Razorfc in forum New To Java
    Replies: 7
    Last Post: 03-09-2012, 10:21 AM
  3. Replies: 3
    Last Post: 10-18-2011, 02:04 AM
  4. Menu Help in TicTacToe Game
    By Ryan10 in forum New To Java
    Replies: 59
    Last Post: 04-04-2011, 06:19 AM
  5. Need help with a menu button in a game
    By pjr5043 in forum Java Applets
    Replies: 1
    Last Post: 12-07-2008, 10:30 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
  •