Solved

Play music in my java game

Posted on 2004-08-28
27
1,466 Views
Last Modified: 2013-11-23
Hi all I am running j2sdk1.4.1_06 ans I want to be able to play sounds in my Java game.   YOu will notice that I have amenu and I wan to be able to click on the Menu item "JCheckBoxMenuItem soundMusic" in order to stop and play the sound.  Also I want the sound to play as default when the Application runs.

At present I have a *.wav file but if needs be I can convert it to a different format.   The code for my application is below

Muches appreciated


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.net.*;

public class JaySnake extends JFrame implements ActionListener
{
      Snake snake = null;
      
  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);

/*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("default.jpg")) //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" ) );
      }
      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);

    }

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

    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 = 600 ;
  private static final int DISPLAY_H = 600 ;

  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()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
     // 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" );
           
     }
     } ) ;
     
    gameMenu.add( gameQuit ) ;

    // 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.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.add( soundMusic );
    soundMenu.add( soundSound ) ;

    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct );


/********** Here is the Additional Codes **********************/

     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();
       }
     } ) ;


    //JaySnake frame Window closing    
   
    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 start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
//**************************Main function*************************************
  public static void main(String [] arguments)
   {
    System.out.println( "Starting JaySnake........" ) ;
    JaySnake app = new JaySnake() ;
   
    app.setSize( DISPLAY_W, DISPLAY_H ) ;
    app.setTitle( "JaySnake Game" ) ;
    app.setVisible( true ) ;
    Splash splash = new Splash(app);  
   }


/*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 ) ;
            super.paint(g);
        //Calls Snake paint method
            snake.draw(g);
      
     }
  /******declared class variables/containers*/
  private Image backgroundImage ;
  private ImageIcon icon;
 
}


thanks
pjcrooks2000
0
Comment
Question by:pjcrooks2000
  • 14
  • 11
  • +1
27 Comments
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
ps:  I have experimwnted with Auidioclip in the past with not much success on this version of the jdk.   Perhaps some experts will know better :)
0
 
LVL 18

Expert Comment

by:armoghan
Comment Utility
check following links for running audio

http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
http://javaalmanac.com/egs/java.applet/LoadAudioApp.html
http://www.developer.com/java/article.php/857411

and attach an ActionListener to JCheckBoxMenuItem soundMusic and in actionPerformed do
audioClip.stop();
to stop and Play to run it
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
Comment Utility
Ok here it is. Tha JaySnake class:

import java.awt.*;
import java.awt.event.*;
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;

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 = 100;

/*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("default")) //Sets background to default image
          {
                    backgroundImage = ImageIO.read( new File( "default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                   backgroundImage = ImageIO.read( new File( "longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                  backgroundImage = ImageIO.read( new File( "sand.jpg" ) );
         }
         
         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                  backgroundImage = ImageIO.read( new File( "blueGlass.jpg" ) );
         }
         else //Sets to default if none mathced
         {
                   backgroundImage = ImageIO.read( new File( "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( "default.jpg" ) );
            clip = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/Aristotle.wav"));
            appleEaten = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/bottle-open.wav"));
      }
      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.green);
        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()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game();
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
     // 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 ) ;

    // 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.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 );
    soundMusic.setState(true);
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

      /* 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.add( userInstruct );
    userInstruct.addActionListener(this);
    helpMenu.add( helpAbout );
    helpAbout.addActionListener(this);

    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();
            /*
            try {
              // At present, ALAW and ULAW encodings must be converted
              // to PCM_SIGNED before it can be played
              AudioFormat format = stream.getFormat();
              if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                  format = new AudioFormat(
                          AudioFormat.Encoding.PCM_SIGNED,
                          format.getSampleRate(),
                          format.getSampleSizeInBits()*2,
                          format.getChannels(),
                          format.getFrameSize()*2,
                          format.getFrameRate(),
                          true);        // big endian
                  stream = AudioSystem.getAudioInputStream(format, stream);
              }
          
              // Create the clip
              DataLine.Info info = new DataLine.Info(
                  Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
              clip = (Clip) AudioSystem.getLine(info);
          
              // This method does not return until the audio file is completely loaded
              clip.open(stream);
          
              // Start playing
              clip.start();
                  
                  // Play and loop forever
                clip.loop(Clip.LOOP_CONTINUOUSLY);
          }
          catch (IOException e)
          {
                System.out.println(e);
          }
          catch (LineUnavailableException e)
          {
                System.out.println(e);
          }
          */
      }
      
  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
     //**************************Main function*************************************
       public static void main(String [] arguments)
     {
         System.out.println( "Starting JaySnake........" ) ;
             final JaySnake app = new JaySnake() ;
             
         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 clip to be played.
  private AudioClip clip = null;
  // The sound of the applet when eaten.
  private AudioClip appleEaten = null;
      // Indicate sif we want sound for eating the apple
      private boolean soundForApple = false;
}

and the Snake class:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
import java.applet.AudioClip;
import java.applet.AudioClip;

/*public class Snake implements ActionListener in
 *particular [CODE]KeyPressed[/CODE]*/

public class Snake implements ActionListener
{

      // The sound of eating an apple
      AudioClip appleEaten = null;
      
/*Image declarations treat and snake body parts
 */
  private Image food, body;

/*class variable sp*/
    private JaySnake sp;
      /*Used for users name input from dialogue*/
    private String player;

/*Timer declaration recommended from sun website as an alternative to [code]Thread[/code]
 */
  private Timer timer;

/*int variable declarations*/
  private int size =3,
          dir,
          score1 =0,
          score2 = 0;
         

/*boolean state declarations*/
  boolean game = false,
          ate=false,
          gameplay=false,
          collide = false;
         
/*Array of points for location on the screen of snake and apples*/
          Point[] location = new Point[600];

          Point treat = new Point(12,7);

/*Constructor - passing snake class to app defined in class as sp*/
     public Snake(JaySnake app, String player, AudioClip appleEaten)
     {
           this.appleEaten = appleEaten;
           this.player = player;
           
            /*new Timer set to 10 cycles per second and started with the
             *[code] timer.start();[/code] methd.*/
          timer = new Timer (100,this);
          timer.start();
          sp = app;

//initialise all points with 0
            for(int i=0; i<600; i++)
        location[i] = new Point(0,0);

          // Setting all starting points
          location[2].move(15,25);
          location[1].move(15,24);
          location[0].move(15,23);
          treat.move(1,6);

//try read in treat and food images
          try
          {
               food = ImageIO.read(new File("food.jpg"));
               body = ImageIO.read(new File("snakebits.jpg"));
          }     catch(IOException e)
          {System.out.println(e);
          }

               try{ Thread.sleep(70); }
          catch(InterruptedException e) { }
     }

      public void setAppleSound(AudioClip clip)
      {
            this.appleEaten = clip;
      }
      
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
     public void actionPerformed(ActionEvent event)
     {
        sp.repaint();
     }

/*Snake class graphics method*/
    public void draw( Graphics g )
    {
            //Draw score board texts
        g.setColor(Color.green);
          g.drawString(player + "'s score: "+score1,10,13);
          g.drawString( "Top score: "+score2,500,15);
       
            //Draws the first treat onscreen
        g.drawImage(food,treat.x*20-20,treat.y*20-20,19,19,null);

            //Collison detection for treat
        if(gameplay)
        {
             if(location[0].x==treat.x && location[0].y==treat.y)
             {
                     if (appleEaten != null)
                  {
                        appleEaten.play();
                  }
                 
                  ate=true;
                  size++;
                  score1++;
             }
            
                  // Drawing new head position, erasing last tale position
              if(location[size-1].x == treat.x && location[size-1].y == treat.y)
                    g.drawImage(food,treat.x*20-20,treat.y*20-20,19,19,null);
      
                  //Move snake body parts based on cases of dir (direction)
              if(gameplay)
              {
                   for(int i=size; i>0; i--)
                        location[i].move(location[i-1].x, location[i-1].y);
      
                   switch(dir)
                   {
                        case 0: location[0].x = location[0].x+1; break;
                        case 1: location[0].x = location[0].x-1; break;
                        case 2: location[0].y = location[0].y-1; break;
                        case 3: location[0].y = location[0].y+1; break;
                   }
              }
      
                  // Checking if had just eaten an treat, if yes - draw new treat location
              if( ate )
              {
                  ate = false;
                        //Math.randon generate new apple positions using the co-ordiantes
                  treat.x=(int)(Math.random()*30+1);
                  treat.y=(int)(Math.random()*25+3);
                        //print co-ordinateds if required
                        //System.out.println("treat.x = "+treat.x+" treat.y = " +treat.y);
                    g.drawImage(food,treat.x*20-20,treat.y*20-20,19,19,null);
              }
          }

            // Check for collison with walls and snake bits
        for(int i=3; i<size; i++)
              if(location[0].x == location[i].x && location[0].y == location[i].y)
                   {
                         gameplay = false;
                    restart();
                  }
     
            //Walls collison
        if(((collide ||
                 (dir==0 && location[0].x==31) || //Right co-ordinates
                     (dir==1 && location[0].x==0) ||   //Left co-ordinates
                     (dir==2 && location[0].y==2) ||  //Top  co-ordinates
                 (dir==3 && location[0].y==28))))  //Bottom co-ordinates
             {
              gameplay = false;
                  restart();
        }

            //Sets images for body
        for(int i=0; i<size; i++)
              g.drawImage(body,location[i].x*20-20,location[i].y*20-20,20,20,null);
     }//end snake draw method

      /*resets game settings including location of snake and apple.  Also updates
       *the Top score and resets player score*/
      public void restart()
      {
            System.out.println("restart");
            
        // Setting all starting points again
        if(score1>score2){
        score2 = score1;}
        score1 = 0;
        game = false;
        dir =0;
        size=3;
            //Move snake back to original position
        location[2].move(15,25);
        location[1].move(15,24);
        location[0].move(15,23);
            //Re generate new apple locations
        treat.x=(int)(Math.random()*30+1);
        treat.y=(int)(Math.random()*25+3);
        }

      /*If keys are presees up Arrow, Down Arrow, Left Arrow and Right Arrow
       *move snake to new location on grid */
     public void keyPressed(KeyEvent evt)
     {
        int key = evt.getKeyCode();
        if(key == KeyEvent.VK_RIGHT && location[1].x!=location[0].x+1) { dir=0; gameplay=true; }
        else if(key == KeyEvent.VK_LEFT && location[1].x!=location[0].x-1) { dir=1; gameplay=true;}
        else if(key == KeyEvent.VK_UP && location[1].y!=location[0].y-1) { dir=2; gameplay=true;}
        else if(key == KeyEvent.VK_DOWN && location[1].y!=location[0].y+1) { dir=3; gameplay=true;}
        else if(key == 112 || key == 1508)
        {
         gameplay=false;
          }
     }
}//end class

These classes are taken from an earlier example. The Splash screen should be the same. The About box is not sued at all here (I guess this is easy to make it work with the rest of the application).

Things to notice.

1) I am using some sample .wav files I had on my computer and some I downloaded from Sun's web site.
2) I am using the Applet's audio capabilities to do it since this is the fastest and shortest way. If you want we can go the  javax.sound.sampled package but the functionallity will be the same (apart from a small issue described at seciton 3).
3) The looping stops and then starts over (i.e. form the biggining) not from the part it stopped. This means that if you stop the music at the middle and then you check the music option again then it will start from the beginning. This is because I cannot get the current position and save it. If we are to use the javax.sound package then we could do something like:

long position = clip.getMicrosecondPosition();
clip.setMicrosecondPosition(position);
clip.loop(0);

and it would have started at the position it previously stopped.
4) I am using the clip itself to determine if the sound for eating the apple should be played or not. It might be fatser to have a boolean variable and use that instead. If we make it work then we can have a look again and see where we cna optimize it for faster/better code.


0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
As always, excuse my syntactical/grammatical errors.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
If the sound file is way too long you might want to use streaming audio.
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
Hmmm g it does not seem to be working,  do you know if there is an issue with my version on the jdk... I read up about having to use the JMF a while back for the latest version of the jdk, which is what I have.  

Very odd!  :(  

my jdk is "j2sdk1.4.1_06"  cheers
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
I am using 1.4.0_03 and everything runs fine. What seems to be the problem?
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
Just that the sounds don't play, when i first made the game i tried adding sounds to it but at that time I became aware that apparently the latest release of the jdk did not support audio anymore..  I thought it strange and didn't believe it but perhaps there is an element of truth to it.  So what i found was that in order to make Apps with sound that the Java Media Framework was required. http://java.sun.com/products/java-media/jmf/2.1.1/guide/

Its a bit strange as I was not able to do it earlier, any ideas on that?

I notice your using an earlier jdk compared to me.  
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> I notice your using an earlier jdk compared to me.  

It shouldn't matter. Did you replace the files I am using in my code with your own ones? Also are you getting any exceptions?
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
I am just download 1.4.0_03 to see if it makes a difference.  You never know :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
If you look at my code I am using two wav files. Aristotle.wav for the music of the game and bottle-open.wav for the sound that the snake makes when eating the apple. Have you replaced these files with your own one?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> I am just download 1.4.0_03 to see if it makes a difference.  You never know :)

I will really be surprised if it does make a difference :)
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
Yep I have replaced them, actually i also downloaded the bottle-open.wav file for good measure!  I suppose I can just install it and try it.  It won't do any hard using that jdk anyway :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Ok try it and tell me if it works. Also, do you get any exceptions?
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
whey hey!  Great solution g, Just for yours and anyone else's reference for the future.  In order to get  sounds to work as described above you will need an older version of the java jdk, i have just installed "j2sdk1.4.2_03" that i obtained from http://java.sun.com/products/archive/ and my sounds play fine and dandy.

g your a genius thanks very muchly again :)   I am sure I will be thinking about something else for you.  Can i just say not only did you get my music to play from my menu at the start of the game, but you also coded it to play a sound file upon collission detection.  Give this man respect everyone   :)   Points on route  !

Why are you not the highest ranked here anyway.. you should be !
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
g while i am on the subject, your good with databases are you not?   I may have another project in the pipeline to pump up some points for ya!  I will let you know more about that once this small project is done!
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> Why are you not the highest ranked here anyway.. you should be !

I am not that good, there are other people with far more knowledge than I do :)

Anyway, what's the deal with the jdk? Did you install an earlier version or a newer one? You said in the beginning that you have j2sdk1.4.1_06 but now you downloaded j2sdk1.4.2_03?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> g while i am on the subject, your good with databases are you not?

I have a bit of knowledge yes. If I know I wil lhelp you :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
oooh yeah... duh!   well maybe its the newer one ahhhhhhhh I take it all back i missed the "2"  

Grab this g www.sfukgamers.co.uk/code.txt   post back as soon as you get it
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Ah.. ok ta m8 :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
u got it?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
aye :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
coolio :) nice bit of code that is ;)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Aye it is. You are a great coder :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
Thanks ... lol
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

728 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

11 Experts available now in Live!

Get 1:1 Help Now