Solved

SetMenonics in my Java game

Posted on 2004-08-30
22
274 Views
Last Modified: 2010-05-18


I want to be able to press a key for three options in the game could anyone provide the solution.  

I want to be able to press "s" to start the game and also to press "q" to quit the game  and to press "p" to pause my game.

Heres the latst code for it, nb I do not have a menuitem for Pause yet :)

import java.awt.* ;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;
import java.applet.AudioClip;
import java.applet.Applet;
import java.net.URL;

/**
 *   Main Game Frame window called JaySnake
 */

public class JaySnake extends JFrame implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
          private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;

/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);
     public int waitTime = 75;

/*Method used to get text from background menu items and set background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("backgrounds/default")) //Sets background to default image
          {
                    backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/sand.jpg" ) );
         }

         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/blueGlass.jpg" ) );
         }
         else //Sets to default if none mathced
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
     }

    public Game()
    {

  /******Try read in default backgroundImage file and catch any exception*/
      try //first read in default image
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
            clip = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/music.au"));
            appleEaten = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/apple.au"));
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }

      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

     public void paint( Graphics g )
    {
            super.paint(g);
        g.drawImage(backgroundImage,0,0,null);

          //Draw green scoreboard and black rects
        g.setColor(Color.black);
        g.fillRect(1,540,598,20);
        g.fillRect(1,34,598,6);
        g.setColor(Color.white);
        g.drawRoundRect(1,0,598,32,10,10);

          //Calls Snake paint method
          if (snake != null)
             snake.draw(g);

    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        //startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        //elapsedTime = System.currentTimeMillis() - startTime ;
        //waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
               Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }


  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 610 ;
  private static final int DISPLAY_H = 610 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
 
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;
 
  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    setResizable( false ) ;
    game = new Game();
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );
                  menubar.add( gameMenu ) ;
                  gameMenu.setIcon(new ImageIcon("menuicons/start.gif"));
    gameMenu.add( gameStart ) ;
    gameStart.setIcon(new ImageIcon("menuicons/play.gif"));
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){

          public void actionPerformed( ActionEvent e )
          {
             String name = new String();
             name = JOptionPane.showInputDialog( "Please enter your name" );
             snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
          }
     });

    gameMenu.add( gameQuit ) ;
    gameQuit.setIcon(new ImageIcon("menuicons/quit.gif"));
   
    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent e )
         {
             System.exit( 0 );
          }
     });
   
/*Background selection menubar setup adding actionlisteners*/
    menubar.add( bgMenu ) ;
    bgMenu.setIcon(new ImageIcon("menuicons/backgrounds.gif"));
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
         bgGroup.add( bg1 );      bgGroup.add( bg2 );
         bgGroup.add( bg3 );        bgGroup.add( bg4 );

     /*Sounds menubar selection with actionListeners*/
    menubar.add( soundMenu );
    soundMenu.setIcon(new ImageIcon("menuicons/speaker.gif"));
    soundMusic.setState(true);
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

    soundSound.setState(true);

     /* Listeners */
     soundMusic.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         System.out.println(source.getText());
                         if (source.getState())
                         {
                              clip.loop();
                         }
                         else
                         {
                              clip.stop();
                         }

                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });

     soundSound.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         if (source.getState())
                         {
                                   soundForApple = true;
                                   snake.setAppleSound(appleEaten);
                         }
                         else
                         {
                                   soundForApple = false;
                                   snake.setAppleSound(null);
                         }
                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
     /* /Listeners */

    menubar.add( helpMenu ) ;
    helpMenu.setIcon(new ImageIcon("menuicons/helpmenu.gif"));
    helpMenu.add( userInstruct );
    userInstruct.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("Instructions button pressed");
                //Create new Jframe to view User instructions
                JFrame f = new JFrame();
                JEditorPane p = new JEditorPane("text/html", "");
                f.getContentPane().add(p); // was missing in the previous code snippet
                p.setEditable(false);
                URL instructions = getClass().getResource("instructions/index.html");
                try {
                    p.setPage(instructions);
                }
               
                catch (Exception ep) {
                   
                    System.out.println("Not Got index.html");
                }

                f.setSize(265, 540);
                f.setVisible(true);
               
               
            }                      
        });
       
       
    helpMenu.add( helpAbout );
    helpAbout.addActionListener( new ActionListener(){
             public void actionPerformed( ActionEvent e )
     {
//Create an instance of About class window
                   About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
    }
     } ) ;

    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
  }

  public void actionPerformed(ActionEvent e)
  {
     try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

     public void playMusic()
     {
          clip.loop();

     }

  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }

//**************************Main method *************************************
       public static void main(String [] arguments)
     {
         System.out.println( "Starting JaySnake........" ) ;
         final JaySnake app = new JaySnake() ;

//Sets the location on screenof the JFrame behind the splash screen
         app.setLocation(210, 80);

         app.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent keyevent) {
                //System.out.println("Test key press >>>>>>>>>>>>>>>>>>>>>>>>>>");
                app.snake.keyPressed(keyevent);
            }
        });
         app.setSize( DISPLAY_W, DISPLAY_H ) ;
         app.setTitle( "JaySnake Game" ) ;
         app.setVisible( true ) ;
         Splash splash = new Splash(app);

         new Thread(new Runnable()
              {
                   public void run()
                   {
                           try
                           {
                             app.playMusic();
                             Thread.sleep(200);
                        }
                        catch (InterruptedException e)
                        {
                             System.out.println(e);
                        }
                   }
              }).start();
    }

/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

/*Draw scoreboard and player details, sets color for score and player
 *fills rectangle and text white and draws another rectangle that is used
 *to highlight the playing area*/
      g.setColor( Color.black ) ;      /*sets color to black*/
      g.fillRect( 0, 0, 598, 32 ) ; /*fillsRectangle for scoreboard*/
      g.setColor( Color.white ) ;   /*sets color to white for text*/
/*Draws text and uses score variables*/
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      //g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;


    }

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private Snake snake = null;
/* The musicclip to be played.*/
  private AudioClip clip = null;
/* The sound of the applet when eaten.*/
  private AudioClip appleEaten = null;
// Indicate if we want sound for eating the apple (options = true/false)
  private boolean soundForApple = true;
}
0
Comment
Question by:pjcrooks2000
  • 7
  • 7
  • 5
  • +1
22 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11931772
You just need to bind your menu item to an action, e.g.

gameStart.getInputMap().put(KeyStroke.getKeyStroke("control S"), "actionStart");


gameStart.getActionMap().put("actionStart",
        new AbstractAction("actionStart") {
            public void actionPerformed(ActionEvent evt) {
                // run the game
            }
        }
);
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11931814
CEHJ, he's not talking about Ctrl+S but just about pressing S
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11931834
Yes just about s.. :)  not a ctrl combination.   Just a single hot key please cheers :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11931906
>>Yes just about s.. :)  not a ctrl combination.  

Slightly strange way to control programs, but, a simple change is all that's required:

gameStart.getInputMap().put(KeyStroke.getKeyStroke("s"), "actionStart");
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11931915
... But maybe

   gameStart.getInputMap().put(KeyStroke.getKeyStroke('S'), "actionStart");
   gameStart.getInputMap().put(KeyStroke.getKeyStroke('s'), "actionStart");

also works.

(I would take uppercase S and lower case s to make it work for both)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11931934
>> gameStart.getInputMap().put(KeyStroke.getKeyStroke("s"), "actionStart");

That should be

    gameStart.getInputMap().put(KeyStroke.getKeyStroke("typed s"), "actionStart");
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11931966
>>That should be
Well,...

The Java doc says:

     If typed, pressed or released is not specified, pressed is assumed.

