Package totalcross.game
Class GameEngine
- java.lang.Object
-
- totalcross.ui.gfx.GfxSurface
-
- totalcross.ui.Control
-
- totalcross.ui.Container
-
- totalcross.ui.Window
-
- totalcross.ui.MainWindow
-
- totalcross.game.GameEngine
-
- All Implemented Interfaces:
MainClass
@Deprecated public abstract class GameEngine extends MainWindow
Deprecated.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.
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.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class totalcross.ui.Control
Control.TranslucentShape
-
-
Field Summary
Fields Modifier and Type Field Description protected ImagebgSurfaceDeprecated.static intGAME_ENGINE_VERSIONDeprecated.java.lang.StringgameCreatorIDDeprecated.Game CreatorID.booleangameDoClearScreenDeprecated.True if the screen should be cleared before the onPaint() call.protected booleangameHasUIDeprecated.Must be set to true if the game screen has any control from the totalcross.ui.intgameHighscoresSizeDeprecated.Amount of highscores entries in the highscores database.protected booleangameIsRunningDeprecated.True if the game is running.java.lang.StringgameNameDeprecated.Name of the game.intgameRefreshPeriodDeprecated.Automatic refresh period in milliseconds.intgameVersionDeprecated.Game version.static intNO_AUTO_REFRESHDeprecated.No automatic refresh.-
Fields inherited from class totalcross.ui.MainWindow
firstTimer
-
Fields inherited from class totalcross.ui.Window
_controlEvent, _dragEvent, _focus, _keyEvent, _mouseEvent, _multiEvent, _penEvent, androidBorderThickness, beepIfOut, blocking, borderStyle, cancelPenUp, canDrag, dragThreshold, fadeOtherWindows, fadeValue, firstFocus, flickEnabled, focusOnPenUp, footerColor, footerH, gradientTitleEndColor, gradientTitleStartColor, headerColor, highlighted, highResPrepared, HORIZONTAL_GRADIENT, ignoreEventOfType, keyHook, lastShiftY, lastSwappedContainer, mainSwapContainer, menubar, multiTouching, needsPaint, NO_BORDER, ORIENTATION_INVERTED, ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT, popped, RECT_BORDER, repaintOnSwap, robot, ROUND_BORDER, rTitle, sameBackgroundColor, shiftH, shiftY, SIP_BOTTOM, SIP_HIDE, SIP_SHOW, SIP_TOP, TAB_BORDER, TAB_ONLY_BORDER, tempTitle, title, titleAlign, titleColor, titleFont, titleGap, topMost, VERTICAL_GRADIENT, zStack
-
Fields inherited from class totalcross.ui.Container
alwaysEraseBackground, BACKGROUND_CYLINDRIC_SHADED, BACKGROUND_SHADED, BACKGROUND_SHADED_INV, BACKGROUND_SOLID, backgroundStyle, BORDER_LOWERED, BORDER_NONE, BORDER_RAISED, BORDER_ROUNDED, BORDER_SIMPLE, BORDER_TOP, borderColor, children, controlFound, finishedStart, ignoreOnAddAgain, ignoreOnRemove, insets, lastH, lastScreenWidth, lastW, npback, numChildren, started, tabOrder, tail, TRANSITION_CLOSE, TRANSITION_FADE, TRANSITION_NONE, TRANSITION_OPEN, TRANSITION_TIME, transitionEffect
-
Fields inherited from class totalcross.ui.Control
AFTER, alphaValue, appId, appObj, asContainer, asWindow, backColor, BEFORE, BOTTOM, BOTTOM_OF, BRIGHTER_BACKGROUND, callListenersOnAllTargets, CENTER, CENTER_OF, clearValueInt, clearValueStr, DARKER_BACKGROUND, DP, effect, enableUpdateScreen, esce, eventsEnabled, FILL, fillColor, FIT, floating, fm, fmH, focusHandler, focusLess, focusOnPenDown, focusTraversable, font, FONTSIZE, foreColor, height, ignoreInsets, isHighlighting, isTablet, KEEP, keepDisabled, keepEnabled, LEFT, next, nextTabControl, npParts, offscreen, offscreen0, onEventFirst, parent, PARENTSIZE, PARENTSIZEMAX, PARENTSIZEMIN, PREFERRED, prev, RANGE, repositionAllowed, RIGHT, RIGHT_OF, SAME, SCREENSIZE, SCREENSIZEMAX, SCREENSIZEMIN, setFont, setH, setRel, setW, setX, SETX_NOT_SET, setY, tempW, textShadowColor, TOP, translucentShape, transparentBackground, uiAdjustmentsBasedOnFontHeightIsSupported, uiAndroid, UICONST, uiFlat, uiHolo, uiMaterial, uiVista, visible, width, WILL_RESIZE, x, y
-
-
Constructor Summary
Constructors Constructor Description GameEngine()Deprecated.Creates a new GameEngine
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description TextRenderercreateTextRenderer(Font font, int foreColor, java.lang.String text, int maxDigits)Deprecated.Create a new TextRenderer.TextRenderercreateTextRenderer(Font font, int foreColor, java.lang.String text, int maxDigits, boolean zeroPadding)Deprecated.Create a new TextRenderer.HighScoresgetHighScores()Deprecated.Get the game highscores.OptionsgetOptions()Deprecated.Get a new instance of the game options.voidinitUI()Deprecated.Replace initUI() handling to initialize the engine.
Could not be overloaded. Notifies onGameInit().voidonEvent(Event evt)Deprecated.Replace onEvent handling to identify and notify some usefull game events.
Could not be overloaded.voidonExit()Deprecated.Replace onExit() handling to shutdown the engine.
Could not be overloaded. Notifies onGameExit().voidonGameExit()Deprecated.Event notication called when the game exits.abstract voidonGameInit()Deprecated.Event notication called when the game is initialized.voidonGameStart()Deprecated.Event notication called when the game mainloop is entered.voidonGameStop()Deprecated.Event notication called when the game mainloop is leaved.voidonKey(KeyEvent evt)Deprecated.Event notication called when a key event is signaled.voidonOtherEvent(Event evt)Deprecated.Event notication called when any other event is signaled.voidonPaint(Graphics g)Deprecated.Called at each refresh to draw the current game statevoidonPenDown(PenEvent evt)Deprecated.Event notication called when a pen down event is signaled.voidonPenDrag(PenEvent evt)Deprecated.Event notication called when a pen drag/move event is signaled.voidonPenUp(PenEvent evt)Deprecated.Event notication called when a pen up event is signaled.voidonTimer(TimerEvent evt)Deprecated.Event notication called when a control event is signaled.voidrefresh()Deprecated.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.protected voidsetGameEngine(GameEngine engine)Deprecated.Called just after the GameEngine is constructedvoidstart()Deprecated.Must be called to start the game.voidstop()Deprecated.Must be called to make the game stop.ImageuseBackground(Image bg)Deprecated.Use an image as background.-
Methods inherited from class totalcross.ui.MainWindow
_onMinimize, _onRestore, _onTimerTick, addTimer, addTimer, addTimer, addUpdateListener, appEnding, appStarting, exit, fillBackground, getClientRect, getCommandLine, getDefaultFont, getMainWindow, getScreenShot, initFirebaseInstanceIdService, initFirebaseMessagingService, isMainThread, minimize, onMinimize, onRestore, removeTimer, removeUpdateListener, restore, runOnMainThread, runOnMainThread, setDefaultFont, setRect, setUIStyle
-
Methods inherited from class totalcross.ui.Window
_doPaint, _postEvent, destroyZStack, drawHighlight, getBorderStyle, getClientRect, getDefaultDragThreshold, getFocus, getHighlighted, getPopupCount, getPreferredHeight, getPreferredWidth, getSafeAreaInsets, getTitleFont, getTopMost, handleFocusChangeKeys, isScreenShifted, isSipShown, isSipShown4D, isTopMost, isVisible, loadBehind, makeUnmovable, onClickedOutside, onPopup, onRobotKey, onUnpop, paintTitle, paintWindowBackground, popup, popupMenuBar, popupNonBlocking, postPopup, postPressedEvent, postUnpop, pumpEvents, removeFocus, repaintActiveWindows, resize, resizeHeight, resizeWidth, screenResized, setBorderStyle, setDeviceTitle, setFocus, setGrabPenEvents, setHighlighted, setMenuBar, setOrientation, setSIP, setTitle, setTitleFont, shiftScreen, swap, swapFocus, unpop, validate
-
Methods inherited from class totalcross.ui.Container
add, add, add, add, add, applyTransitionEffect, broadcastEvent, clear, fillBackground, findChild, findNearestChild, findNextFocusControl, getChildren, getChildrenCount, getFirstChild, getFocusableControls, getInsets, incLastX, incLastY, isPressed, moveFocusToNextControl, moveFocusToNextEditable, onAddAgain, onColorsChanged, onRemove, onSwapFinished, paintChildren, remove, removeAll, setEnabled, setFocusTraversable, setHighlighting, setInsets, setNextTransitionEffect, setPressColor, setPressed, swapToTopmostWindow
-
Methods inherited from class totalcross.ui.Control
_onEvent, addEnabledStateListener, addFocusListener, addFontChangeHandler, addGridListener, addHandler, addHighlightListener, addKeyListener, addListContainerListener, addMouseListener, addMultiTouchListener, addPenListener, addPressListener, addPushNotificationListener, addSizeChangeHandler, addTimer, addTimer, addTimerListener, addValueChangeHandler, addWindowListener, bringToFront, changeHighlighted, contains, drawTranslucentBackground, getAbsoluteRect, getBackColor, getDoEffect, getEffectH, getEffectW, getEffectX, getEffectY, getEventListeners, getFont, getForeColor, getGap, getGraphics, getHeight, getNext, getParent, getParentWindow, getPos, getPressedEvent, getPrev, getRect, getSize, getTextShadowColor, getWidth, getX, getX2, getY, getY2, hadParentScrolled, handleGeographicalFocusChangeKeys, hasFocus, internalSetEnabled, intXYWH, isActionEvent, isChildOf, isDisplayed, isEnabled, isFloating, isInsideOrNear, isObscured, isVisibleAndInside, onBoundsChanged, onFontChanged, onWindowPaintFinished, post, postEvent, releaseScreenShot, removeEnabledStateListener, removeFocusListener, removeGridListener, removeHandler, removeHighlightListener, removeKeyListener, removeListContainerListener, removeMouseListener, removeMultiTouchListener, removePenListener, removePressListener, removePushNotificationListener, removeTimerListener, removeWindowListener, repaint, repaintNow, reposition, reposition, repositionChildren, requestFocus, resetSetPositions, resetStyle, safeRepaintNow, safeUpdateScreen, sendToBack, setBackColor, setBackForeColors, setDoEffect, setFloating, setFocusLess, setFont, setForeColor, setNinePatch, setNinePatch, setRect, setRect, setRect, setSet, setTextShadowColor, setTranslucent, setVisible, showTip, takeInitialScreenShot, takeScreenShot, translateFromOrigin, uiStyleChanged, updateScreen, updateTemporary, willOpenKeyboard
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface totalcross.MainClass
_postEvent
-
-
-
-
Field Detail
-
GAME_ENGINE_VERSION
public static final int GAME_ENGINE_VERSION
Deprecated.- See Also:
- Constant Field Values
-
gameName
public java.lang.String gameName
Deprecated.Name of the game.
The Highscores/Options databases are prefixed with this name.
-
gameCreatorID
public java.lang.String gameCreatorID
Deprecated.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
Deprecated.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
Deprecated.Amount of highscores entries in the highscores database.
-
NO_AUTO_REFRESH
public static final int NO_AUTO_REFRESH
Deprecated.No automatic refresh.- See Also:
gameRefreshPeriod, Constant Field Values
-
gameRefreshPeriod
public int gameRefreshPeriod
Deprecated.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
Deprecated.True if the screen should be cleared before the onPaint() call.
-
gameIsRunning
protected boolean gameIsRunning
Deprecated.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
Deprecated.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
Deprecated.
-
-
Method Detail
-
onGameInit
public abstract void onGameInit()
Deprecated.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()
Deprecated.Event notication called when the game exits.
-
onGameStart
public void onGameStart()
Deprecated.Event notication called when the game mainloop is entered.
-
onGameStop
public void onGameStop()
Deprecated.Event notication called when the game mainloop is leaved.- See Also:
stop()
-
onTimer
public void onTimer(TimerEvent evt)
Deprecated.Event notication called when a control event is signaled.- Parameters:
evt- control event that occurred.
-
onKey
public void onKey(KeyEvent evt)
Deprecated.Event notication called when a key event is signaled.- Parameters:
evt- key event that occurred.
-
onPenDown
public void onPenDown(PenEvent evt)
Deprecated.Event notication called when a pen down event is signaled.- Parameters:
evt- pen event that occurred.
-
onPenUp
public void onPenUp(PenEvent evt)
Deprecated.Event notication called when a pen up event is signaled.- Parameters:
evt- pen event that occurred.
-
onPenDrag
public void onPenDrag(PenEvent evt)
Deprecated.Event notication called when a pen drag/move event is signaled.- Parameters:
evt- pen event that occurred.
-
onOtherEvent
public void onOtherEvent(Event evt)
Deprecated.Event notication called when any other event is signaled.- Parameters:
evt- event that occurred.
-
onPaint
public void onPaint(Graphics g)
Deprecated.Called at each refresh to draw the current game state
-
getHighScores
public HighScores getHighScores()
Deprecated.Get the game highscores.- Returns:
- HighScores.
-
getOptions
public Options getOptions()
Deprecated.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
Deprecated.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
Deprecated.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()
Deprecated.Must be called to start the game.
-
stop
public final void stop()
Deprecated.Must be called to make the game stop.
-
refresh
public final void refresh()
Deprecated.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)
Deprecated.Called just after the GameEngine is constructed
-
initUI
public final void initUI()
Deprecated.Replace initUI() handling to initialize the engine.
Could not be overloaded. Notifies onGameInit().
-
onExit
public final void onExit()
Deprecated.Replace onExit() handling to shutdown the engine.
Could not be overloaded. Notifies onGameExit().- Overrides:
onExitin classMainWindow
-
useBackground
public Image useBackground(Image bg) throws ImageException
Deprecated.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
-
-