Solved

Java games question -  continued

Posted on 2004-08-25
11
254 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
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 35

Accepted Solution

by:
girionis earned 400 total points
Comment Utility
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
Comment Utility
Yep oakies to that :)
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 100 total points
Comment Utility
Sounds right to me
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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
Comment Utility
Is this question answered? If so then please accept girionis's comment.
If not, let us know further what you need.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 8

Author Comment

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

Author Comment

by:pjcrooks2000
Comment Utility
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
Comment Utility
:-)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
:) :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
:) :)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
allStar challenge 1 40
json example 39 108
Checkbox and ListView in Android Layout 4 35
eclipse java  build path 6 16
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now