Class GameEngine

  • All Implemented Interfaces:
    MainClass

    public abstract class GameEngine
    extends MainWindow
    This abstract class represents the game API engine.
     Version 1.1 of the GameEngine features:
     
    • Highscores management.
    • Versionned options management of String, Integer, Double and Boolean types.
    • Quick text display through text pre-rendering for game status & score display.
    • Sprite/animated sprite support.
    • Animation control.
    • AnimatedButton control.
    • Game framework extending the TotalCross MainWindow.
    You can find a complete game API sample named 'Ping' in the TotalCross samples folder.
    NOTE: This sample may be used as a skeleton for your own game development and the source reading may be much helpful to understand this framework. You also can change the game settings at the top of the file 'Ping.java' to experiment the different game API behaviours.
    Further i recommand the reading of the TotalCross game API tutorial that gives many details on this framework use. 1) GAME FRAMEWORK DESCRIPTION Basically the game engine consists in a class that extends TotalCross's MainWindow. This class is named GameEngine and provides many game oriented services like game settings and game highscores management. You won't have to access the game associated settings nor the highscore databases directly, you will have to use HighScores and Options interfaces instead. This services are retrievable by the getHisghscores() and the getOptions() calls.
    2) GAME SETUP A game using this API has to extend the GameEngine class, like this: public class MyOwnGame extends GameEngine { ... } to setup the game engine, you will have to provide some information. These information are defined through the following GameEngine member variables: -gameName the name of the game, this information is used to name the game associated databases. -gameCreatorID the creatorID of the game -gameVersion the game version number -gameHighscoresSize number of best scores to save in the highscores database -gameRefreshPeriod refresh period in milliseconds for action games, or NO_AUTO_REFRESH for non animated games. -gameDoClearScreen enable/disable the whole screen erasing between frames displays. -gameHasUI declare UI uses, if false the drawing is improved You see below the definition of a the sample game named "Scape": import totalcross.game.*; import totalcross.util.props.*; ... public class Ping extends GameEngine { // constructor public Ping() { totalcross.sys.Settings.setPalmOSStyle(true); // define the game API setup attributes gameName = "Scape"; // when not run on device, appCreatorId does not always return the same value. gameCreatorID = Settings.onJavaSE ? totalcross.sys.Settings.appCreatorId:"Scpe"; gameVersion = 100; // v1.00 gameHighscoresSize = 7; // store the best 7 highscores gameRefreshPeriod = 75; // 75 ms refresh periods gameIsDoubleBuffered = true; // used double buffering to prevent flashing display gameDoClearScreen = true; // screen is cleared before each frame display gameHasUI = false; // no UI elements, frame displays are optimized ... } 3) GAME FRAMEWORK DETAILS The GameEngine class traps many TotalCross event handler functions to fulfill tasks behind the scenes. Thus the following TotalCross functions cannot be overloaded in your game's main window: void initUI (); void onExit (); void onEvent (Event ev); they are replaced by the following game API functions that may be overloaded : void onGameInit (); void onGameExit (); void onKey (KeyEvent evt); void onPenDown (PenEvent evt); void onPenUp (PenEvent evt); void onPenDrag (PenEvent evt); void onTimer (ControlEvent evt); void onOtherEvent (Event evt); The framework extends the event handlers to provide game specific events, such as: void onGameStart (); void onGameStop (); The first one is called when the game mainloop starts (when the game enters the "run mode"), the second one when the run mode is leaved. You can control (run/stop) and retrieve the current state by the game API functions and fields: void start (); void stop (); boolean gameIsRunning; The game API supports both arcade games that are "time driven" (a timer causes frequent screen refreshes to get an animation of the game elements/objects) and "static" games such as cards, puzzles, etc. When entering the game run mode by the start() call, time based games arm a timer that causes scheduled calls to your overloaded onPaint() to draw a new frame/image.
    On static games that may be designated as "user event driven" refreshes have to be launched by an explicit call of refresh() that also causes the call of your overloaded onPaint() to draw a new frame/image. Static games can also use timers to signal the end of a reflection time, etc.
    4) GAME SPRITES A Sprite is a graphical object typicaly used in games that can be moved, with collision detection feature and background saving/restoring capability. To create a sprite you will have to provide an Image object, it's transparency color if needed (DRAW_SPRITE mode), a flag indicating if the background have to be saved (required if screen clearing is disabled as far as the screen is not erased to be redrawn completly) and the sprite valid positions area (Rect). You may also have to define the drawOp for the Sprite drawing. It's common values are:
  • USE_CURRENT_DRAWOP default
  • DRAW_SPRITE
  • DRAW_PAINT You can override the onPositionChange() method to manage valid positions, collisions, bounces or any other object position based condition.
    The default implementation checks position validity by using the region argument of the sprite constructor. see the "Scape" source code for more details. When background saving is enabled, each sprite display with the show() method restores any previously saved background.
    In some games, sprites may overlap... if you write such a game, you may have to call the sprite hide() method explicitly (which is not necessary in the common usage) in the reverse draw order to restore the background. 5) ANIMATIONS This Animation control provides an image sequence display. You can handle the animation frames displays by your own, or call one of the several start() methods provided to launch a thread driven animation. The animation is composed by a collection of Image objects that can be loaded from indexed BMP files (one frame per image) or from a so-called multi-image bitmap. It is an image format that contains all the animation frames side by side. All the images share a same color palette and must have the same size. 6) ANIMATED BUTTONS The AnimatedButton class is a button implementation that extends the Animation class. It uses an animation containing the different states of the button and their transition frames in a specific layout.
    • Field Detail

      • gameName

        public java.lang.String gameName
        Name of the game.
        The Highscores/Options databases are prefixed with this name.
      • gameCreatorID

        public java.lang.String gameCreatorID
        Game CreatorID.
        The Highscores/Options databases references are created with this ID.
        This must be a String with exactly four characters. This has the effect to link the databases to the game software causing an automatic database removal when the application is deleted from the device.
      • gameVersion

        public int gameVersion
        Game version.
        This information is written in the Options database and may be compared to it's old version retrievable by the getOldVersion() function of the Options interface. E.g. 100 for 1.00)
      • gameHighscoresSize

        public int gameHighscoresSize
        Amount of highscores entries in the highscores database.
      • gameRefreshPeriod

        public int gameRefreshPeriod
        Automatic refresh period in milliseconds.
        The NO_AUTO_REFRESH value prevents the engine to do time based refreshes. You will have to call explicitly the refresh() function to force a screen repainting.
        See Also:
        refresh()
      • gameDoClearScreen

        public boolean gameDoClearScreen
        True if the screen should be cleared before the onPaint() call.
      • gameIsRunning

        protected boolean gameIsRunning
        True if the game is running. Set by the GameEngineMainWindow. To stop or start the game use the methods stop or run. Setting this variable has no effect.
      • gameHasUI

        protected boolean gameHasUI
        Must be set to true if the game screen has any control from the totalcross.ui. package. Complex games should not have UI elements
      • bgSurface

        protected Image bgSurface
    • Constructor Detail

      • GameEngine

        public GameEngine()
        Creates a new GameEngine
    • Method Detail

      • onGameInit

        public abstract void onGameInit()
        Event notication called when the game is initialized.
        It's the first place where API calls can take place because the game engine has been initialized.
        You can do game initialization at this place. Typically Sprites may be created in the overloaded function.
      • onGameExit

        public void onGameExit()
        Event notication called when the game exits.
      • onGameStart

        public void onGameStart()
        Event notication called when the game mainloop is entered.
      • onGameStop

        public void onGameStop()
        Event notication called when the game mainloop is leaved.
        See Also:
        stop()
      • onTimer

        public void onTimer​(TimerEvent evt)
        Event notication called when a control event is signaled.
        Parameters:
        evt - control event that occurred.
      • onKey

        public void onKey​(KeyEvent evt)
        Event notication called when a key event is signaled.
        Parameters:
        evt - key event that occurred.
      • onPenDown

        public void onPenDown​(PenEvent evt)
        Event notication called when a pen down event is signaled.
        Parameters:
        evt - pen event that occurred.
      • onPenUp

        public void onPenUp​(PenEvent evt)
        Event notication called when a pen up event is signaled.
        Parameters:
        evt - pen event that occurred.
      • onPenDrag

        public void onPenDrag​(PenEvent evt)
        Event notication called when a pen drag/move event is signaled.
        Parameters:
        evt - pen event that occurred.
      • onOtherEvent

        public void onOtherEvent​(Event evt)
        Event notication called when any other event is signaled.
        Parameters:
        evt - event that occurred.
      • onPaint

        public void onPaint​(Graphics g)
        Called at each refresh to draw the current game state
        Overrides:
        onPaint in class Container
        Parameters:
        g - the graphics object for drawing
        See Also:
        Graphics
      • getHighScores

        public HighScores getHighScores()
        Get the game highscores.
        Returns:
        HighScores.
      • getOptions

        public Options getOptions()
        Get a new instance of the game options.
        Returns:
        Options.
      • createTextRenderer

        public final TextRenderer createTextRenderer​(Font font,
                                                     int foreColor,
                                                     java.lang.String text,
                                                     int maxDigits)
                                              throws ImageException
        Create a new TextRenderer. A TextRenderer performs a fast String display with an optional integer value.
        Parameters:
        font - to display with.
        foreColor - text color, may be null.
        text - to render.
        maxDigits - digits to display.
        Returns:
        a new TextRenderer.
        Throws:
        ImageException
        See Also:
        TextRenderer for more information
      • createTextRenderer

        public final TextRenderer createTextRenderer​(Font font,
                                                     int foreColor,
                                                     java.lang.String text,
                                                     int maxDigits,
                                                     boolean zeroPadding)
                                              throws ImageException
        Create a new TextRenderer. A TextRenderer performs a fast String display with an optional integer value.
        Parameters:
        font - to display with.
        foreColor - text color, may be null.
        text - to render.
        maxDigits - digits to display.
        zeroPadding - pad with leading zeros.
        Returns:
        a new TextRenderer.
        Throws:
        ImageException
        See Also:
        TextRenderer for more information
      • start

        public final void start()
        Must be called to start the game.
      • stop

        public final void stop()
        Must be called to make the game stop.
      • refresh

        public final void refresh()
        This function causes an onPaint() call to draw a new frame.
        This function has to be called in non time based games to refresh the complete screen.
      • setGameEngine

        protected void setGameEngine​(GameEngine engine)
        Called just after the GameEngine is constructed
      • initUI

        public final void initUI()
        Replace initUI() handling to initialize the engine.
        Could not be overloaded. Notifies onGameInit().
        Overrides:
        initUI in class Container
      • onExit

        public final void onExit()
        Replace onExit() handling to shutdown the engine.
        Could not be overloaded. Notifies onGameExit().
        Overrides:
        onExit in class MainWindow
      • useBackground

        public Image useBackground​(Image bg)
                            throws ImageException
        Use an image as background.
        The provided image is scaled if required to the screen size and displayed at each frame refresh. NOTE: the "gameHasUI" also have to be set to false to support this feature
        Throws:
        ImageException
      • onEvent

        public final void onEvent​(Event evt)
        Replace onEvent handling to identify and notify some usefull game events.
        Could not be overloaded.
        Overrides:
        onEvent in class Control
        Parameters:
        evt - event that occurs.
        See Also:
        Event, KeyEvent, PenEvent