2
\$\begingroup\$

This is improved code from my previous question. This mini game which we call "Moon Buggy" is available in beta from the google playstore.

enter image description here

The action is that you control a vechicle on the moon and you defend yourself against evil UFO:s.

I have written a separate class for the UFO which is instanciated once for every UFO. I have also created a separate class for the vehicle which we call the "moon rover" (might change the name of the game to "Moon Rover" possibly).

UFO.java

public class UFO extends MoonSprite {

    private Bitmap ufoBitmap;
    //boolean to avoid multiple hits, switched in the beginning
    static boolean recent = true;
    private long changeDirections = System.currentTimeMillis();
    private long fireTimeout = System.currentTimeMillis();
    private int ufoY = 0;
    private int ufoX = 0;
    private int missileX = 25;
    private int deltaUfoY = 7;
    private int deltaUfoX = 7;
    private int missileOffSetY = 0;
    private int missileYstart = 0;
    private boolean wasHit = false;
    private boolean alienexplode;
    private boolean waitForTimer, waitForUfoTimer;
    private boolean toggleDeltaY = true;
    private boolean runOnce = true;

    protected UFO(Context context, String name, int deltaUfoY) {
        super(context, name);
        this.screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        this.screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        Log.d("dimensions", "dimensions " + this.screenHeight + " " + this.screenWidth);
        this.deltaUfoY = deltaUfoY; // the vertical velocity
        int ufoId = context.getResources().getIdentifier(name,
                "drawable", context.getPackageName());
        ufoBitmap = BitmapFactory.decodeResource(context.getResources(), ufoId);
        ufoX = randomize((int) (0.8 * screenWidth), (int) (0.2 * screenWidth));
        // missile starts at same coordinates as UFO
        missileX = ufoX;
        ufoY = 0;
        waitForUfoTimer = true;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(() -> {
            missileX = ufoX;
            UFO.recent = false;
            waitForUfoTimer = false;
        }, randomize(20000, 18000));
    }

    //not yet used. start from beginning if target or UFO is hit
    public void reset(Canvas canvas, Paint paint) {
        missileX = randomize((int) (0.75 * screenWidth), 20);
        ufoX = missileX;
        ufoY = 0;
        waitForUfoTimer = true;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(() -> {
            missileX = ufoX;
            UFO.recent = false;
            waitForUfoTimer = false;
        }, randomize(20000, 18000));
    }

    private void changeDirections() {
        if (System.currentTimeMillis() - changeDirections >= randomize(500, 100)) {
            // Change direction here
            toggleDeltaY = !toggleDeltaY;
            changeDirections = System.currentTimeMillis();
        }
    }

    public void update(Canvas canvas, Paint paint, boolean toggleDeltaY) {
        // don't move outside the top. (0,0) is top left corner
        if(ufoY<0) {
            ufoY = 0;
            deltaUfoY = (int) Math.sqrt(deltaUfoY * deltaUfoY);  // use the positive
        }

        if (ufoX > screenWidth - ufoBitmap.getWidth() || ufoX <= 0) { // UFO change horizontal direction
            deltaUfoX = -deltaUfoX;
        }

        //if missiles goes outside the screen lower part, update to new missile coordinates
        if (missileYstart + ufoBitmap.getHeight() + missileOffSetY >= screenHeight) {
            missileYstart = ufoY;
            missileX = ufoX;
        }

        //change directions after a while
        if (toggleDeltaY) {
            deltaUfoY = -deltaUfoY;
        }

        //make sure UFO does not move too low
        //(0,0) is top left corner
        if (ufoY >= (int) (0.2 * screenHeight)) { // why 0.2 ?
            deltaUfoY = - (int) Math.sqrt(deltaUfoY * deltaUfoY);  // use the negative;
        }

        if (!waitForUfoTimer && MoonBackground.checkpoint >= 'A') {
            runOnce = true;
            canvas.drawBitmap(ufoBitmap, ufoX + 10, ufoY, paint);
        }

        ufoX = ufoX + deltaUfoX;
        if (waitForTimer) missileX = ufoX;


        ufoY = ufoY + deltaUfoY;
        changeDirections();
    }

    public boolean checkBeingHit(int[] missiles, int buggyXDisplacement, double buggyXDistance, Canvas canvas, Bitmap explode2, Paint paint, int score, ParallaxView pview, int i1, int xbuggy2) {
        // if UFO is being hit by buggy
        if (!waitForTimer && java.lang.Math.abs(ufoX + 10 - 400 - buggyXDistance) * 2 < (ufoBitmap.getWidth()) && java.lang.Math.abs(ufoY - (screenHeight / 100 * 95 - missiles[i1] - xbuggy2)) * 2 < (ufoBitmap.getHeight())) {
            missileOffSetY = -9999;
            canvas.drawBitmap(explode2, ufoX + 10, ufoY, paint);
            if (runOnce) {
                ParallaxView.score = ParallaxView.score + 100;
                Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(() -> {
                    missileX = randomize((int) (0.75 * screenWidth), 20);
                    ufoX = missileX;
                    ufoY = 0;
                    alienexplode = false;
                    waitForTimer = false;
                    waitForUfoTimer = false;
                }, 3000);
            }
            runOnce = false;
            waitForUfoTimer = true;
            waitForTimer = true;
            if (!alienexplode) {
                pview.changeText();
            }
            alienexplode = true;
            return true;
        } else return false;
    }

    //return boolean if fire, boolean which is not yet used
    private boolean checkFire() {
        if (System.currentTimeMillis() - fireTimeout >= randomize(30000, 24000)) { // means how often the ufoBitmap fires
            fireTimeout = System.currentTimeMillis();
            missileOffSetY = 0;
            missileX = ufoX;
            missileYstart = ufoY;
            return true;
        } else return false;
    }

    // if buggy was hit by a missile then return true
    private boolean checkBuggyHitByMissile(Canvas canvas, ParallaxView view, int buggyXDisplacement, double buggyXDistance, Paint paint, Bitmap buggy, int jumpHeight) {
        if (!UFO.recent && !view.waitForTimer && java.lang.Math.abs(((buggyXDisplacement + buggyXDistance) + buggy.getWidth() / 2) - (missileX + 10 + ufoBitmap.getWidth() / 2)) < buggy.getWidth() / 2 && java.lang.Math.abs((ufoY + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight + buggy.getHeight())) < 65) {
            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 {
            // buggy was not hit so UFO fires more missiles
            if (!waitForTimer && !waitForUfoTimer && MoonBackground.checkpoint >= 'A') {
                canvas.drawText("●", missileX + ufoBitmap.getWidth() / 2 + 10, missileYstart + ufoBitmap.getHeight() + missileOffSetY, paint);
                missileOffSetY = missileOffSetY + 3;
            }
            wasHit = false;
        }
        return wasHit;
    }

    public boolean drawMissile(ParallaxView view, Canvas canvas, Paint paint, int buggyXDisplacement, double buggyXDistance, Bitmap buggy, int jumpHeight) {
        checkFire();
        return checkBuggyHitByMissile(canvas, view, buggyXDisplacement, buggyXDistance, paint, buggy, jumpHeight);
    }
}

MoonRover.java

public class MoonRover extends MoonSprite {

    public Bitmap getBitmapRover() {
        return bitmapRover;
    }

    private Bitmap bitmapRover, explode;

    public int getJumpHeight() {
        return jumpHeight;
    }

    public void setJumpHeight(int jumpHeight) {
        this.jumpHeight = jumpHeight;
    }

    private int jumpHeight;

    private double retardation = 0.5;

    private double buggyXdistance = 0;

    public double getBuggyXdistance() {
        return buggyXdistance;
    }

    public void setBuggyXdistance(double buggyXdistance) {
        this.buggyXdistance = buggyXdistance;
    }

    public void increaseBuggyXdistance(double d) {
        buggyXdistance = buggyXdistance + d;
    }

    public void decreaseBuggyXdistance(double d) {
        buggyXdistance = buggyXdistance - d;
    }

    public double getRetardation() {
        return retardation;
    }

    public void increaseRetardation(double d) {
        retardation = retardation + d;
    }

    public void setRetardation(double retardation) {
        this.retardation = retardation;
    }


    public double getDistanceDelta() {
        return distanceDelta;
    }

    public void setDistanceDelta(double distanceDelta) {
        this.distanceDelta = distanceDelta;
    }

    private double distanceDelta;

    protected MoonRover(Context context, String name) {
        super(context, name);

        this.screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        this.screenWidth = context.getResources().getDisplayMetrics().widthPixels;

        int roverId = context.getResources().getIdentifier(name,
                "drawable", context.getPackageName());
        bitmapRover = BitmapFactory.decodeResource(context.getResources(), roverId);

        int explodeId = context.getResources().getIdentifier("explode",
                "drawable", context.getPackageName());
        explode = BitmapFactory.decodeResource(context.getResources(), explodeId);

        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
            }
        }, randomize(20000, 18000));
    }

    //if rover was hit by UFO missile then return true, false otherwise
    //not implemented yet
    public boolean isHit(UFO ufo) {
        boolean isHit = false;
        return isHit;
    }


    //if rover was hit by UFO missile, hits a moon rock or a hole, then explode for some time
    //and after a while reset to beginning of section
    public void explode(Canvas canvas, Paint paint, float left, float top) {
        canvas.drawBitmap(explode, left, top, paint);
    }

    //if rover fires a missile then draw the missile
    //not implemented yet
    public void fireMissile(Canvas canvas) {

    }

    public void draw(Canvas canvas, Paint paint, float left, float top) {
          canvas.drawBitmap(bitmapRover, left, top, paint);
    }

    //if rover jumps then draw the jumping rover
    public void jump(Canvas canvas, boolean up) {
        if (up && jumpHeight < 500) {
            jumpHeight = jumpHeight + 7;
            if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55;
        } else if (jumpHeight > 0) {
            jumpHeight = jumpHeight - 4;
            if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55;
        }

    }
}

ParallaxView.java

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

    static int bombed = 5;

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

    boolean waitForTimer = false;
    boolean recent = false;
    boolean increment = false;
    boolean toggleDeltaY = true;
    boolean toggleGround = true;
    boolean jump = false;
    boolean shoot = 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

    final int buggyXDisplacement = 450;
    int numberOfshots = 0; // change to 0
    int[] missiles = new int[200];
  /*  int alienBombYDelta = 0;
    int alienBombYDelta2 = 0;
    int alienBombXDelta = 20;
    int alienBombXDelta2 = 30;*/
    int p = 7;
    int p2 = 13;
    int index = 0;
    int missileOffSetY = 0;
    int jumpHeight = 0;
    int xbuggy2 = 0;
    int craterX = -550;

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

    TextView tvId1;
    int sectionComplete = 0;
    static int score = 0;
    double lastTurn4 = System.currentTimeMillis();
    List<MoonBackground> backgrounds;
    List<UFO> ufos;
    int moondRockSmallId, resID, explodeID, explodeID2, alienResID2;

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

    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 alien3;
    UFO alien4;
    UFO alien5;
    // Holds a reference to the Activity
    Context context;
    ScreenDimension screenDimension;

    // Control the fps
    long fps = 60;

    MoonRover moonRover;

    // Screen resolution
    int screenWidth;
    int screenHeight;
    boolean bexplode = false;
    boolean brake = false;
    boolean scoring = false;

    public MoonRover getMoonRover() {
        return moonRover;
    }

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

    // use Handler instead
    class ResetCheckpoint extends TimerTask {
        public void run() {
            Log.d("## sectionComplete", "sectionComplete " + sectionComplete);
            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
        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<>();

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

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

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

        //Log.d("Timer", "Timer ");
        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());

        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);

        spacerock2 = BitmapFactory.decodeResource(context.getResources(), spacerock2i);
        spacerock3 = BitmapFactory.decodeResource(context.getResources(), spacerock3i);

        alienResID2 = context.getResources().getIdentifier("right_side_hdpi",
                "drawable", context.getPackageName());

        int alienResID3 = context.getResources().getIdentifier("spaceship2_hdpi",
                "drawable", context.getPackageName());

        alien = BitmapFactory.decodeResource(context.getResources(), alienResID2);

        alien2 = BitmapFactory.decodeResource(context.getResources(), alienResID3);

        hole = BitmapFactory.decodeResource(context.getResources(), holeid);

        alien3 = new UFO(context, "spaceship2_hdpi", 1);
        alien4 = new UFO(context, "spaceship3_hdpi", 2);
        alien5 = new UFO(context, "right_side_hdpi", 3);
        // Initialize our array list
        ufos = new ArrayList<>();
        ufos.add(alien3);
        ufos.add(alien4);
        ufos.add(alien5);
        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.drawText("o", (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--;
            }
        }
    }

    //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;
    }

    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(new Runnable() {
                    @Override
                    public void run() {
                        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 str = "Player 1  " + String.format("%06d", score);
                            tvId.setText(str);
                            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_SHORT;
                    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
                            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
                drawBackground(0);
                // 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 = alien3.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight());

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

                boolean recent2 = alien4.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 = alien5.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(new Runnable() {
                        @Override
                        public void run() {
                            waitForTimer = false;
                            bexplode = false;
                            moonRover.setBuggyXdistance(0);
                            Log.d("postDelayed", "postDelayed ");
                            donotdrawBuggy = true;
                            Handler handler2 = new Handler(Looper.getMainLooper());
                                handler2.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    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++) {

                    alien3.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);
                    alien4.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);
                    alien5.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2);

                }
                drawBackground(1);

                // 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);
                }
                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();
                //updateDeltas();
                controlVelocity();
            }
            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();
    }

    private void drawBackground(int position) {

        // Make a copy of the relevant background
        MoonBackground bg = backgrounds.get(position);

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

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

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

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

            if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(spacerock3, toRect1.left, toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(spacerock2, toRect1.left, toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && bg.xClip <= 0) { // && position == 2) {
                canvas.drawBitmap(spacerock, toRect1.left, toRect1.top, paint);
            }
            if (position == 1) {
                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 (increment) {
                    MoonBackground.checkpoint++;
                    toggleGround = true;
                }
                if (MoonBackground.checkpoint == 'B' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) {
                    passed = true;
                }

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

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

            canvas.drawBitmap(bg.bitmapReversed, fromRect1, toRect1, paint);
            if (MoonBackground.checkpoint != '@' && position == 1 && 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 (!waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !recent && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip)) < moonRover.getBitmapRover().getWidth()) {
                    canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint);
                    bombed--;
                    recent = true;
                    waitForTimer = true;
                    bexplode = true;
                    moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight());
                    moonRover.setDistanceDelta(1.15);
                    moonRover.setRetardation(0.5);
                    jumpHeight = 0;
                    moonRover.setJumpHeight(0);
                    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Handler handler = new Handler();
                            handler.postDelayed(() -> {
                                waitForTimer = false;
                                moonRover.setBuggyXdistance(0);
                                bexplode = false;
                            }, 2000);
                        }
                    });
                    new Timer().schedule(new SetRecent(), 10000);
                    new Timer().schedule(new ResetCheckpoint(), 1000);
                }

                canvas.drawBitmap(spacerock3, toRect1.left, toRect1.top, paint);
            } else if (MoonBackground.checkpoint != '@' && position == 1 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') {
                canvas.drawBitmap(spacerock2, toRect1.left, toRect1.top, paint);
                //if buggy collides with moon rock 2
                if (!waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !recent && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip)) < 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);
                    moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight());
                    bombed--;
                    recent = true;
                    waitForTimer = true;
                    bexplode = true;
                    canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint);
                    moonRover.setDistanceDelta(1.15);
                    moonRover.setRetardation(0.5);
                    jumpHeight = 0;
                    moonRover.setJumpHeight(0);
                    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Handler handler = new Handler();
                            handler.postDelayed(() -> {
                                waitForTimer = false;
                                moonRover.setBuggyXdistance(0);
                                bexplode = false;
                            }, 2000);
                        }
                    });
                    new Timer().schedule(new SetRecent(), 10000);
                    new Timer().schedule(new ResetCheckpoint(), 1000);
                }

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

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

    // 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;
    }

    // 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;
    }
}

ParallaxActivity.java

public class ParallaxActivity extends Activity implements View.OnClickListener {

    long startTime;
    long countUp;
    TextView textGoesHere;
    TextView tvId;
    ParallaxView parallaxView;
    boolean paused = false;
    double acceleration = 0;
    @Override
    public void onClick(View v) {
        ParallaxView parallaxView = findViewById(R.id.backgroundImage);
        switch (v.getId()) {
            case R.id.button3:
                //ParallaxView parallaxView = findViewById(R.id.backgroundImage);
                parallaxView.recent = false;
                parallaxView.brake = false;
                parallaxView.getMoonRover().setRetardation(0);
                //parallaxView.buggyXDistance = parallaxView.buggyXDistance + 3;
                parallaxView.getMoonRover().increaseBuggyXdistance(3);
                parallaxView.getMoonRover().setDistanceDelta(parallaxView.getMoonRover().getDistanceDelta() + acceleration);
                acceleration = acceleration + 0.2;
                break;
            case R.id.button4:
                //ParallaxView parallaxView2 = findViewById(R.id.backgroundImage);
                parallaxView.recent = false;
                //parallaxView.buggyXDistance = parallaxView.buggyXDistance - 7;
                parallaxView.getMoonRover().decreaseBuggyXdistance(7);
                acceleration = 0;
                parallaxView.getMoonRover().increaseRetardation(0.2);
                parallaxView.brake = true;
                break;
            case R.id.button2:
                //ParallaxView parallaxView3 = findViewById(R.id.backgroundImage);
                parallaxView.numberOfshots++;
                parallaxView.recent = false;
                parallaxView.launchMissile();
                parallaxView.scoring = true;
                break;
            case R.id.button1:
                //ParallaxView parallaxView4 = findViewById(R.id.backgroundImage);
                if (parallaxView.getMoonRover().getDistanceDelta() < 3) {
                   // parallaxView4.distanceDelta = parallaxView4.distanceDelta + 0.2;
                    parallaxView.getMoonRover().setDistanceDelta(parallaxView.getMoonRover().getDistanceDelta()+0.2);
                }
                parallaxView.jump = true;
                parallaxView.shoot = false;
                parallaxView.lastTurn3 = System.currentTimeMillis();
                break;
            case R.id.button5:
                if (!paused) {
                    paused = true;
                    onPause();

                } else {
                    paused = false;
                    onResume();

                }
                break;
            default:
                break;
        }
    }


    public void setText(final String s, final TextView tv) {
        //TextView tv= (TextView) tf.getView().findViewById(R.id.textview1);
        tv.append(String.valueOf(s));
    }

    Chronometer stopWatch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get a Display object to access screen details
        Display display = getWindowManager().getDefaultDisplay();

        // Load the resolution into a Point object
        Point resolution = new Point();
        display.getSize(resolution);
        setContentView(R.layout.main_layout);
        Button btn1 = findViewById(R.id.button3);
        btn1.setOnClickListener(this);
        Button btn2 = findViewById(R.id.button4);
        btn2.setOnClickListener(this);
        Button btn3 = findViewById(R.id.button2);
        btn3.setOnClickListener(this);
        Button btn4 = findViewById(R.id.button1);
        btn4.setOnClickListener(this);
        Button btn5 = findViewById(R.id.button5);
        btn5.setOnClickListener(this);
        tvId = findViewById(R.id.player1);
        TextView tvId1 = findViewById(R.id.checkpoint);

        String s1 = "   A   ";
        tvId1.setText(s1);
        parallaxView = findViewById(R.id.backgroundImage);
        parallaxView.checkpointtextview = findViewById(R.id.checkpointtext);
        parallaxView.checkpointtextview.setText("");

        parallaxView.checkpointtextview2 = findViewById(R.id.checkpointtext2);
        parallaxView.checkpointtextview2.setText("");

        parallaxView.checkpointtextview3 = findViewById(R.id.checkpointtext3);
        parallaxView.checkpointtextview3.setText("");

        parallaxView.checkpointtextview4 = findViewById(R.id.checkpointtext4);
        parallaxView.checkpointtextview4.setText("");

        parallaxView.checkpointtextview5 = findViewById(R.id.checkpointtext5);
        parallaxView.checkpointtextview5.setText("");

        parallaxView.checkpointtextview6 = findViewById(R.id.checkpointtext6);
        parallaxView.checkpointtextview6.setText("");

        stopWatch = (Chronometer) findViewById(R.id.chrono);
        startTime = SystemClock.elapsedRealtime();
        stopWatch.setBase(startTime);
        textGoesHere = (TextView) findViewById(R.id.textGoesHere);
        stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer arg0) {
                countUp = (SystemClock.elapsedRealtime() - startTime) / 1000;
                String str = String.format("%04d", countUp);
                textGoesHere.setText(str);
            }
        });
        stopWatch.start();
        parallaxView.tvId1 = tvId1;
        parallaxView.tvId = tvId;
    }

    // If the Activity is paused make sure to pause our thread
    @Override
    protected void onPause() {
        super.onPause();
        parallaxView.pause();
    }

    // If the Activity is resumed make sure to resume our thread
    @Override
    protected void onResume() {
        super.onResume();
        parallaxView.resume();
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ This question has about a thousand lines of code. You might want to split it up or at least describe it in more detail. \$\endgroup\$ – l0b0 Jul 13 '18 at 6:44
  • \$\begingroup\$ @l0b0 I split it up. I will probably create a class or an interface "CruiseControl" for autonomous vehicles which change directions like non-player moving enemies do. \$\endgroup\$ – Niklas R. Jul 23 '18 at 5:24
2
\$\begingroup\$

My answer will also be short as there are too many things to adress at one time. But there is exactly one thing I am able to say at this point of time: You mixed up model and view.

So my suggestion is to first create a model of your game so it is runnable without ANY UI elements and connect the model to the UI afterwards.

A good way to learn this kind of separation of concerns is to force yourself writing the model not in the android studio and have the model imported if you think it is "ready". You may also consider to have another UI techonology in the first place like JavaFX. If you import the model to Android at som point you will recognize the elements that you accidently put into the UI as it has been better placed within the model.

One other thing I recognized as I had a rough review over the code: your draw()-method is very long. Not that long methods are bad from scratch but your draw method has a lot of logic in it so it would be better split into pieces.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ That seems difficult, but I will try it. I am also aware that my draw methods are long and my request for review was mostly how to split the logic up in more and smaller elements. \$\endgroup\$ – Niklas R. Jul 21 '18 at 23:10
1
\$\begingroup\$

You are probably using Android Studio, which is based on IntelliJ. This IDE offers really many inspections to improve your code. One of them is:

variable = variable + 3;

Can be replaced with:

variable += 3;

You should enable all these inspections and decide whether to apply them. Some of the inspections contradict each other, so choose your favorite ones. And don't apply the inspections blindly, only apply them if they actually improve the code.

Doing this relieves us humans from boring review tasks so that we can concentrate on the more interesting details in the next review round.

\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.