0
\$\begingroup\$

In the same project as in my previous questions I have released a new beta ("0.1.24b") of the game we call "Moon Buggy". It is now possible to get the background to change when completing a section, so that you can reach the Future City. I was wondering if there is an "idiomatic" way to create sections/levels because I will use if...else if... to check which section ini the game that has been completed.

if (ParallaxView.sectionComplete == 1)
    bg = view.backgroundsSection2.get(position);
else
    bg = view.backgrounds.get(position);

So in the above way the background changes when the player has completed a section/level.

The code in context is as follows.

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;

import java.util.Timer;

public class BackgroundHandler {


    public void drawBackground(int position, ParallaxView view, Canvas canvas, Paint paint) {

        MoonBackground bg;

        // Make a copy of the relevant background
        if (ParallaxView.sectionComplete == 1)
            bg = view.backgroundsSection2.get(position);
        else
            bg = view.backgrounds.get(position);

        // define what portion of images to capture and
        // what coordinates of screen to draw them at

        // For the regular bitmap
        view.fromRect1 = new Rect(0, 0, bg.width - bg.xClip, bg.height);
        view.toRect1 = new Rect(bg.xClip, bg.startY, bg.width, bg.endY);

        // For the reversed background
        view.fromRect2 = new Rect(bg.width - bg.xClip, 0, bg.width, bg.height);
        view.toRect2 = new Rect(0, bg.startY, bg.xClip, bg.endY);

        //draw the three background bitmaps
        if (!bg.reversedFirst) {
            if (position == 1) {
                canvas.drawBitmap(bg.bitmap, view.fromRect1, view.toRect1, paint);
            } else
            if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'E' && position == 2) {
                //canvas.drawBitmap(bg.bitmap, fromRect1, toRect1, paint);
                canvas.drawBitmap(bg.bitmap2, view.fromRect1, view.toRect1, paint);
            } else {
                canvas.drawBitmap(bg.bitmap, view.fromRect1, view.toRect1, paint);
            }
            canvas.drawBitmap(bg.bitmapReversed, view.fromRect2, view.toRect2, paint);

            if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(view.spacerock3, view.toRect1.left, view.toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(view.spacerock2, view.toRect1.left, view.toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(view.spacerock, view.toRect1.left, view.toRect1.top, paint);
            }
            if (position == 2) {
                paint.setTextSize(160);
                if (MoonBackground.checkpoint <= 'Z' && MoonBackground.checkpoint >= 'A') {
                    canvas.drawText(Character.toString(MoonBackground.checkpoint), bg.xClip, (float) (bg.startY * 1.4), paint);
                }
                if (view.increment) {
                    MoonBackground.checkpoint++;
                    view.toggleGround = true;
                }
                if (MoonBackground.checkpoint == 'B' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.passed = true;
                }

                if (MoonBackground.checkpoint == 'E' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.checkpointComplete = true;
                    view.toggleGround = false;
                    canvas.drawColor(Color.BLACK);
                    return;
                } else if (MoonBackground.checkpoint == 'J' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.checkpointComplete = true;
                    canvas.drawColor(Color.BLACK);
                    return;
                } else if (MoonBackground.checkpoint == 'O' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.checkpointComplete = true;
                    canvas.drawColor(Color.BLACK);
                    return;
                } else if (MoonBackground.checkpoint == 'T' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.checkpointComplete = true;
                    canvas.drawColor(Color.BLACK);
                    return;
                } else if (MoonBackground.checkpoint == 'Z' && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < view.moonRover.getBitmapRover().getWidth()) {
                    view.checkpointComplete = true;
                    canvas.drawColor(Color.BLACK);
                    return;
                }
                view.increment = false;
                if (bg.xClip == bg.width) view.increment = true;
                ((Activity) view.getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        view.tvId1.setText(Character.toString(MoonBackground.checkpoint));
                    }
                });
            }
        } else {

            if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'E' && position == 2)
                canvas.drawBitmap(bg.bitmap2, view.fromRect2, view.toRect2, paint);
            else
                canvas.drawBitmap(bg.bitmap, view.fromRect2, view.toRect2, paint);

            canvas.drawBitmap(bg.bitmapReversed, view.fromRect1, view.toRect1, paint);
            if (MoonBackground.checkpoint != '@' && position == 2 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && MoonBackground.checkpoint != 'C' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') {
                //if buggy collides with moon rock 3
                if (!view.waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !view.recent && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((view.screenHeight * 0.5) - view.moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip)) < view.moonRover.getBitmapRover().getWidth()) {
                    canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
                    view.bombed--;
                    view.recent = true;
                    view.waitForTimer = true;
                    view.bexplode = true;
                    view.moonRover.explode(canvas, paint, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight());
                    view.moonRover.setDistanceDelta(1.15);
                    view.moonRover.setRetardation(0.5);
                    view.jumpHeight = 0;
                    view.moonRover.setJumpHeight(0);
                    ((Activity) view.getContext()).runOnUiThread(() -> {
                        Handler handler = new Handler();
                        handler.postDelayed(() -> {
                            view.waitForTimer = false;
                            view.moonRover.setBuggyXdistance(0);
                            view.bexplode = false;
                        }, 2000);
                    });
                    new Timer().schedule(new ParallaxView.SetRecent(), 10000);
                    new Timer().schedule(new ParallaxView.ResetCheckpoint(), 1000);
                }

                canvas.drawBitmap(view.spacerock3, view.toRect1.left, view.toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && position == 2 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') {
                canvas.drawBitmap(view.spacerock2, view.toRect1.left, view.toRect1.top, paint);
                //if buggy collides with moon rock 2
                if (!view.waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !view.recent && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((view.screenHeight * 0.5) - view.moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip)) < view.moonRover.getBitmapRover().getWidth()) { // && java.lang.Math.abs((alienBombY + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {
                    //canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint);
                    view.moonRover.explode(canvas, paint, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight());
                    view.bombed--;
                    view.recent = true;
                    view.waitForTimer = true;
                    view.bexplode = true;
                    canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
                    view.moonRover.setDistanceDelta(1.15);
                    view.moonRover.setRetardation(0.5);
                    view.jumpHeight = 0;
                    view.moonRover.setJumpHeight(0);
                    ((Activity) view.getContext()).runOnUiThread(() -> {
                        Handler handler = new Handler();
                        handler.postDelayed(() -> {
                            view.waitForTimer = false;
                            view.moonRover.setBuggyXdistance(0);
                            view.bexplode = false;
                        }, 2000);
                    });
                    new Timer().schedule(new ParallaxView.SetRecent(), 10000);
                    new Timer().schedule(new ParallaxView.ResetCheckpoint(), 1000);
                }

            } else if (MoonBackground.checkpoint != '@' && position == 2 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') {
                canvas.drawBitmap(view.spacerock, view.toRect1.left, view.toRect1.top, paint);
                //if buggy collides with moon rock 1
                if (!view.waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !view.recent && (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((view.screenHeight * 0.5) - view.moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((view.buggyXDisplacement + view.moonRover.getBuggyXdistance()) - (bg.xClip)) < view.moonRover.getBitmapRover().getWidth()) { // && java.lang.Math.abs((alienBombY + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {
                    view.moonRover.explode(canvas, paint, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight());
                    view.bombed--;
                    view.recent = true;
                    view.waitForTimer = true;
                    view.bexplode = true;
                    view.moonRover.setDistanceDelta(1.15);
                    view.moonRover.setRetardation(0.5);
                    view.moonRover.setJumpHeight(0);
                    ((Activity) view.getContext()).runOnUiThread(() -> {
                        Handler handler = new Handler();
                        handler.postDelayed(() -> {
                            view.waitForTimer = false;
                            view.moonRover.setBuggyXdistance(0);
                            view.bexplode = false;
                        }, 2000);
                    });
                    new Timer().schedule(new ParallaxView.SetRecent(), 10000);
                    new Timer().schedule(new ParallaxView.ResetCheckpoint(), 1000);
                }
            }
        }

        // collide with holes when there are holes
        if (!view.waitForTimer && !UFO.recent && bg.reversedFirst && !UFO.recent && position == 2 && view.moonRover.getJumpHeight() < 20 && java.lang.Math.abs(view.moonRover.getBuggyXdistance() + view.craterX + java.lang.Math.abs(bg.xClip - bg.width)) < 20) {
            canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
            view.bombed--;
            view.recent = true;
            view.waitForTimer = true;
            view.bexplode = true;
            canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
            view.moonRover.setDistanceDelta(1.15);
            view.moonRover.setRetardation(0.5);
            view.jumpHeight = 0;
            view.moonRover.setJumpHeight(0);
            ((Activity) view.getContext()).runOnUiThread(() -> {
                Handler handler = new Handler();
                handler.postDelayed(() -> {
                    view.waitForTimer = false;
                    view.moonRover.setBuggyXdistance(0);
                    view.bexplode = false;
                }, 2000);
            });
            new Timer().schedule(new ParallaxView.SetRecent(), 10000);
            new Timer().schedule(new ParallaxView.ResetCheckpoint(), 1000);
        }
        //Log.d("## hole", "hole " + (int) ((buggyXDistance) + bg.xClip -bg.width));
        if (!view.recent && view.moonRover.getJumpHeight() < 30 && position == 2 && !bg.reversedFirst && (java.lang.Math.abs((view.moonRover.getBuggyXdistance() + view.craterX) - java.lang.Math.abs(bg.xClip)) < 15)) // >1
        {
            canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
            // MoonBackground.checkpoint = 'A';
            view.bombed--;
            view.recent = true;
            view.waitForTimer = true;
            view.bexplode = true;
            canvas.drawBitmap(view.explode, (float) (view.buggyXDisplacement + view.moonRover.getBuggyXdistance()), (float) (view.screenHeight * 0.5) - view.moonRover.getJumpHeight(), paint);
            view.moonRover.setDistanceDelta(1.15);
            view.moonRover.setRetardation(0.5);
            view.moonRover.setJumpHeight(0);
            ((Activity) view.getContext()).runOnUiThread(() -> {
                Handler handler = new Handler();
                handler.postDelayed(() -> {
                    view.waitForTimer = false;
                    view.moonRover.setBuggyXdistance(0);
                    view.bexplode = false;
                }, 2000);
            });
            new Timer().schedule(new ParallaxView.SetRecent(), 10000);
            new Timer().schedule(new ParallaxView.ResetCheckpoint(), 1000);
        }
    }

}

The background handler is used in the parallax view class.

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ParallaxView extends SurfaceView implements Runnable, SurfaceHolder.Callback {

    static int bombed = 5;

    Rect fromRect1;
    Rect toRect1;
    Rect fromRect2;
    Rect toRect2;

    boolean enemyForward = true;
    boolean runOnce2 = true;
    boolean waitForTimer = false;
    static boolean recent = false;
    boolean increment = false;
    boolean toggleDeltaY = true;
    boolean toggleGround = true;
    boolean jump = false;
    boolean shoot = false;
    boolean enemyTankShoot = false;
    boolean checkpointComplete = false;
    boolean runOnce = true;
    boolean passed = false;
    boolean donotdrawBuggy = false; // keep track of whether to not draw anything at all during the wait between being bombed and getting a new life
    boolean bexplode = false;
    boolean brake = false;
    boolean scoring = false;

    final int buggyXDisplacement = 450;
    int numberOfshots = 0; // change to 0
    int numberOfEnemyTankshots = 0; // change to 0
    int[] missiles = new int[200];
    int[] enemyTankmissiles = new int[200];

    int enemyTankIndex = 0;
    int index = 0;

    int missileOffSetY = 0;
    int jumpHeight = 0;
    int enemyTankxbuggy2 = 0;
    int xbuggy2 = 0;

    int craterX = -550;
    int moondRockSmallId, resID, explodeID, explodeID2, alienResID2, missileRightId, missileUpId, enemyTankId;
    static int sectionComplete = 0;

    long lastTurn2 = System.currentTimeMillis();
    long lastTurn3 = System.currentTimeMillis();

    TextView tvId1;

    static int score = 0;
    double lastTurn4 = System.currentTimeMillis();
    List<MoonBackground> backgrounds;
    List<MoonBackground> backgroundsSection2;
    List<UFO> ufos;

    private volatile boolean running;
    private Thread gameThread = null;
    Bitmap explode, explode2, spacerock, spacerock3, spacerock2, hole, missileRight, missileUp;

    TextView tvId;
    TextView checkpointtextview;
    TextView checkpointtextview2;
    TextView checkpointtextview3;
    TextView checkpointtextview4;
    TextView checkpointtextview5;
    TextView checkpointtextview6;
    // For drawing
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder ourHolder;
    UFO ufo;
    UFO ufo1;
    UFO ufo2;
    EnemyTank enemyTank;
    // Holds a reference to the Activity
    Context context;
    ScreenDimension screenDimension;

    // Control the fps
    long fps = 60;

    MoonRover moonRover;
    BackgroundHandler bgh = new BackgroundHandler();
    // Screen resolution
    int screenWidth;
    int screenHeight;

    public MoonRover getMoonRover() {
        return moonRover;
    }

    // use Handler instead
    static class SetRecent extends TimerTask {
        public void run() {
            recent = false;
        }
    }

    // use Handler instead
    static class ResetCheckpoint extends TimerTask {
        public void run() {
            if (sectionComplete == 0) MoonBackground.checkpoint = 'A';
            if (sectionComplete == 1) MoonBackground.checkpoint = 'F';
            if (sectionComplete == 2) MoonBackground.checkpoint = 'K';
            if (sectionComplete == 3) MoonBackground.checkpoint = 'P';
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    public void surfaceDestroyed(SurfaceHolder holder3) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    public void surfaceChanged(SurfaceHolder holder, int i1, int i2, int i3) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    private void update() {
        // Update all the background positions

        if (ParallaxView.sectionComplete == 1) {
            for (MoonBackground bg : backgroundsSection2) {
                bg.update(fps);
            }

        } else {

              for (MoonBackground bg : backgrounds) {
                bg.update(fps);
            }

        }


    }

    public ParallaxView(Context c, AttributeSet a) {
        super(c, a);
        this.context = c;
        MoonBackground.checkpoint--; // why?
        this.screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        this.screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
        screenDimension = new ScreenDimension(getContext().getResources().getDisplayMetrics().widthPixels, getContext().getResources().getDisplayMetrics().heightPixels);
        // Initialize our drawing objects
        ourHolder = getHolder();
        paint = new Paint();

        // Initialize our arraylist
        backgrounds = new ArrayList<>();
        backgroundsSection2 = new ArrayList<>();

        //load the background data into the MoonBackground objects and
        // place them in our GameObject arraylist

        backgrounds.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "galaxy_set1", 0, 120, 50));

        backgrounds.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "mountains_set1", 40, 80, 70)); //use relative values instead?


        backgrounds.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "grass", 70, 110, 200));

        backgroundsSection2.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "galaxy_set3", 0, 120, 50));

        backgroundsSection2.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "future_city", 0, 80, 70)); //use relative values instead?


        backgroundsSection2.add(new MoonBackground(
                this.context,
                screenWidth,
                screenHeight,
                "terrain_plain", 70, 110, 200));

        resID = context.getResources().getIdentifier("vehicle",
                "drawable", context.getPackageName());
        explodeID = context.getResources().getIdentifier("explode",
                "drawable", context.getPackageName());
        explodeID2 = context.getResources().getIdentifier("explode2",
                "drawable", context.getPackageName());
        moondRockSmallId = context.getResources().getIdentifier("spacerock",
                "drawable", context.getPackageName());

        missileRightId = context.getResources().getIdentifier("missile_right",
                "drawable", context.getPackageName());
        missileUpId = context.getResources().getIdentifier("missile_up",
                "drawable", context.getPackageName());


        int spacerock2i = context.getResources().getIdentifier("rock2_hdpi",
                "drawable", context.getPackageName());

        int spacerock3i = context.getResources().getIdentifier("rock3_hdpi",
                "drawable", context.getPackageName());

        int holeid = context.getResources().getIdentifier("hole",
                "drawable", context.getPackageName());
        //buggy = BitmapFactory.decodeResource(context.getResources(), resID);
        explode = BitmapFactory.decodeResource(context.getResources(), explodeID);
        explode2 = BitmapFactory.decodeResource(context.getResources(), explodeID2);
        spacerock = BitmapFactory.decodeResource(context.getResources(), moondRockSmallId);
        missileRight = BitmapFactory.decodeResource(context.getResources(), missileRightId);
        missileUp = BitmapFactory.decodeResource(context.getResources(), missileUpId);
        spacerock2 = BitmapFactory.decodeResource(context.getResources(), spacerock2i);
        spacerock3 = BitmapFactory.decodeResource(context.getResources(), spacerock3i);
        alienResID2 = context.getResources().getIdentifier("right_side_hdpi",
                "drawable", context.getPackageName());

        hole = BitmapFactory.decodeResource(context.getResources(), holeid);
        enemyTank = new EnemyTank(context, "enemy_tank");
        ufo = new UFO(context, "spaceship2_hdpi", 1);
        ufo1 = new UFO(context, "spaceship3_hdpi", 2);
        ufo2 = new UFO(context, "right_side_hdpi", 3);
        // Initialize our array list
        ufos = new ArrayList<>();
        ufos.add(ufo);
        ufos.add(ufo1);
        ufos.add(ufo2);
        moonRover = new MoonRover(context, "vehicle");
    }

    @Override
    public void run() {
        while (running) {
            long startFrameTime = System.currentTimeMillis();
            update();
            draw();
            // Calculate the fps this frame
            long timeThisFrame = System.currentTimeMillis() - startFrameTime;
            if (timeThisFrame >= 1) {
                fps = 1000 / timeThisFrame;
            }
        }
    }

    private void checkJump() {
        if (System.currentTimeMillis() - lastTurn3 >= 650) { // 650 means how long the vehicle is in the air at a jump
            // Change direction here
            jump = false;
            lastTurn3 = System.currentTimeMillis();
        }
    }

    private void drawShots() {
        for (int i1 = 0; i1 < numberOfshots; i1++) {
            if (shoot) {
                // canvas.drawText("o", (float) (missiles[i1] + moonRover.getBuggyXdistance() + 450), (float) (screenHeight * 0.7) - moonRover.getJumpHeight(), paint); // add to y the jump height
                canvas.drawBitmap(missileRight, (float) (missiles[i1] + moonRover.getBuggyXdistance() + 450), (float) (screenHeight * 0.57) - moonRover.getJumpHeight(), paint); // add to y the jump height

                //  canvas.drawText("o", (float) (moonRover.getBuggyXdistance() + 185 + 400), screenHeight / 110 * 95 - missiles[i1] - xbuggy2, paint);
                canvas.drawBitmap(missileUp, (float) (moonRover.getBuggyXdistance() + 185 + 400), screenHeight / 110 * 95 - missiles[i1] - xbuggy2, paint);
                //}
            }
            if (i1 == numberOfshots - 1 && missiles[i1] > screenWidth) {
                if (numberOfshots > 0) numberOfshots--;
                if (index > 0) index--;
            }
        }
    }

    private void drawEnemyTankShots() {
        //use a list instead
        for (int i1 = 0; i1 < numberOfEnemyTankshots; i1++) {
            if (enemyTankShoot) {
                canvas.drawBitmap(missileRight, (float) (-enemyTankmissiles[i1] + screenWidth - enemyTank.getBuggyXdistance()), (float) (screenHeight * 0.56), paint);
            }
            if (i1 == numberOfEnemyTankshots - 1 && enemyTankmissiles[i1] > screenWidth) {
                if (numberOfEnemyTankshots > 0) numberOfEnemyTankshots--;
                if (enemyTankIndex > 0) enemyTankIndex--;
            }
        }
    }

    boolean roverDestroysTankMissile = false;

    // if enemy tank missile hits buggy
    private boolean checkBuggyHitByEnemyTankMissile(Canvas canvas, ParallaxView view, int buggyXDisplacement, double buggyXDistance, Paint paint, Bitmap buggy, int jumpHeight) {
        boolean wasHit = false;
        // use a list instead and remove shots which hit
        for (int i1 = 0; i1 < numberOfEnemyTankshots; i1++) {
            if (java.lang.Math.abs(-enemyTankmissiles[i1] + screenWidth - enemyTank.getBuggyXdistance() - buggyXDisplacement + moonRover.getBuggyXdistance()) < 150) {
                UFO.recent = true;
                canvas.drawBitmap(view.explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
                ParallaxView.bombed--;
                missileOffSetY = 0;
                //    wasHit = true;
                view.recent = true;
                Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(() -> {
                    UFO.recent = false;
                    waitForTimer = false;
                    //     wasHit = false;
                }, 4500);
                waitForTimer = true;
            } //else if (!roverDestroysTankMissile &&  !waitForTimer && !waitForUfoTimer && MoonBackground.checkpoint >= 'A') {
            //fire list of missiles
            //     canvas.drawBitmap(ufoMissile, missile.getX(), missile.getY(), paint);
            //    missile.setY(missile.getY() + 2);
            //  }// else {
            //  missile.setY(ufoY);
            //   missile.setX(ufoX);
            // }
            //  wasHit = false;
        }
        return wasHit;
    }


    //use a Handler instead
    private void changeDirections() {
        if (System.currentTimeMillis() - lastTurn2 >= 7000) {
            // Change direction here
            toggleDeltaY = !toggleDeltaY;
            lastTurn2 = System.currentTimeMillis();
        }
    }

    //try to improve this
    private void controlVelocity() {
        if (!brake && moonRover.getBuggyXdistance() > 0) {
            moonRover.increaseBuggyXdistance(moonRover.getDistanceDelta());
        } else if (brake && moonRover.getBuggyXdistance() > 0) {
            moonRover.decreaseBuggyXdistance(moonRover.getRetardation());
        }
    }

    private void makeShots() {
        for (int n = 0; n < numberOfshots; n++)
            missiles[n] = missiles[n] + 20;

        for (int n = 0; n < numberOfEnemyTankshots; n++)
            enemyTankmissiles[n] = enemyTankmissiles[n] + 20;
    }

    public void changeText() {
        if (scoring) {
            ((Activity) this.getContext()).runOnUiThread(() -> {
                String str = "Player 1  " + String.format("%06d", score);
                tvId.setText(str);
                scoring = false;

            });
        }
    }

    //change to handler
    private void checkFire() {
        if (System.currentTimeMillis() - lastTurn4 >= 118500) { // it means how often the alien fires
            lastTurn4 = System.currentTimeMillis();
            missileOffSetY = 0;
        }
    }

    private void draw() {
        if (moonRover.getRetardation() > 0.5) {
            moonRover.setDistanceDelta(0);
        }
        if (moonRover.getDistanceDelta() > 0) //why?
            moonRover.setRetardation(0.5);
        if (ourHolder.getSurface().isValid()) {
            //First we lock the area of memory we will be drawing to
            canvas = ourHolder.lockCanvas();
            if (checkpointComplete) {

                canvas.drawColor(Color.BLACK);
                ((ParallaxActivity) getContext()).stopWatch.stop();
                paint.setTextSize(60);
                String s2 = "TIME TO REACH POINT \"" + MoonBackground.checkpoint + "\"\n";
                if (runOnce) {
                    for (int q = 0; q < s2.length(); q++) {
                        final String s2f = s2;
                        final int r = q;
                        ((Activity) this.getContext()).runOnUiThread(() -> {
                            checkpointtextview.setTextColor(Color.RED);
                            checkpointtextview.append(Character.toString(s2f.charAt(r)));

                        });
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException ie) {
                        }
                    }
                }
                String str = String.format("%03d", ((ParallaxActivity) this.getContext()).countUp);
                String s3 = "YOUR TIME                :   " + str;
                if (runOnce) {
                    for (int q = 0; q < s3.length(); q++) {
                        final String s3f = s3;
                        final int r = q;
                        ((Activity) this.getContext()).runOnUiThread(() -> {
                            checkpointtextview2.setTextColor(Color.parseColor("#ADD8E6"));
                            checkpointtextview2.append(Character.toString(s3f.charAt(r)));

                        });
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException ie) {
                        }
                    }
                }
                String s4 = "THE AVERAGE TIME        :   060";
                if (runOnce) {
                    for (int q = 0; q < s4.length(); q++) {
                        final String s4f = s4;
                        final int r = q;
                        ((Activity) this.getContext()).runOnUiThread(() -> {
                            checkpointtextview3.setTextColor(Color.parseColor("#ADD8E6"));
                            checkpointtextview3.append(Character.toString(s4f.charAt(r)));

                        });
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException ie) {
                        }
                    }
                }
                String s5 = "TOP RECORD        :   060";
                if (runOnce) {
                    for (int q = 0; q < s5.length(); q++) {
                        final String s5f = s5;
                        final int r = q;
                        ((Activity) this.getContext()).runOnUiThread(() -> {
                            checkpointtextview4.setTextColor(Color.RED);
                            checkpointtextview4.append(Character.toString(s5f.charAt(r)));
                        });
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException ie) {
                        }
                    }
                }

                String s6 = "GOOD BONUS POINTS        :   1000";
                if (runOnce) {
                    for (int q = 0; q < s6.length(); q++) {
                        final String s6f = s6;
                        final int r = q;
                        ((Activity) this.getContext()).runOnUiThread(() -> {
                            checkpointtextview5.setTextColor(Color.RED);
                            checkpointtextview5.append(Character.toString(s6f.charAt(r)));
                        });
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException ie) {
                        }
                    }
                }
                if (runOnce) {
                    score = score + 1000;
                    sectionComplete++;
                    recent = true;
                }
                runOnce = false;
                ((Activity) this.getContext()).runOnUiThread(() -> {
                    Handler handler = new Handler();
                    handler.postDelayed(() -> {
                        ((ParallaxActivity) getContext()).startTime = SystemClock.elapsedRealtime();
                        ((ParallaxActivity) getContext()).stopWatch.setBase(((ParallaxActivity) getContext()).startTime);
                        ((ParallaxActivity) getContext()).stopWatch.start();
                        checkpointtextview.setText("");
                        checkpointtextview2.setText("");
                        checkpointtextview3.setText("");
                        checkpointtextview4.setText("");
                        checkpointtextview5.setText("");
                        checkpointtextview6.setText("");
                        String str2 = "Player 1  " + String.format("%06d", score);
                        tvId.setText(str2);
                        scoring = false;
                        moonRover.setBuggyXdistance(0);
                        moonRover.setDistanceDelta(0);
                        moonRover.setRetardation(0);
                        checkpointComplete = false;
                        runOnce = true;
                    }, 3000);
                });
            } else {
                if (bombed == 0) //GAME OVER
                {
                    final int duration = Toast.LENGTH_LONG;
                    ((Activity) this.getContext()).runOnUiThread(() -> {
                        final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        Handler handler = new Handler();
                        handler.postDelayed(() -> {
                            toast.cancel();
                            bombed = 5;
                            score = 0;
                            MoonBackground.checkpoint = 'A';
                            String str = "Player 1  " + String.format("%06d", score);
                            tvId.setText(str);
                        }, 3000);
                    });
                }
                moonRover.jump(canvas, jump);
                if (shoot) {
                    xbuggy2 = xbuggy2 + 4;
                }
                checkFire();
                checkJump();
                canvas.drawColor(Color.argb(255, 0, 0, 0));
                // Draw the background parallax
                bgh.drawBackground(0, this, canvas,paint);

                // Draw the background mountain parallax
                bgh.drawBackground(1, this, canvas,paint);

                // Draw the rest of the game
                paint.setTextSize(60);
                paint.setColor(Color.argb(255, 255, 255, 255));
                // drawShots();
                changeDirections();

                for (UFO ufo : ufos) {
                    ufo.update(canvas, paint, toggleDeltaY);
                }
                recent = ufo.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight());

                if (recent) {
                    waitForTimer = true;
                    bexplode = true;
                    UFO.recent = true;
                }

                boolean recent2 = ufo1.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight());
                if (recent || recent2) {
                    recent = true;
                    waitForTimer = true;
                    bexplode = true;
                    UFO.recent = true;
                }

                boolean recent3 = ufo2.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight());

                boolean recent4 = enemyTank.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight());


                //TODO: reset scenario after buggy being hit by UFO missile
                if (recent || recent2 || recent3) {
                    recent = true;
                    waitForTimer = true;
                    bexplode = true;
                    UFO.recent = true;

                    new Timer().schedule(new SetRecent(), 10000);
                    new Timer().schedule(new ResetCheckpoint(), 1000);

                    Handler handler = new Handler(Looper.getMainLooper());
                    // this code runs after a while
                    handler.postDelayed(() -> {
                        waitForTimer = false;
                        bexplode = false;
                        moonRover.setBuggyXdistance(0);
                        Log.d("postDelayed", "postDelayed ");
                        donotdrawBuggy = true;
                        Handler handler2 = new Handler(Looper.getMainLooper());
                        handler2.postDelayed(() -> {
                            donotdrawBuggy = false;
                            bexplode = false;
                            Handler handler3 = new Handler(Looper.getMainLooper());
                            handler3.postDelayed(() -> {
                                recent = false;
                                UFO.recent = false;
                            }, 2000);
                        }, 2000);

                    }, 2000);
                }
                //checkBuggyBombed();
                for (int i1 = 0; i1 < numberOfshots; i1++) {

                    ufo.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);
                    ufo1.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);
                    ufo2.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);

                }
                bgh.drawBackground(2, this, canvas,paint);

                // canvas.drawText("X", (float) (50 + buggyXDistance)+moonRover.getBitmapRover().getWidth()/2, (float) (screenHeight * 0.3) - jumpHeight+buggy.getHeight(), paint);
                paint.setTextSize(60);
                canvas.drawText("A    E    J    O    T    Z", (float) (screenWidth * 0.7), (float) (screenHeight * 0.15), paint);

                // Prevent buggy from moving outside horizontal screen
                if (!brake && buggyXDisplacement + moonRover.getBuggyXdistance() > screenWidth - moonRover.getBitmapRover().getWidth() - 200) {
                    //buggyXDistance = screenWidth - moonRover.getBitmapRover().getWidth() - 200;
                    moonRover.setBuggyXdistance(screenWidth - moonRover.getBitmapRover().getWidth() - 200);
                }
                //Log.d("buggyXDistance", "buggyXDistance " + buggyXDistance);

                if (!donotdrawBuggy && !bexplode && !waitForTimer && !checkpointComplete) {
                    moonRover.draw(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight());
                } else if (!donotdrawBuggy && bexplode && !checkpointComplete) {
                    moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight());
                    moonRover.setDistanceDelta(0);
                    moonRover.setRetardation(0);
                }
                // TODO: enemy tank that also can fire

                if (MoonBackground.checkpoint >= 'F') {

                    enemyTank.draw(canvas, paint, (float) (enemyTank.getBuggyXdistance()), (float) (screenHeight * 0.57));

                    if (runOnce2 && java.lang.Math.abs(screenWidth - enemyTank.getBuggyXdistance()) < 350) {
                        enemyForward = false;
                        runOnce2 = false;
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.postDelayed(() -> {
                            runOnce2 = true;
                        }, 6500);

                    } else if (java.lang.Math.abs(screenWidth - (screenWidth - enemyTank.getBuggyXdistance())) < 150) {
                        enemyForward = true;
                    }


                    if (enemyForward) {
                        enemyTank.increaseBuggyXdistance(8); //accelerate later
                        enemyTank.setTankX((int) (enemyTank.getBuggyXdistance()));
                    } else {
                        enemyTank.decreaseBuggyXdistance(3);
                        enemyTank.setTankX((int) (enemyTank.getBuggyXdistance()));
                    }
                    enemyTank.setDistanceDelta(0);
                }

                int inc = 0;
                for (int i = 0; i < bombed; i++) {
                    canvas.drawBitmap(Bitmap.createScaledBitmap(moonRover.getBitmapRover(), (int) (0.50 * (moonRover.getBitmapRover().getWidth() / 3)), (int) (0.50 * moonRover.getBitmapRover().getHeight() / 3), false), inc, 100, paint);
                    inc = inc + getMoonRover().getBitmapRover().getWidth() / 4;
                }
                makeShots();

                controlVelocity();
                drawShots();
                // checkBuggyHitByEnemyTankMissile(canvas, this, buggyXDisplacement, moonRover.getBuggyXdistance(), paint, getMoonRover().getBitmapRover(), jumpHeight);
                // drawEnemyTankShots();

            }
            ourHolder.unlockCanvasAndPost(canvas);
        }
    }

    // Clean up our thread if the game is stopped
    public void pause() {
        running = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
            // Error
            //e.printStackTrace();
        }
    }

    // Make a new thread and startMissile it
    // Execution moves to our run method
    public void resume() {
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    // Because we call this from onTouchEvent, this code will be executed for both
    // normal touch events and for when the system calls this using Accessibility
    @Override
    public boolean performClick() {
        super.performClick();
        launchMissile();
        return true;
    }

    protected void launchMissile() {
        missiles[index] = 350; // missile distance from buggy
        index++;
        xbuggy2 = 0;
        shoot = true;
    }

    protected void launchEnemyTankMissile() {
        enemyTankmissiles[enemyTankIndex] = 10;//350; // missile distance from buggy
        enemyTankIndex++;
        enemyTankxbuggy2 = 0;
        enemyTankShoot = true;
        numberOfEnemyTankshots++;
    }

    // event listener for when the user touches the screen
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = MotionEventCompat.getActionMasked(event);
        int coordX = (int) event.getX();
        int coordY = (int) event.getY();
        //Log.d("coordY", "coordY " + coordY);
        if (coordX < 220 && moonRover.getJumpHeight() == 0 && action == MotionEvent.ACTION_MOVE) {
            jump = true;
            shoot = false;
            lastTurn3 = System.currentTimeMillis();
            return true; // do nothing
        }

        if (coordX > 219 && action == MotionEvent.ACTION_DOWN) {
            numberOfshots++;
            performClick();
            return true;
        }
        return true;
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ IMO the methods are too big to read and review. Maybe you could make smaller methods so that others may give a better review. \$\endgroup\$ – Ankit Soni Aug 12 '18 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.