So, it will work.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11932018
Where in my code should I put that ?  muchees thank you!
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11932073
In your JaySnake constructor where you now have gameStart.addActionListener(....
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11932143
So, you replace

    gameStart.addActionListener( new ActionListener(){

          public void actionPerformed( ActionEvent e )
          {
             String name = new String();
             name = JOptionPane.showInputDialog( "Please enter your name" );
             snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
          }
    });

by

    gameStart.getInputMap().put(KeyStroke.getKeyStroke("typed S"), "actionStart");
    gameStart.getInputMap().put(KeyStroke.getKeyStroke("typed s"), "actionStart");

    gameStart.getActionMap().put("actionStart",
        new AbstractAction("actionStart") {
            public void actionPerformed(ActionEvent evt) {
               String name = JOptionPane.showInputDialog( "Please enter your name" );
               snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
            }
        }
);
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11932184
Nope zzynx that does not work :(

even the menu does not work after replacing it with that snippet !  
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 86

Expert Comment

by:CEHJ
ID: 11932270
Are you getting the dialog shown?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11932327
>> Nope zzynx that does not work :(
Sorry. I'm afraid I'm still in vacation mood.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11932351
Heh!  Keep trying :)  I am sure you will be in "the need for a vacation mood" some time soon !
0
 
LVL 35

Expert Comment

by:girionis
ID: 11933019
Right this is the JaySnake class with q for quit, s for start and p for pause:

import java.awt.* ;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;
import java.applet.AudioClip;
import java.applet.Applet;
import java.net.URL;

/**
 *   Main Game Frame window called JaySnake
 */

public class JaySnake extends JFrame implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
          private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;

/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);
     public int waitTime = 75;

/*Method used to get text from background menu items and set background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("backgrounds/default")) //Sets background to default image
          {
                    backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/sand.jpg" ) );
         }

         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/blueGlass.jpg" ) );
         }
         else //Sets to default if none mathced
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
     }

    public Game()
    {

  /******Try read in default backgroundImage file and catch any exception*/
      try //first read in default image
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
            clip = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/music.au"));
            appleEaten = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/apple.au"));
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }

      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

     public void paint( Graphics g )
    {
            super.paint(g);
        g.drawImage(backgroundImage,0,0,null);

          //Draw green scoreboard and black rects
        g.setColor(Color.black);
        g.fillRect(1,540,598,20);
        g.fillRect(1,34,598,6);
        g.setColor(Color.white);
        g.drawRoundRect(1,0,598,32,10,10);

          //Calls Snake paint method
          if (snake != null)
             snake.draw(g);

    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        //startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        //elapsedTime = System.currentTimeMillis() - startTime ;
        //waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
               Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }


  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 610 ;
  private static final int DISPLAY_H = 610 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
 
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;
 
  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    setResizable( false ) ;
    game = new Game();
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );
                  menubar.add( gameMenu ) ;
                  gameMenu.setIcon(new ImageIcon("menuicons/start.gif"));
    gameMenu.add( gameStart ) ;
    gameStart.setIcon(new ImageIcon("menuicons/play.gif"));
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){

          public void actionPerformed( ActionEvent e )
          {
             String name = new String();
             name = JOptionPane.showInputDialog(JaySnake.this,  "Please enter your name", "Title by Girionis", JOptionPane.QUESTION_MESSAGE );
             snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
          }
     });

    gameMenu.add( gameQuit ) ;
    gameQuit.setIcon(new ImageIcon("menuicons/quit.gif"));
   
    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent e )
         {
             System.exit( 0 );
          }
     });
   
