Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple game engine using Canvas for Android - using for quick prototype or simple games
package com.gamarist.momoney;
import android.os.Bundle;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
public class MoMoney extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameView(this));
}
}
class GameView extends View {
private GameLoop mainLoop;
Bitmap gameBitmap;
Canvas gameCanvas;
public GameView(Context context) {
super(context);
this.setDrawingCacheEnabled(true);
gameCanvas = new Canvas();
mainLoop = new GameLoop(getResources(), gameCanvas);
mainLoop.start();
}
@SuppressLint("DrawAllocation") @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = MeasureSpec.getSize(heightMeasureSpec);
gameBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
gameCanvas.setBitmap(gameBitmap);
setMeasuredDimension(w, h);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawBitmap(gameBitmap, 0, 0, new Paint());
invalidate();
}
}
class GameLoop extends Thread {
private float frameRate = 60;
private float frameTime = 1000 / frameRate;
private Game logicGame;
private Resources gameResources;
private Canvas gameCanvas;
public GameLoop(Resources res, Canvas canvas) {
logicGame = new Game(res, canvas);
}
@Override
public void run()
{
while (true) {
float startTime = System.currentTimeMillis();
logicGame.Update();
logicGame.Draw();
float endTime = System.currentTimeMillis();
long deltaTime = (long) (frameTime - (endTime - startTime));
try {
Thread.sleep(deltaTime);
} catch (InterruptedException e) {
}
}
}
}
class Game {
private Resources resources;
private Canvas canvas;
private int x = 0;
private Paint paint;
public Game(Resources res, Canvas cas) {
resources = res;
canvas = cas;
paint = new Paint();
paint.setTextSize(50);
}
public void Draw() {
canvas.drawColor(Color.WHITE);
canvas.drawRect(new Rect(x, 0, x + 50, 50), paint);
}
public void Update() {
x += 1;
Log.d("DEBUG", "X: " + x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.