Home arrow Java & J2EE arrow Page 6 - Gaming Development Setup

Basics Example - Java

One important step in creating your own computer games is configuring your development environment. Keep reading to learn how. This article is taken from chapter one of Advanced Java Game Programming by David Wallace Croft (Apress, 2004; ISBN 1590591232).

  1. Gaming Development Setup
  2. Playing the Demo Online
  3. Introducing XML
  4. Using Open Source
  5. Finding Multimedia for Your Games
  6. Basics Example
  7. Generating an event
  8. Drawing the background and target
By: Apress Publishing
Rating: starstarstarstarstar / 33
March 02, 2005

print this article



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

  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 (

  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 & J2EE Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates


Dev Shed Tutorial Topics: