You are here

Chapter 11: Implement the GameEngine

Finally it's time for some Java coding!

Start with removing the three "Toast.makeText" lines from, as we already tested the page navigation and I only added them to show an example of the simplest possible tracing functionality.

I also set back "Project Build Target" to Android 2.1, so that Eclipse is able to stop me from writing code that won't work on 2.1.

Given that, I must also comment out the AdActivity from the manifest file. (I will put it back before publishing the app):

Ok, let's start coding.
Right click on your package, select New -> Class and name it "GameEngine".
Paste in the following code:
package com.ajomannen.justroids;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;

public class GameEngine {

  public float screenWidth;
  public float screenHeight;
  private Paint blackPaint;
  private Paint textPaint;
  private String currentTimeString;

  public void Init(Context context) {
    setSurfaceDimensions(240, 160);

    blackPaint = new Paint();

    textPaint = new Paint();

  public void onDestroy() {
    try {
    } catch (Exception e) {

  public void setSurfaceDimensions(int width, int height) {
    screenWidth = width;
    screenHeight = height;

  public void Update() {
    currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());

  public void Draw(Canvas canvas) {
    canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), blackPaint);
    canvas.drawText(currentTimeString, 30, 100, textPaint);

What we have done here is the bare minimums; 
  • An Init method, in which we handle everything that needs to be set up at program startup.
  • An onDestroy event handler, which is currently empty.
  • A setSurfaceDimensions that we need to call from our future GameSurface class.
  • The classic Update and Draw methods, that are the core in any real-time game.

(Just to have something to update and draw, I put the current time into a text string and draw it onto screen.)


Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer