pjcrooks2000
asked on
Trying to get my game to work in my JFrame
Hi all, i have a Java game made up of three classes,
JaySnake = The main game window with menus etc etc
Splash = a game splash screen that loads when the program is run
Snake = My game grid that controls my Snake to operate from the JaySnake window
On my Jaysnake window I have a menu system one of the tabs is to play the game, I have not added my Snake class to my JaySnake yet and I am having difficulty on getting it to show up. Further to this I want to have the Snake class to be invoked by my JaySnake game menu. I would appreciate some solutions on how to do this and how to add the Snake to my game. My code follows for each class.
JaySnake:::
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.*;
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);
/*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"
{
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" ) );
}
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()
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().setLayo
//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.addActionListene
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo
}
} ) ;
gameMenu.add( gameQuit ) ;
// ActionListener to quit the game when quit is clicked
gameQuit.addActionListener
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 ); userInstruct.addActionList
helpMenu.add( helpAbout ); helpAbout.addActionListene
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(ActionEven
{
try
{
JMenuItem source = (JMenuItem)(e.getSource())
System.out.println(source.
game.setImage(source.getTe
}
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.isEventDis
{
try
{
SwingUtilities.invokeAndWa
}
catch( Exception e )
{}
}
else
resize.run() ;
validate() ;
}
public void start()
{
Thread gamePlay = new Thread( game ) ;
gamePlay.start() ;
}
//************************
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 ) ;
}
/******declared class variables/containers*/
private Image backgroundImage ;
}
Snake:::
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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 name;
private String outName;
/*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)
{
/*Get player name from Input dialogue and pass back to String outName*/
String name = new String();
name = JOptionPane.showInputDialo
outName = name;
/*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
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven
{
sp.repaint();
}
/*Snake class graphics method*/
public void draw( Graphics g )
{
//Draw score board texts
g.setColor(Color.green);
g.drawString(outName+"'s score: "+score1,10,13);
g.drawString( "Top score: "+score2,500,15);
//Draws the first treat onscreen
g.drawImage(food,treat.x*2
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2
//Move snake body parts based on cases of dir (direction)
if(gameplay)
{
for(int i=size; i>0; i--)
location[i].move(location[
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(
treat.y=(int)(Math.random(
//print co-ordinateds if required
//System.out.println("trea
g.drawImage(food,treat.x*2
}
}
// 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[
}//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()
{
// 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(
treat.y=(int)(Math.random(
}
/*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]
else if(key == KeyEvent.VK_LEFT && location[1].x!=location[0]
else if(key == KeyEvent.VK_UP && location[1].y!=location[0]
else if(key == KeyEvent.VK_DOWN && location[1].y!=location[0]
else if(key == 112 || key == 1508)
{
gameplay=false;
}
}
}//end class
Splash:::
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Splash extends JWindow
{
public Splash(JaySnake snake)
{
super(snake);
final JaySnake sn = snake;
JLabel l = new JLabel(new ImageIcon("splash.jpg"));
//JLabel l = new JLabel(new ImageIcon("splash.jpg"));
getContentPane().add(l, BorderLayout.CENTER);
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit(
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.wid
screenSize.height/2 - (labelSize.height/2));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
setVisible(false);
dispose();
sn.start();
}
});
setVisible(true);
}
}
Thanks guys very much appreicated
ASKER
Is anyone looking at this question yet??
I will be shortly :)
ASKER
Good man thank ya! I gotta hand my game in next week and I am learning a real lot :) Sooo glad I am using EE now!
Right I had a quick look at your code. First of all you have the "name" option twice. One in the Snake class and one in the JaySnake. Just get rid of it in the Snake class since thsi should belong to JaySnake really. Snake shall not know about the play, only player shall know about the Snake.
You also need an instance of your Snake. Just declare it:
Snake snake = null;
Now you need to start the Snake when the user clicks on the new game. After this line:
name = JOptionPane.showInputDialo g( "Please enter your name" );
call the Snake. But you cannot call it from within the ActionListener class since the "this" keyword we will be using refers to the current class (i.e. the ActionListener). We need to pass a JaySnake as a paramete to the Snake and therefore, instead of creating another JaySnake instance, we wil lpass the "this" variable of the JaySnake. To do that we will need to call the Snake class outisde the AcitonListener, so have a methdo that is called (lets say) createSnake() and call it from within your listener:
name = JOptionPane.showInputDialo g( "Please enter your name" );
createSnake();
and then in your createSnake() do something like:
public void createSnake()
{
snake = new Snake(this);
}
You will also need a call to the draw method of the snake in order to start the snake (i.e. to draw the applet and the initial snake position). I would add a paint method in your JSnake class and I would call snake's draw method from inside there. Something like:
public void paint( Graphics g )
{
super.paint(g);
//Calls Snake paint method
snake.draw(g);
}
That's all I can think of. Try my suggestions and tell me if they work. If not we will look at it again.
You also need an instance of your Snake. Just declare it:
Snake snake = null;
Now you need to start the Snake when the user clicks on the new game. After this line:
name = JOptionPane.showInputDialo
call the Snake. But you cannot call it from within the ActionListener class since the "this" keyword we will be using refers to the current class (i.e. the ActionListener). We need to pass a JaySnake as a paramete to the Snake and therefore, instead of creating another JaySnake instance, we wil lpass the "this" variable of the JaySnake. To do that we will need to call the Snake class outisde the AcitonListener, so have a methdo that is called (lets say) createSnake() and call it from within your listener:
name = JOptionPane.showInputDialo
createSnake();
and then in your createSnake() do something like:
public void createSnake()
{
snake = new Snake(this);
}
You will also need a call to the draw method of the snake in order to start the snake (i.e. to draw the applet and the initial snake position). I would add a paint method in your JSnake class and I would call snake's draw method from inside there. Something like:
public void paint( Graphics g )
{
super.paint(g);
//Calls Snake paint method
snake.draw(g);
}
That's all I can think of. Try my suggestions and tell me if they work. If not we will look at it again.
Sorry for my syntactical erros, I was trying to write the message really quick :)
This
> JSnake
should be JaySnake :)
This
> JSnake
should be JaySnake :)
ASKER
Girionis and all others concerned just having tea will work on this llater ... :) thanks
Ok, let me know if you have any questions.
ASKER
Ok sure will do, I will try to implement this tonight at some stage but for now I have a visitor.. thanks g :)
ASKER
g I have not forgot about this, I will hopefully get on it sometime today. I have just been called ou tto look at a Laptop for now ... Grrrrrrrrrrrrr.. r u going to be around this weekend by any chance ? :) I have quite a bit more to do on this game!
I will probably be around yes, although I cannot promise it :)
ASKER
Ok good man... Still looking at this laptop. Hes only gone and dropped it! Sheeeeesh. Damn thing is not booting I think the CPU has gone. Smashed screen to boot and does not work on a VDU neither.
ASKER
g what are you referring too The "name" option i'm not sure i understand that... :) Also you said get rid of the JaySnake. The way that this should be constructed is with a systematic OOD in that if I wanted to have another snake I can create another one as with a two player model game.
So lets say for instance I had a menu that says Game options = Single player, two player net game.
I might get round to making a networked game ... So i would like to develop it that way, forgive if I am babbling... do you know what I mean ?
So lets say for instance I had a menu that says Game options = Single player, two player net game.
I might get round to making a networked game ... So i would like to develop it that way, forgive if I am babbling... do you know what I mean ?
I mean the popup window where you type your name, you have it twice, one in your Snake class and one in your JaySnake class. I would get rid of it in the Snake class and leave it in the JaySnake since this is the main entry point for the Snake.
ASKER
Ahhh ok gotcha fella, ok i have done most of that but I am having a paint problem.... I will post the code up
I have this
JaySnake:::
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().setLayo ut( 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.addActionListene r( new ActionListener(){
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo g( "Please enter your name" );
createSnake();
}
} ) ;
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.addActionList ener(new ActionListener() {
public void actionPerformed(ActionEven t e) {
System.out.println("Instru ctions 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(400, 400);
f.setVisible(true);
}
});
helpMenu.add( helpAbout );
helpAbout.addActionListene r( 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.w idth - 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(ActionEven t e)
{
try
{
JMenuItem source = (JMenuItem)(e.getSource()) ;
System.out.println(source. getText()) ;
game.setImage(source.getTe xt());
}
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.isEventDis patchThrea d() )
{
try
{
SwingUtilities.invokeAndWa it( 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);
}
public void createSnake()
{
snake = new Snake(this);
}
/******declared class variables/containers*/
private Image backgroundImage ;
private ImageIcon icon;
}
Snake::::
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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 name;
private String outName;
/*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)
{
/*Get player name from Input dialogue and pass back to String outName*/
String name = new String();
/*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) { }
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven t event)
{
sp.repaint();
}
/*Snake class graphics method*/
public void draw( Graphics g )
{
//Draw score board texts
g.setColor(Color.green);
g.drawString(outName+"'s score: "+score1,10,13);
g.drawString( "Top score: "+score2,500,15);
//Draws the first treat onscreen
g.drawImage(food,treat.x*2 0-20,treat .y*20-20,1 9,19,null) ;
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2 0-20,treat .y*20-20,1 9,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("trea t.x = "+treat.x+" treat.y = " +treat.y);
g.drawImage(food,treat.x*2 0-20,treat .y*20-20,1 9,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,nul l);
}//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()
{
// 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
Its something I have done wrong I know the snake creates a background etc etc but its writing over the one in JaySnake.. also the scoreboard in the Snake paint method...
See what you think or can suggest :)
I have this
JaySnake:::
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.
{
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()
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().setLayo
//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.addActionListene
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo
createSnake();
}
} ) ;
gameMenu.add( gameQuit ) ;
// ActionListener to quit the game when quit is clicked
gameQuit.addActionListener
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.addActionList
public void actionPerformed(ActionEven
System.out.println("Instru
//Create new Jframe to view User instructions
JFrame f = new JFrame();
JEditorPane p = new JEditorPane("text/html", "");
f.getContentPane().add(p);
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(400, 400);
f.setVisible(true);
}
});
helpMenu.add( helpAbout );
helpAbout.addActionListene
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.w
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(ActionEven
{
try
{
JMenuItem source = (JMenuItem)(e.getSource())
System.out.println(source.
game.setImage(source.getTe
}
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.isEventDis
{
try
{
SwingUtilities.invokeAndWa
}
catch( Exception e )
{}
}
else
resize.run() ;
validate() ;
}
public void start()
{
Thread gamePlay = new Thread( game ) ;
gamePlay.start() ;
}
//************************
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);
}
public void createSnake()
{
snake = new Snake(this);
}
/******declared class variables/containers*/
private Image backgroundImage ;
private ImageIcon icon;
}
Snake::::
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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 name;
private String outName;
/*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)
{
/*Get player name from Input dialogue and pass back to String outName*/
String name = new String();
/*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
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven
{
sp.repaint();
}
/*Snake class graphics method*/
public void draw( Graphics g )
{
//Draw score board texts
g.setColor(Color.green);
g.drawString(outName+"'s score: "+score1,10,13);
g.drawString( "Top score: "+score2,500,15);
//Draws the first treat onscreen
g.drawImage(food,treat.x*2
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2
//Move snake body parts based on cases of dir (direction)
if(gameplay)
{
for(int i=size; i>0; i--)
location[i].move(location[
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(
treat.y=(int)(Math.random(
//print co-ordinateds if required
//System.out.println("trea
g.drawImage(food,treat.x*2
}
}
// 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[
}//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()
{
// 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(
treat.y=(int)(Math.random(
}
/*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]
else if(key == KeyEvent.VK_LEFT && location[1].x!=location[0]
else if(key == KeyEvent.VK_UP && location[1].y!=location[0]
else if(key == KeyEvent.VK_DOWN && location[1].y!=location[0]
else if(key == 112 || key == 1508)
{
gameplay=false;
}
}
}//end class
Its something I have done wrong I know the snake creates a background etc etc but its writing over the one in JaySnake.. also the scoreboard in the Snake paint method...
See what you think or can suggest :)
ASKER
I can't thank you enough for all your help on this g :)
> Its something I have done wrong I know the snake creates a background etc etc but its writing over the one in JaySnake..
Ok I will be off and on in the office for the next few hours. I will take a look later on tonight, but at a *guess* I'd say it is probably a problem with the paint method.
Ok I will be off and on in the office for the next few hours. I will take a look later on tonight, but at a *guess* I'd say it is probably a problem with the paint method.
ASKER
Yep loks like it also the KeyEvent listeners ... Hmmm I think we are going out to tea and to visit friends for awhile so .. thats cool with me.
Thank yee very muches :) speak later
Thank yee very muches :) speak later
ASKER
G are you around today by any chance?
Yes I probably will. I am trying to compile your programme, is it possible to post your About class?
ASKER
yeah sure not a problem will do now... Thank G your there :) Here it is anything else let me know
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class About extends JDialog implements ActionListener
{
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel insetsPanel1 = new JPanel();
JPanel insetsPanel2 = new JPanel();
JPanel insetsPanel3 = new JPanel();
JButton button1 = new JButton();
JLabel imageLabel = new JLabel();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JLabel label4 = new JLabel();
ImageIcon iconImage = new ImageIcon();
BorderLayout borderLayout1 = new BorderLayout();
BorderLayout borderLayout2 = new BorderLayout();
FlowLayout flowLayout1 = new FlowLayout();
GridLayout gridLayout1 = new GridLayout();
String productAndAuthor = "JaySnake by Patrick Crooks";
String versionNum = "Version 1.1";
String assignment = "Java Programming and animation";
String assNum = "Assigment 2";
public About(Frame parent)
{
super(parent);
enableEvents(AWTEvent.WIND OW_EVENT_M ASK);
try
{
AboutInit();
}
catch(Exception e)
{
System.out.println(e);//e. printStack Trace();
}
}
//Component initialization
private void AboutInit() throws Exception
{
jay = new ImageIcon("icons/jayIcon.j pg");
imageLabel.setIcon(jay);
this.setTitle("About JaySnake ");
panel1.setLayout(borderLay out1);
panel2.setLayout(borderLay out2);
insetsPanel1.setLayout(flo wLayout1);
insetsPanel2.setLayout(flo wLayout1);
insetsPanel2.setBorder(Bor derFactory .createEmp tyBorder(1 0, 10, 10, 10));
gridLayout1.setRows(4);
gridLayout1.setColumns(1);
label1.setText(productAndA uthor);
label2.setText(versionNum) ;
label3.setText(assignment) ;
label4.setText(assNum);
insetsPanel3.setLayout(gri dLayout1);
insetsPanel3.setBorder(Bor derFactory .createEmp tyBorder(1 0, 60, 10, 10));
button1.setText("Ok");
button1.addActionListener( this);
insetsPanel2.add(imageLabe l, null);
panel2.add(insetsPanel2, BorderLayout.WEST);
this.getContentPane().add( panel1, null);
insetsPanel3.add(label1, null);
insetsPanel3.add(label2, null);
insetsPanel3.add(label3, null);
insetsPanel3.add(label4, null);
panel2.add(insetsPanel3, BorderLayout.CENTER);
insetsPanel1.add(button1, null);
panel1.add(insetsPanel1, BorderLayout.SOUTH);
panel1.add(panel2, BorderLayout.NORTH);
setResizable(true);
}
//Overridden so we can exit when window is closed
protected void processWindowEvent(WindowE vent e)
{
if (e.getID() == WindowEvent.WINDOW_CLOSING )
{
cancel();
}
super.processWindowEvent(e );
}
//Close the dialog box on window event
void cancel()
{
dispose();
}
//Close the dialog on a button event
public void actionPerformed(ActionEven t e)
{
if (e.getSource() == button1)
{
cancel();
}
}
//Image storage container
private ImageIcon jay;
}
cheers pal
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class About extends JDialog implements ActionListener
{
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel insetsPanel1 = new JPanel();
JPanel insetsPanel2 = new JPanel();
JPanel insetsPanel3 = new JPanel();
JButton button1 = new JButton();
JLabel imageLabel = new JLabel();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JLabel label4 = new JLabel();
ImageIcon iconImage = new ImageIcon();
BorderLayout borderLayout1 = new BorderLayout();
BorderLayout borderLayout2 = new BorderLayout();
FlowLayout flowLayout1 = new FlowLayout();
GridLayout gridLayout1 = new GridLayout();
String productAndAuthor = "JaySnake by Patrick Crooks";
String versionNum = "Version 1.1";
String assignment = "Java Programming and animation";
String assNum = "Assigment 2";
public About(Frame parent)
{
super(parent);
enableEvents(AWTEvent.WIND
try
{
AboutInit();
}
catch(Exception e)
{
System.out.println(e);//e.
}
}
//Component initialization
private void AboutInit() throws Exception
{
jay = new ImageIcon("icons/jayIcon.j
imageLabel.setIcon(jay);
this.setTitle("About JaySnake ");
panel1.setLayout(borderLay
panel2.setLayout(borderLay
insetsPanel1.setLayout(flo
insetsPanel2.setLayout(flo
insetsPanel2.setBorder(Bor
gridLayout1.setRows(4);
gridLayout1.setColumns(1);
label1.setText(productAndA
label2.setText(versionNum)
label3.setText(assignment)
label4.setText(assNum);
insetsPanel3.setLayout(gri
insetsPanel3.setBorder(Bor
button1.setText("Ok");
button1.addActionListener(
insetsPanel2.add(imageLabe
panel2.add(insetsPanel2, BorderLayout.WEST);
this.getContentPane().add(
insetsPanel3.add(label1, null);
insetsPanel3.add(label2, null);
insetsPanel3.add(label3, null);
insetsPanel3.add(label4, null);
panel2.add(insetsPanel3, BorderLayout.CENTER);
insetsPanel1.add(button1, null);
panel1.add(insetsPanel1, BorderLayout.SOUTH);
panel1.add(panel2, BorderLayout.NORTH);
setResizable(true);
}
//Overridden so we can exit when window is closed
protected void processWindowEvent(WindowE
{
if (e.getID() == WindowEvent.WINDOW_CLOSING
{
cancel();
}
super.processWindowEvent(e
}
//Close the dialog box on window event
void cancel()
{
dispose();
}
//Close the dialog on a button event
public void actionPerformed(ActionEven
{
if (e.getSource() == button1)
{
cancel();
}
}
//Image storage container
private ImageIcon jay;
}
cheers pal
Ok I did it without the About dialog but I have problem with drawing the snake and the apple. For some reason it keeps reapints them and they flicker... I will post the code I have so far, try to run it and tell me if you notice something weird. This is what I have so far:
JaySnake
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.*;
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);
/*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" ) );
}
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().setLayo ut( 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.addActionListene r( new ActionListener(){
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo g( "Please enter your name" );
snake = new Snake(JaySnake.this);
}
});
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 ); userInstruct.addActionList ener(this) ;
helpMenu.add( helpAbout ); helpAbout.addActionListene r(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(ActionEven t e)
{
try
{
JMenuItem source = (JMenuItem)(e.getSource()) ;
System.out.println(source. getText()) ;
game.setImage(source.getTe xt());
}
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.isEventDis patchThrea d() )
{
try
{
SwingUtilities.invokeAndWa it( 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);
}
public void paint( Graphics g )
{
super.paint(g);
/*
g.drawImage(backgroundImag e,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);
}
/*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;
}
Snake
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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 name;
private String outName;
/*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)
{
/*Get player name from Input dialogue and pass back to String outName*/
String name = new String();
/*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) { }
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven t event)
{
sp.repaint();
}
/*Snake class graphics method*/
public void draw( Graphics g )
{
//Draw score board texts
g.setColor(Color.green);
g.drawString(outName+"'s score: "+score1,10,13);
g.drawString( "Top score: "+score2,500,15);
//Draws the first treat onscreen
g.drawImage(food,treat.x*2 0-20,treat .y*20-20,1 9,19,null) ;
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2 0-20,treat .y*20-20,1 9,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("trea t.x = "+treat.x+" treat.y = " +treat.y);
g.drawImage(food,treat.x*2 0-20,treat .y*20-20,1 9,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,nul l);
}//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("restar t");
// 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
The Splahs screen is the same.
JaySnake
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.*;
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);
/*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"
{
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" ) );
}
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()
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().setLayo
//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.addActionListene
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo
snake = new Snake(JaySnake.this);
}
});
gameMenu.add( gameQuit ) ;
// ActionListener to quit the game when quit is clicked
gameQuit.addActionListener
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 ); userInstruct.addActionList
helpMenu.add( helpAbout ); helpAbout.addActionListene
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(ActionEven
{
try
{
JMenuItem source = (JMenuItem)(e.getSource())
System.out.println(source.
game.setImage(source.getTe
}
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.isEventDis
{
try
{
SwingUtilities.invokeAndWa
}
catch( Exception e )
{}
}
else
resize.run() ;
validate() ;
}
public void start()
{
Thread gamePlay = new Thread( game ) ;
gamePlay.start() ;
}
//************************
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);
}
public void paint( Graphics g )
{
super.paint(g);
/*
g.drawImage(backgroundImag
//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
*/
//Calls Snake paint method
if (snake != null)
snake.draw(g);
}
/*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;
}
Snake
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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 name;
private String outName;
/*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)
{
/*Get player name from Input dialogue and pass back to String outName*/
String name = new String();
/*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
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven
{
sp.repaint();
}
/*Snake class graphics method*/
public void draw( Graphics g )
{
//Draw score board texts
g.setColor(Color.green);
g.drawString(outName+"'s score: "+score1,10,13);
g.drawString( "Top score: "+score2,500,15);
//Draws the first treat onscreen
g.drawImage(food,treat.x*2
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2
//Move snake body parts based on cases of dir (direction)
if(gameplay)
{
for(int i=size; i>0; i--)
location[i].move(location[
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(
treat.y=(int)(Math.random(
//print co-ordinateds if required
//System.out.println("trea
g.drawImage(food,treat.x*2
}
}
// 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[
}//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("restar
// 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(
treat.y=(int)(Math.random(
}
/*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]
else if(key == KeyEvent.VK_LEFT && location[1].x!=location[0]
else if(key == KeyEvent.VK_UP && location[1].y!=location[0]
else if(key == KeyEvent.VK_DOWN && location[1].y!=location[0]
else if(key == 112 || key == 1508)
{
gameplay=false;
}
}
}//end class
The Splahs screen is the same.
Doh.. I should have thought about it. We should call the paint method on the panel not on the whole frame. Let me try it and see what I can come up with.
Ok, it's working fine now. Let me do the key listener stuff and I will get back to you. I also changed the Snake class a bit. It takes as second parameter the player's name, since the drawing for the players socre is done inside the Snake class. It's not a big deal but once we make it work and we want to change it we could move this code (the drawing of the player's name) outside the Snake clas and change again the Snake constructor to only take the JaySnake instance.
ASKER
fantastic man :)
Ok here it is:
JaySnake
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.*;
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" ) );
}
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(backgroundImag e,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().setLayo ut( 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.addActionListene r( new ActionListener(){
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo g( "Please enter your name" );
snake = new Snake(JaySnake.this, 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 ); userInstruct.addActionList ener(this) ;
helpMenu.add( helpAbout ); helpAbout.addActionListene r(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(ActionEven t e)
{
try
{
JMenuItem source = (JMenuItem)(e.getSource()) ;
System.out.println(source. getText()) ;
game.setImage(source.getTe xt());
}
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.isEventDis patchThrea d() )
{
try
{
SwingUtilities.invokeAndWa it( 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........" ) ;
final JaySnake app = new JaySnake() ;
app.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent keyevent) {
//System.out.println("Test key press >>>>>>>>>>>>>>>>>>>>>>>>>> ");
app.snake.keyPressed(keyev ent);
}
});
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 ) ;
}
/******declared class variables/containers*/
private Image backgroundImage ;
private Snake snake = null;
}
Snake:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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)
{
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) { }
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven t 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*2 0-20,treat .y*20-20,1 9,19,null) ;
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2 0-20,treat .y*20-20,1 9,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("trea t.x = "+treat.x+" treat.y = " +treat.y);
g.drawImage(food,treat.x*2 0-20,treat .y*20-20,1 9,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,nul l);
}//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("restar t");
// 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
JaySnake
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.*;
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"
{
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" ) );
}
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(backgroundImag
//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
//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()
//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().setLayo
//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.addActionListene
public void actionPerformed( ActionEvent e )
{
String name = new String();
name = JOptionPane.showInputDialo
snake = new Snake(JaySnake.this, name);
}
});
gameMenu.add( gameQuit ) ;
// ActionListener to quit the game when quit is clicked
gameQuit.addActionListener
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 ); userInstruct.addActionList
helpMenu.add( helpAbout ); helpAbout.addActionListene
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(ActionEven
{
try
{
JMenuItem source = (JMenuItem)(e.getSource())
System.out.println(source.
game.setImage(source.getTe
}
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.isEventDis
{
try
{
SwingUtilities.invokeAndWa
}
catch( Exception e )
{}
}
else
resize.run() ;
validate() ;
}
public void start()
{
Thread gamePlay = new Thread( game ) ;
gamePlay.start() ;
}
//************************
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
app.snake.keyPressed(keyev
}
});
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 ) ;
}
/******declared class variables/containers*/
private Image backgroundImage ;
private Snake snake = null;
}
Snake:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
/*public class Snake implements ActionListener in
*particular [CODE]KeyPressed[/CODE]*/
public class Snake implements ActionListener
{
/*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)
{
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
}
/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
public void actionPerformed(ActionEven
{
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*2
//Collison detection for treat
if(gameplay)
{
if(location[0].x==treat.x && location[0].y==treat.y)
{
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*2
//Move snake body parts based on cases of dir (direction)
if(gameplay)
{
for(int i=size; i>0; i--)
location[i].move(location[
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(
treat.y=(int)(Math.random(
//print co-ordinateds if required
//System.out.println("trea
g.drawImage(food,treat.x*2
}
}
// 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[
}//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("restar
// 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(
treat.y=(int)(Math.random(
}
/*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]
else if(key == KeyEvent.VK_LEFT && location[1].x!=location[0]
else if(key == KeyEvent.VK_UP && location[1].y!=location[0]
else if(key == KeyEvent.VK_DOWN && location[1].y!=location[0]
else if(key == 112 || key == 1508)
{
gameplay=false;
}
}
}//end class
ASKER
Oakies I have just run it and it compiles ok, but I am getting a grey window in the JaySnake frame
Would there be a problem with the Splash class at all, posted below ...ta sport
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Splash extends JWindow
{
public Splash(JaySnake splash)
{
super(splash);
final JaySnake sp = splash;
JLabel l = new JLabel(new ImageIcon("splashImage/spl ash.jpg")) ;
//JLabel l = new JLabel(new ImageIcon("splash.jpg"));
getContentPane().add(l, BorderLayout.CENTER);
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit( ).getScree nSize();
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.wid th/2 - (labelSize.width/2),
screenSize.height/2 - (labelSize.height/2));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
setVisible(false);
dispose();
sp.start();
}
});
setVisible(true);
}
}
Would there be a problem with the Splash class at all, posted below ...ta sport
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Splash extends JWindow
{
public Splash(JaySnake splash)
{
super(splash);
final JaySnake sp = splash;
JLabel l = new JLabel(new ImageIcon("splashImage/spl
//JLabel l = new JLabel(new ImageIcon("splash.jpg"));
getContentPane().add(l, BorderLayout.CENTER);
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit(
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.wid
screenSize.height/2 - (labelSize.height/2));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
setVisible(false);
dispose();
sp.start();
}
});
setVisible(true);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
heh g i just noticed I had moved all my images to folders, so thats why they were not loading... :) that is fantastic fella... well done thank you very very much I am sure I will have another one quite soon. Actually I do have one related to sound if you get a sec to look at it. ;)
https://www.experts-exchange.com/questions/21110718/Play-music-in-my-java-game.html#11920694
Meantime I am uploading the game up for you to have a play with :) should take a couple of mins to upload. Check it out you may aswell you have almost done it yourself :) Still got to do some work on it I think!
www.sfukgamers.co.uk/Game.rar
Points on the way
https://www.experts-exchange.com/questions/21110718/Play-music-in-my-java-game.html#11920694
Meantime I am uploading the game up for you to have a play with :) should take a couple of mins to upload. Check it out you may aswell you have almost done it yourself :) Still got to do some work on it I think!
www.sfukgamers.co.uk/Game.rar
Points on the way
:)
ASKER
You are one fantastic fella do you know that? :) i'd have your babies if i was a girl .. heh
lol :)
BTW I am looking at your other question atm :)
ASKER
This guy is Excellent... I have done a bit more work on the game so I will upload a new one if you wish... Just changed it so the menu items were working, the instruction window and About help box ... and played around with the score board area ... :)
ASKER