You are here: JGT Tutorial > 3. First step: creating a game

Lesson 1: Your Spaceship

In this lesson we are going to create the game and put a spaceship in it, that we can move using the keyboard. This will take several steps; the first step is to create the game.

First step: creating a game

The Java Game Toybox already has all the necessary tools to set up a game environment, so all that we have to do is to call these functions. Let's do that in our first step, and have a "game" that shows a window on the screen.

The main thing to remember is that we use the class BaseApp for this purpose (clicking the link will take you to the javadoc for this class; you don't need the javadoc to follow the tutorial). The figure below shows the code, you can cut and paste it into your editor. Don't worry about the amount of text, most of it is boilerplate.

import java.awt.*;
import com.jpemartin.jtb.*;

/** my new game */
public class MyGame extends BaseApp {

   /** for BaseApp **/
   public String getName() {
      return "MyGame";
   }
   
   public int getWidth() { return 200; }
   public int getHeight() { return 200; }

   /** main game loop **/
   public void run() {
      createImageAndGraphics(); 
      while (_gameRunning) {
         drawWorld();
         showAndWait();
      }
   }
   
   /** draw what the player sees **/
   public void drawWorld() {
      if (null==_dbImage) return;
      synchronized(_dbImage) {
         _dbg.setColor(Color.GREEN);
         _dbg.fillRect(0, 0, getWidth(), getHeight());
         
      }
   }
   
   static public void main(String argv[]) {
      new MyGame().runAsApplet(argv); 
   }
}
When you run the code above, you should see the following:

The code above is boilerplate, except for three things. First, the getName() function determines what is in the title bar of your game. Right now it returns "MyGame" but if you were to change it to, for example, "cool game", then when you recompile and rerun the game you'll see that the window title has changed.

Second, the getWidth() and getHeight() return the size of the game window. 200 by 200 is probably a bit small, so we'll want to increase it for example to 300 by 300.

Third, the drawWorld() function is where the actual game will be. Right now all this does is draw an uniform green background (if you change the color to Color.BLUE you'll see a blue background instead). In the next steps of the tutorial we'll add code there to draw an actual game.

The main loop is contained in the run() function. The while() loop will run until the user closes the game window (BaseApp will then set _gameRunning to false).In the main loop, we repeatedly call drawWorld to draw the current picture, and then we call showAndWait() to show the picture and wait the appropriate amount of time -- by default that's 20ms, so the game will run at 50 frames per second.

Next: The Spaceship