Java
  Home arrow Java arrow Page 6 - Gaming Development Setup
FaxWave - Free Trial.
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Gaming Development Setup
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 31
    2005-03-02

    Table of Contents:
  • Gaming Development Setup
  • Playing the Demo Online
  • Introducing XML
  • Using Open Source
  • Finding Multimedia for Your Games
  • Basics Example
  • Generating an event
  • Drawing the background and target

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    PCmover - $15 Off with Coupon Code CJPH7Q

    Gaming Development Setup - Basics Example
    (Page 6 of 8 )

    Assuming your development environment is set up, you should be able to start creating your own games after reading just this first chapter. You can modify the example game shown in Figure 1-3 to get started.


    Figure 1-3. Basics Example

    The object of this simple game is to launch a ball at a moving target at the top of the screen. You can build and launch this example game using the Ant target basics. In a minimum amount of code, it demonstrates loading media files, drawing shapes and images, displaying text, playing sounds, random number generation, state maintenance, animation, mouse and keyboard input, collision detection, and dirty rectangle management.

    Modifying the Source

    This game is built upon an extensive game library that is described in subsequent chapters. As I review the source code, I will point out which code you can safely modify and which you should leave as is until you have read further. As this example covers most of the Java game programming basics, many readers might find they can simply copy and modify this file to create games successfully without even having to read the next chapter.

    package com.croftsoft.ajgp.basics;

    You can find this game in package com.croftsoft.ajgp.basics. The first thing you want to modify is the package name.

    import java.applet.Applet;
    import java.applet.AudioClip;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.util.Random; import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;

    import com.croftsoft.core.CroftSoftConstants;
    import com.croftsoft.core.animation.AnimatedApplet;
    import com.croftsoft.core.animation.AnimationInit;

    Remove import statements at your own risk. Note that only three custom classes are imported. The rest are all from the Java core.

    public final class BasicsExample
      extends AnimatedApplet
    //////////////////////////////////////////////////////// 
    ///////////////////////////////////////////////////////
    {

    Change the class name but continue to extend the superclass
    AnimatedApplet.

      private static final String VERSION
        = "2003-11-06";

      private static final String TITLE
        = "CroftSoft Basics";

      private static final String APPLET_INFO
        = "\n" + TITLE + "\n"
        + "Version " + VERSION + "\n"
       
    + CroftSoftConstants.COPYRIGHT + "\n"
        + CroftSoftConstants.DEFAULT_LICENSE + "\n"
        + CroftSoftConstants.HOME_PAGE + "\n";

    Change the values for the VERSION, TITLE, and APPLET_INFO.

    private static final Color BACKGROUND_COLOR
      = Color.BLACK;

    private static final Cursor CURSOR
      = new Cursor ( Cursor.CROSSHAIR_CURSOR );

    private static final Font FONT
      = new Font ( "Arioso", Font.BOLD, 20 );

    private static final Double FRAME_RATE
      = new Double ( 30.0 );

    private static final Dimension FRAME_SIZE
      = new Dimension ( 600, 400 );

    private static final String SHUTDOWN_CONFIRMATION_PROMPT
       = "Close " + TITLE + "?";

    You can specify the background color, mouse cursor type, text font, animation speed, window size, and the shutdown confirmation prompt. These constants are passed to superclass AnimatedApplet. You probably want to keep all these constants but customize the values as required.

    private static final String   MEDIA_DIR = "media/basics/";

    private static final String   AUDIO_FILENAME
      = MEDIA_DIR + "drip.wav";

    private static final String   IMAGE_FILENAME
      = MEDIA_DIR + "croftsoft.png";

    Add or remove media file names as required for your game.

    private static final long   RANDOM_SEED = 0L;
    private static final Color  BALL_COLOR = Color.RED;
    private static final Color  SCORE_COLOR = Color.GREEN;
    private static final int    VELOCITY = 3;

    Add or remove additional constants as required for your game. You use the RANDOM_SEED with the random number generator. The VELOCITY is the speed of the bowling ball in pixels per frame.

    private final Rectangle componentBounds;

    private final Random random;

    The variable componentBounds is a Rectangle for storing the width and height of the game screen. Variable random is the random number generator. You probably need these in most of your games.

    private final Rectangle ballRectangle;

    private final Rectangle targetRectangle;

    Variables ballRectangle and targetRectangle are used for collision detection. These variables are game-specific.

    private boolean componentResized;

    private KeyEvent keyEvent;

    private Point mousePoint;

    private boolean mousePressed;

    These variables are used for flagging or storing user input events. You will want to use these in most of your games.

    private AudioClip audioClip;

    private Icon icon;

    You will have an audioClip or icon for each media file you use.

    private boolean rolling;

    private int score;

    These are game-specific state variables. Variable rolling indicates whether the ball has been launched.

    public static void main ( String [ ] args )
    ////////////////////////////////////////////////////
    {
      launch ( new BasicsExample ( ) );
    }

    In the main() method, change the BasicsExample to the name of your new class.

    private static AnimationInit createAnimationInit ( )
    //////////////////////////////////////////////////////

     
      AnimationInit animationInit = new AnimationInit ( );

      animationInit.setAppletInfo ( APPLET_INFO );

      animationInit.setCursor ( CURSOR );

      animationInit.setFont ( FONT );

      animationInit.setFrameIconFilename ( IMAGE_FILENAME );

      animationInit.setFrameRate ( FRAME_RATE );

      animationInit.setFrameSize ( FRAME_SIZE );

      animationInit.setFrameTitle ( TITLE );

      animationInit.setShutdownConfirmationPrompt (
        SHUTDOWN_CONFIRMATION_PROMPT );

      return animationInit;
    }

    The static method createAnimationInit() sets a number of parameters commonly used by the superclass AnimatedApplet. You probably will not need to modify this method.

    public BasicsExample ( ) //////////////////////////////////////////////////////

    {
      super ( createAnimationInit ( ) );

      componentBounds = new Rectangle ( );

      random = new Random ( RANDOM_SEED );

    Change the name of this constructor method to the new name of your class. Keep the initial call to the superclass constructor as is. You almost always need the componentBounds variable. Many games use a random number generator.

    animatedComponent.addComponentListener (
      new ComponentAdapter ( )
      {
        public void componentResized (
        ComponentEvent componentEvent )
      {
        componentResized = true;
      }
    } );

    animatedComponent.addKeyListener (
       new KeyAdapter ( )
      {
        public void keyPressed ( KeyEvent ke )
      { 
        keyEvent = ke;
      }
    } );

    animatedComponent.addMouseListener (
      new MouseAdapter ( )
      {
        public void mousePressed ( MouseEvent mouseEvent )
      {
        mousePressed = true;
      }
    } );

    animatedComponent.addMouseMotionListener (
      new MouseMotionAdapter ( )
      { 
        public void mouseMoved ( MouseEvent mouseEvent )
      {
        mousePoint = mouseEvent.getPoint ( );
      }
    } );

    These methods attach user input event listeners to the animatedComponent. Variable animatedComponent is inherited from the superclass AnimatedApplet. You normally want to have these event listeners in all your games. 

      ballRectangle = new Rectangle ( );

      targetRectangle = new Rectangle ( );
    }

    You can initialize many of your game-specific objects in your constructor method.

    public void init ( )
    //////////////////////////////////////////////////
    {
      super.init ( );

      animatedComponent.requestFocus ( );

      componentResized = true;

    As described in Chapter 2, method init() is called when your game first starts to perform any additional initialization not performed in your constructor method. You generally always want to call the superclass init() method, request the keyboard focus, and set componentResized to true. Setting the componentResized flag is necessary to load the screen width and height into the componentBounds variable for the first time.

    ClassLoader classLoader = getClass ( ).getClassLoader ( );

    audioClip = Applet.newAudioClip (
      classLoader.getResource ( AUDIO_FILENAME ) );

    icon = new ImageIcon (
      classLoader.getResource ( IMAGE_FILENAME ) );

    For reasons explained in subsequent chapters, the creation of some of your media objects must be delayed until the initialization method init() is called, otherwise a NullPointerException might be thrown. This example demonstrates how to load audio and image file data into memory.

      ballRectangle.width    = icon.getIconWidth ( );

      ballRectangle.height   = icon.getIconHeight ( );

      targetRectangle.width  = icon.getIconWidth ( );

      targetRectangle.height = icon.getIconHeight ( );

    }

    The dimensions of the ball and the target are equal to the image dimensions.

    public void update ( JComponent component )
    ////////////////////////////////////////////////////
    {

    As explained in Chapter 3, the update() method is where you perform all your state updates. It is called each time a new frame of animation is required by the game loop. The game loop logic is provided by the superclass AnimatedApplet.

    if ( componentResized )
      {
        componentResized = false;

        component.repaint ( );

        component.getBounds ( componentBounds );

        if ( !rolling )
          {
            ballRectangle.y = componentBounds.height - ballRectangle.height;
          }
      }

    This article is excerpted from Advanced Java Game Programming by David Wallace Croft (Apress, 2004; ISBN 1590591232). Check it out at your favorite bookstore today. Buy this book now.

    More Java Articles
    More By Apress Publishing


     

       

    JAVA ARTICLES

    - The Spring Framework: Understanding IoC
    - Introducing the Spring Framework
    - Java Classes
    - Completing the Syntactic Comparison of Java ...
    - Syntactic Comparison of Java and C/C++
    - Java Statements
    - Conditionals, Expressions and Other Java Ope...
    - Java Operators
    - Primitive Data Types and Basic Language Rule...
    - Java and Object-Oriented Programming
    - Java Beginning Programming
    - Gaming Development Setup
    - Using RPC-Style Web Services with J2EE
    - Integrating XML with J2EE
    - Taming Tiger: Concurrent Collections

    Iron Speed
     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway