Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Java games question -  continued

Posted on 2004-08-25
11
Medium Priority
?
287 Views
Last Modified: 2010-03-31

Hi all please refer to an old question for the code for my game.  

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21106149.html 

I am making a game and I have got a JFrame for it and a splash screen that appears before the game runs.  I am creating this new game based on one that i created a while back and the original one I made was very week in a OOD sense.  

Orininallly i had a snake Panel and a Snake class for my game which can be seen below:

Snakepanel
------------------

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

/*SnakePanel class extends JPanel*/
public class SnakePanel extends JPanel
{
//Images
    private Image backgroundImage,intro;
//Snake class variable s
    private Snake s;
//timer variable used for splash screen with boolean
    int timer;
    boolean Introscreen=true;
   
//Constructor
      public SnakePanel() {
//declare new instance of Snake s
            s = new Snake(this);
//Sets size of Panel
            setPreferredSize( new Dimension( 600, 600 ));
//Read in backGround and SpashScreen images
            try      {
                  backgroundImage = ImageIO.read(new File("backGround.jpg"));
      intro = ImageIO.read(new File("splash.jpg"));
            } catch(IOException e) {
                  System.out.println(e);
            }
      }

//Main method
      public static void main(String args[])
      {
    final SnakePanel app = new SnakePanel();
//Created new JFrameand add KeyPressed Listener to it      
            JFrame jf = new JFrame();
            jf.getContentPane().add( app );
            jf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent keyevent) {
                        //System.out.println("Test key press >>>>>>>>>>>>>>>>>>>>>>>>>>");
                app.s.keyPressed(keyevent);
            }
        });
            jf.setTitle("JaySnake Game by Patrick Crooks at Bolton Institute");
            jf.setResizable(false);
            jf.pack();
            jf.show();
            
   
      }
/*Splash screen graphics method*/

public void splash( Graphics g )

{
  timer++;
    if(Introscreen&&timer<50)
    {
      g.drawImage(intro,125,40,null);
 
    }
 
  }

/*Main graphics method paint*/
      public void paint( Graphics g )
      {              
  super.paint(g);
            g.drawImage(backgroundImage,0,0,null);

//call splash paint method
    splash(g);
            
//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
        s.draw(g);
      }
      
      
}


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 SnakePanel 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(SnakePanel app)
      {
/*Get player name from Input dialogue and pass back to String outName*/
   String name = new String();
   name = JOptionPane.showInputDialog( "Please enter your name" );
   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 e) { }
      }

/* [code]public void actionPerformed[/code] on KeyPress repaint sp snake panel.*/
      public void actionPerformed(ActionEvent event)
      {
            sp.repaint();
      
    }

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

//Collison detection for treat
            if(gameplay)
            {
                  if(location[0].x==treat.x && location[0].y==treat.y)
                  {
                        ate=true;
                        size++;
                        score1++;
                  }
     
// Drawing new head position, erasing last tale position
                  if(location[size-1].x == treat.x && location[size-1].y == treat.y)
                        g.drawImage(food,treat.x*20-20,treat.y*20-20,19,19,null);

//Move snake body parts based on cases of dir (direction)
                  if(gameplay)
                  {
                        for(int i=size; i>0; i--)
                              location[i].move(location[i-1].x, location[i-1].y);

                        switch(dir)
                        {
                              case 0: location[0].x = location[0].x+1; break;
                              case 1: location[0].x = location[0].x-1; break;
                              case 2: location[0].y = location[0].y-1; break;
                              case 3: location[0].y = location[0].y+1; break;
                        }
                  }

// Checking if had just eaten an treat, if yes - draw new treat location
                  if( ate )
                  {
                        ate = false;
//Math.randon generate new apple positions using the co-ordiantes
                        treat.x=(int)(Math.random()*30+1);
                        treat.y=(int)(Math.random()*25+3);
//print co-ordinateds if required
//System.out.println("treat.x = "+treat.x+" treat.y = " +treat.y);
        g.drawImage(food,treat.x*20-20,treat.y*20-20,19,19,null);
                  }
            }

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

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

/*resets game settings including location of snake and apple.  Also updates
 *the Top score and resets player score*/
public void restart()
{
  // 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


Now what I would like to do with this is to split it up into several classes, perhaps to have an interface that will work with my game for keyEvents.  Also you will see that the game works on a grid of Points and I would like to incorporate this into an my game in some way perhaps as an Engine that is run from the game.  Also I have my Snake and my Apples that I perhaps should split up into different classes to be used in the grid.    This question is failry complicated so it may be better if the game is broken up into different parts as you see appropriate.   Then I will post new questions for each part of the of the overall thing.

I am not a Java Genius as I seem to have forgotten more than I originally thought i knew.   Shall we start by redesigning this game and could you please offer me an approach to break this game up into more manageable parts.  Best OOD approach will win.   I would imagine I will need to create about 4 more classes to enable this to work properley and I don't really want to shove it all into the one JaySnake game class if I can help it.

Many thanks all  

pjcrooks2000
0
Comment
Question by:pjcrooks2000
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 35

Accepted Solution

by:
girionis earned 1600 total points
ID: 11891173
I do not think the apples should be represented as different classes. The point with a class (and the objects you will create from it) is that they have state and behaviour. The apple has state (e.g. colour, weight, etc) but not behavior (except if you consider behaviour the growing of an apple). In your game I do not think you will ever need to get information about your apple (i.e. how big it is or what colour it has) so I'd say leave it as it is, just a plain image.

I'd also leave the snake as it is but if you really feel you have to represent it as a class you could since the class can represent the direction of the snake (up, down, left, right) the length of the snake (how many grids it occupies) and the position of the snake (in what grid is the head of snake, i.e. the first part of the snake).

For the keys you could have a separate class to that implements the KeyListener. Then add this class to your frame and every key event will be dispatched there.

For the grid of points I can't think of a better solution. I think the screen is represented fine as it is.

That's my 2 cents, lets wait what other people can say on the design and then you can cross the opinions for the final result :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11891203
Yep oakies to that :)
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 400 total points
ID: 11892126
Sounds right to me
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11892249
Ok then I will hold fore on it for now!  

I am trying to get my Snake class from my old game to work with the new setup!  
0
 
LVL 92

Expert Comment

by:objects
ID: 11898928
Is this question answered? If so then please accept girionis's comment.
If not, let us know further what you need.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11901836
I was waiting for any other advice on the matter at present girionis has it :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11902027
I was looking at the Snake class as a whole to see if it could be broken up into an interface for the Key events.  However a general view was what I was after.  I suppose this will need to be looked at further in the full context of my working game for which I will post about that later.

Girionis's comment on how I should break up my game or indeed not break it up as the Snake and Apple components of my class work on a grid system so perhaps I woul dbe better to keep it all together in my Snake class.

Thanks for the advice all!  
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11902045
:-)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11902050
:) :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11903982
:)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11904033
:) :)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

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

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

Join & Ask a Question