/*Background selection menubar setup adding actionlisteners*/
    menubar.add( bgMenu ) ;
    bgMenu.setIcon(new ImageIcon("menuicons/backgrounds.gif"));
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
         bgGroup.add( bg1 );      bgGroup.add( bg2 );
         bgGroup.add( bg3 );        bgGroup.add( bg4 );

     /*Sounds menubar selection with actionListeners*/
    menubar.add( soundMenu );
    soundMenu.setIcon(new ImageIcon("menuicons/speaker.gif"));
    soundMusic.setState(true);
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

    soundSound.setState(true);

     /* Listeners */
     soundMusic.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         System.out.println(source.getText());
                         if (source.getState())
                         {
                              clip.loop();
                         }
                         else
                         {
                              clip.stop();
                         }

                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });

     soundSound.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         if (source.getState())
                         {
                                   soundForApple = true;
                                   snake.setAppleSound(appleEaten);
                         }
                         else
                         {
                                   soundForApple = false;
                                   snake.setAppleSound(null);
                         }
                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
     /* /Listeners */

    menubar.add( helpMenu ) ;
    helpMenu.setIcon(new ImageIcon("menuicons/helpmenu.gif"));
    helpMenu.add( userInstruct );
    userInstruct.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("Instructions button pressed");
                //Create new Jframe to view User instructions
                JFrame f = new JFrame();
                JEditorPane p = new JEditorPane("text/html", "");
                f.getContentPane().add(p); // was missing in the previous code snippet
                p.setEditable(false);
                URL instructions = getClass().getResource("instructions/index.html");
                try {
                    p.setPage(instructions);
                }
               
                catch (Exception ep) {
                   
                    System.out.println("Not Got index.html");
                }

                f.setSize(265, 540);
                f.setVisible(true);
               
               
            }                      
        });
       
       
    helpMenu.add( helpAbout );
    helpAbout.addActionListener( new ActionListener(){
             public void actionPerformed( ActionEvent e )
     {
//Create an instance of About class window
/*                   About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
                   */
    }
     } ) ;

    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
   
    this.addKeyListener(new MyKeyListener());
  }

  public void actionPerformed(ActionEvent e)
  {
     try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

     public void playMusic()
     {
          clip.loop();

     }

  public void start()
  {
    gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }

//**************************Main method *************************************
       public static void main(String [] arguments)
     {
         System.out.println( "Starting JaySnake........" ) ;
         final JaySnake app = new JaySnake() ;

//Sets the location on screenof the JFrame behind the splash screen
         app.setLocation(210, 80);

         app.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent keyevent) {
                //System.out.println("Test key press >>>>>>>>>>>>>>>>>>>>>>>>>>");
                app.snake.keyPressed(keyevent);
            }
        });
         app.setSize( DISPLAY_W, DISPLAY_H ) ;
         app.setTitle( "JaySnake Game" ) ;
         app.setVisible( true ) ;
         Splash splash = new Splash(app);

         new Thread(new Runnable()
              {
                   public void run()
                   {
                           try
                           {
                             app.playMusic();
                             Thread.sleep(200);
                        }
                        catch (InterruptedException e)
                        {
                             System.out.println(e);
                        }
                   }
              }).start();
    }


      
// *****************************************
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
              

            // Check for key characters.
            if (evt.getKeyChar() == 's' || evt.getKeyChar() == 'S') {
                System.out.println("s");
                String name = new String();
                   name = JOptionPane.showInputDialog(JaySnake.this,  "Please enter your name", "Title by Girionis", JOptionPane.QUESTION_MESSAGE );
                   snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
                   gamePlay.resume();
            }
            else if (evt.getKeyChar() == 'p' || evt.getKeyChar() == 'P') {
                System.out.println("p");
                gamePlay.suspend();
                /*
                try
                {
                      
                      //gamePlay.wait();
                }
                catch (InterruptedException ie)
                {
                      System.out.println(ie);
                }
                */
            }
                else if (evt.getKeyChar() == 'q' || evt.getKeyChar() == 'Q') {
                System.out.println("q");
                System.exit( 0 );
            }
            else
            {
                  gamePlay.resume();
            }
            /*
            // Check for key codes.
            if (evt.getKeyCode() == KeyEvent.VK_HOME) {
                System.out.println(evt.getKeyCode());
            }*/
        }
    }
// *****************************************

/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

/*Draw scoreboard and player details, sets color for score and player
 *fills rectangle and text white and draws another rectangle that is used
 *to highlight the playing area*/
      g.setColor( Color.black ) ;      /*sets color to black*/
      g.fillRect( 0, 0, 598, 32 ) ; /*fillsRectangle for scoreboard*/
      g.setColor( Color.white ) ;   /*sets color to white for text*/
/*Draws text and uses score variables*/
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      //g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;


    }

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private Snake snake = null;
/* The musicclip to be played.*/
  private AudioClip clip = null;
/* The sound of the applet when eaten.*/
  private AudioClip appleEaten = null;
// Indicate if we want sound for eating the apple (options = true/false)
  private boolean soundForApple = true;
}

Things to notice.

1) I am using a deprectaed API, suspend() and resume(). Instead I should be using wait()/notify(), but I had an illegal access exception, this is due to not holding a monitor to the thread I am trying to access. I am off for a drink soon so I do not have time to look into it but I promise I will try to fix it as soon a I get back. I will try to make it work with wait()/notify().
0
 
LVL 35

Expert Comment

by:girionis
ID: 11933041
2) (I forgot about that). The "p" key is to pause the game. Press any other key to resume apart from "p". Pressing the "p" key will keep pausing the game. If you want we can look at it again and try to make the game resume by pressing any key ("p" including). I had some problems making it resume/start again with "p". I added a boolean flag but this didn't seem to work. I'd say leave it as it is for the time being and I will also try to make it pause/resume by pressing the "p" key again.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11933495
Well that certainly works, fantastic girionis!  Good job....  

I will hold fire on the accepted answer until you resolve the depreciated API problem... cheers sport :)
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 11939899
Ok here are the latest changes that work with wait()/notify().

First of all I added a variabel called "pause" what indicates whether the game should pause or not. I added it at the end of the JaySnake class, where you have the rest of the variables:

protected boolean pause = false;

Then I added some synchronization and if code inside the run() method of your Game class. This code waits as soon as the "p" key is pressed (and the pause variable becomes true). So the run() method of your Game class becomes:

public void run()
    {
     
      while( running )
      {
              if (pause)
            {
                  try
                  {
                        synchronized (this)
                        {
                              wait();
                        }
                  }
                  catch (InterruptedException ie)
                  {
                        System.out.println(ie);
                  }
            }
            
        //startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        //elapsedTime = System.currentTimeMillis() - startTime ;
        //waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
               Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }


The wait() method releases the lock to the Game class and pauses it. It then waits for a notification in order to obtain it again.

Now we need a way to notify the waiting thread that we want to play the game again. I added some code in the MyKeyListener class that does this so the MyKeyListener class becomes:

class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
   
/*do character checks if else statements*/
            if (evt.getKeyChar() == 's' || evt.getKeyChar() == 'S') {
                System.out.println("s");
                //JOptionPane.showMessageDialog(null, "Game start shortcut invoked");
                String name = new String();
                  name = JOptionPane.showInputDialog(JaySnake.this,  "Please enter your name", "Player name input box", JOptionPane.QUESTION_MESSAGE );
                  snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
                         
                          synchronized (game)
                          {
                                pause = false;
                                game.notify();
                          }
            }
            else if (evt.getKeyChar() == 'p' || evt.getKeyChar() == 'P') {
                System.out.println("p");
                        pause = true;
            }
              else if (evt.getKeyChar() == 'q' || evt.getKeyChar() == 'Q') {
                System.out.println("q");
                System.exit( 0 );
            }
            else
            {
                        synchronized (game)
                          {
                                pause = false;
                                game.notify();
                          }
            }
           
        }
    }

You notice that I got rid of the JOptionPane messages. Just add them again if you really need them. On any key press apart from "p" or "q" the listener notifies the Game class to continue.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11939957
Another thing you can do since synchronizing is expensive you coudl add an if statement thatchecks whether the game is paused. Only if it is then you call the notify():

/*KeyListener to chck for keys being pressed*/
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
   
/*do character checks if else statements*/
            if (evt.getKeyChar() == 's' || evt.getKeyChar() == 'S') {
                System.out.println("s");
                //JOptionPane.showMessageDialog(null, "Game start shortcut invoked");
                String name = new String();
                  name = JOptionPane.showInputDialog(JaySnake.this,  "Please enter your name", "Player name input box", JOptionPane.QUESTION_MESSAGE );
                  snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
                         
                          if (pause)
                          {
                              synchronized (game)
                              {
                                    pause = false;
                                    game.notify();
                              }
                         }
            }
            else if (evt.getKeyChar() == 'p' || evt.getKeyChar() == 'P') {
                System.out.println("p");
                        pause = true;
            }
              else if (evt.getKeyChar() == 'q' || evt.getKeyChar() == 'Q') {
                System.out.println("q");
                System.exit( 0 );
            }
            else
            {
                        if (pause)
                        {
                              synchronized (game)
                              {
                                    pause = false;
                                    game.notify();
                              }
                        }
            }
           
        }
    }
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11941315
Fantastic g it works:::

Here is the code for all who wish to know in the future

/*Class name:           JaySnake
 *Author:                 Patrick Crooks
 *Course:                  Bsc hons + HND
 *Module title:        Java Programming and animation
 *Module number:      LCT 3006
 *Assignment no:      Assignment 2
 *Tutor:                  Poppy Pickard
 *Due date:                  28/08/04
 */


import java.awt.* ;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;
import java.applet.AudioClip;
import java.applet.Applet;
import java.net.URL;

/**
 *   Main Game Frame window called JaySnake
 */

public class JaySnake extends JFrame implements
ActionListener
{
  class Game extends JPanel implements Runnable
  {
   
/*Method used to get text from background menu items and set
background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("backgrounds/default")) //Sets background to default image
          {
                    backgroundImage = ImageIO.read( new File("backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                   backgroundImage = ImageIO.read( new File("backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sandimage
         {
                  backgroundImage = ImageIO.read( new File("backgrounds/sand.jpg" ) );
         }

         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                  backgroundImage = ImageIO.read( new File("backgrounds/blueGlass.jpg" ) );
         }
         else //Sets to default if none mathced
         {
                   backgroundImage = ImageIO.read( new File("backgrounds/default.jpg" ) );
         }
     }

    public Game()
    {

/*Try read in default backgroundImage file and sound files
and catch any exception*/
      try
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg"
) );
            clip = Applet.newAudioClip(new URL("file:" +
System.getProperty("user.dir") + "/sounds/music.au"));
            appleEaten = Applet.newAudioClip(new URL("file:" +
System.getProperty("user.dir") + "/sounds/apple.au"));
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }

      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H,
BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

/*set up the menubar*/
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

     public void paint( Graphics g )
    {
            super.paint(g);
        g.drawImage(backgroundImage,0,0,null);

//Draw green scoreboard and black rects
        g.setColor(Color.black);
        g.fillRect(1,540,598,20);
        g.fillRect(1,34,598,6);
        g.setColor(Color.white);
        g.drawRoundRect(1,0,598,32,10,10);

          //Calls Snake paint method
          if (snake != null)
             snake.draw(g);

    }

    public void run()
    {
     
      while( running )
      {
            if (pause)
          {
               try
               {
                    synchronized (this)
                    {
                         wait();
                    }
               }
               catch (InterruptedException ie)
               {
                    System.out.println(ie);
               }
          }
         
        //startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        //elapsedTime = System.currentTimeMillis() - startTime ;
        //waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
               Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }
      
      private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;

/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);
    public int waitTime = 85;

  }

/******JaySnake constructor*/
  public JaySnake()
  {
    setResizable( false ) ;
    game = new Game();
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );
                  menubar.add( gameMenu ) ;
                  gameMenu.setIcon(new
ImageIcon("menuicons/start.gif"));
    gameMenu.add( gameStart ) ;
    gameStart.setIcon(new ImageIcon("menuicons/play.gif"));
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){

          public void actionPerformed( ActionEvent e )
          {
             String name = new String();
             name = JOptionPane.showInputDialog(JaySnake.this,  "Please enteryour name", "Player Name dialogue",
             JOptionPane.QUESTION_MESSAGE );
             snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten
: null));
          }
     });

    gameMenu.add( gameQuit ) ;
    gameQuit.setIcon(new ImageIcon("menuicons/quit.gif"));
   
    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent e )
         {
             System.exit( 0 );
          }
     });
   
/*Background selection menubar setup adding actionlisteners*/
    menubar.add( bgMenu ) ;
    bgMenu.setIcon(new ImageIcon("menuicons/backgrounds.gif"));
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
         bgGroup.add( bg1 );      bgGroup.add( bg2 );
         bgGroup.add( bg3 );        bgGroup.add( bg4 );

/*Sounds menubar selection with actionListeners*/
    menubar.add( soundMenu );
    soundMenu.setIcon(new ImageIcon("menuicons/speaker.gif"));
    soundMusic.setState(true);
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;
    soundSound.setState(true);

/* Sound menu ActionListeners */
     soundMusic.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source =
(JCheckBoxMenuItem)(e.getSource());
                         
                                    System.out.println(source.getText());
                         if (source.getState())
                         {
                              clip.loop();
                         }
                         else
                         {
                              clip.stop();
                         }

                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
/*Sound menu item action listeners and if statements*/
     soundSound.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source =
(JCheckBoxMenuItem)(e.getSource());
                         if (source.getState())
                         {
                                   soundForApple = true;
                                   snake.setAppleSound(appleEaten);
                         }
                         else
                         {
                                   soundForApple = false;
                                   snake.setAppleSound(null);
                         }
                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
     
    menubar.add( helpMenu ) ;
    helpMenu.setIcon(new ImageIcon("menuicons/helpmenu.gif"));
    helpMenu.add( userInstruct );
    userInstruct.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    System.out.println("Instructions button pressed");
/*Create new Jframe to view User instructions*/
    JFrame f = new JFrame();
         JEditorPane p = new JEditorPane("text/html", "");
    f.getContentPane().add(p); // was missing in the previous code snippet
    p.setEditable(false);
    URL instructions = getClass().getResource("instructions/index.html");
    try {
          p.setPage(instructions);
        }
               
    catch (Exception ep)
    {
       System.out.println("Not Got index.html");
    }
/*size size and position of Instrutions frame f */
    f.setSize(265, 540);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }});
       
       
    helpMenu.add( helpAbout );
    helpAbout.addActionListener( new ActionListener(){
             public void actionPerformed( ActionEvent e )
     {
//Create an instance of About class window
                  About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
(frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
                   
    }
     } ) ;
/* create window closing event for About window*/
    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
   
    this.addKeyListener(new MyKeyListener());
  }

  public void actionPerformed(ActionEvent e)
  {
     try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }
/*Resize screen method if required*/
  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }
/*Play music method*/
     public void playMusic()
     {
          clip.loop();

     }
/*gamePlay Thread method*/
  public void start()
  {
    gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }

/*Main Method*/
       public static void main(String [] arguments)
     {
         System.out.println( "Starting JaySnake........" ) ;
         final JaySnake app = new JaySnake() ;
/*Sets the location to the centre of the screen relative to
screensixe*/
         app.setLocationRelativeTo(null);
/*snake key event adapter*/
         app.addKeyListener(new KeyAdapter() {
           public void keyPressed(KeyEvent keyevent) {
         app.snake.keyPressed(keyevent);
            }
        });
/*set frame size title and visibility*/
         app.setSize( DISPLAY_W, DISPLAY_H ) ;
         app.setTitle( "JaySnake Game" ) ;
         app.setVisible( true ) ;
             app.start();
/*show splash screen*/
         Splash splash = new Splash(app);

         new Thread(new Runnable()
              {
                   public void run()
                   {
                           try
                           {
                             app.playMusic();
                             Thread.sleep(200);
                        }
                        catch (InterruptedException e)
                        {
                             System.out.println(e);
                        }
                   }
              }).start();
    }

     
/*KeyListener to chck for keys being pressed*/
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
   
/*do character checks if else statements*/
            if (evt.getKeyChar() == 's' || evt.getKeyChar() == 'S') {
                System.out.println("s");
                //JOptionPane.showMessageDialog(null, "Game start shortcut invoked");
                String name = new String();
                  name = JOptionPane.showInputDialog(JaySnake.this,  "Please enter your name", "Player name input box", JOptionPane.QUESTION_MESSAGE );
                  snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
                     
                      if (pause)
                      {
                         synchronized (game)
                         {
                              pause = false;
                              game.notify();
                         }
                     }
            }
            else if (evt.getKeyChar() == 'p' || evt.getKeyChar() == 'P') {
                System.out.println("p");
                    pause = true;
            }
              else if (evt.getKeyChar() == 'q' || evt.getKeyChar() == 'Q') {
                System.out.println("q");
                System.exit( 0 );
            }
            else
            {
                    if (pause)
                    {
                         synchronized (game)
                         {
                              pause = false;
                              game.notify();
                         }
                    }
            }
           
        }
    }

/*Render method for graphics content of background images*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;
    }
   
/*Thread gamePlay created*/
  private Thread gamePlay ;
/*Booleans*/
  private boolean running = true ;
/*Game class declaration*/
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor
/*Display Width and Height constants*/
  private static final int DISPLAY_W = 610 ;
  private static final int DISPLAY_H = 610 ;
/*Integer containers*/
  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;
/*Creates JMenuBar with relevant tabs within the menubar*/
  private JMenuBar menubar ;
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;
  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" )
;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;
  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;
  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private Snake snake = null;
/* The musicclip to be played.*/
  private AudioClip clip = null;
/* The sound of the applet when eaten.*/
  private AudioClip appleEaten = null;
// Indicate if we want sound for eating the apple (options = true/false)
  private boolean soundForApple = true;

  protected boolean pause = false;  
}//End Jaysnake class

Many many thanks G
0
 
LVL 35

Expert Comment

by:girionis
ID: 11941344
Thank you for accepting, glad I was of help :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11941586
Your very very welcome sire!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now