Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

java - Problem with changing my game's background

I created a video game I initialized variable named score, which saves the user's score for every bird he killes.

So basically after 10 scores I want the background to replace itself to another one automatically .I tried to initailize score as a static variable and I also created a unique method in my GameView activity getScore to return it's value.

Afterwards I passed the value to my Background class with an if statement to replace the background automatically but it did not worked the background stays as it is and won't replace after 10 scores. I will be very glad if someone can help me

Here is my code:

package com.example.gobirdgo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.graphics.drawable.Drawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.view.MotionEvent;
import android.view.SurfaceView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GameView extends SurfaceView implements Runnable {
    private int screenX,screenY;
    public static int score=0;
    public int candyhouseheight,candyhousewidth;
    private FlightActivity flight;
    private BirdActivity[]birds;
    private Boolean isGameOver=false;
    private SoundPool soundPool;
    private int sound;
    Context context;

    private Random random;
    private SharedPreferences prefs;
    Bitmap candyhouse1;
    int candyX,candyY;
    private Paint paint;
    private Thread thread;
    private GameActivity activity;
    public static float screenRatioX,screenRatioY;//suit the screen to every app
    private boolean isPlaying;
    private List<BulletActivity>bullets;
    private Background background1,background2;
    public GameView(GameActivity activity, int screenX, int screenY) {
        super(activity);
        prefs=activity.getSharedPreferences("game",Context.MODE_PRIVATE);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            AudioAttributes audioAttributes=new AudioAttributes.Builder().
                    setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_GAME)
                    .build();
            soundPool=new SoundPool.Builder().setAudioAttributes(audioAttributes).build();

        }
        else
            soundPool=new SoundPool(1, AudioManager.STREAM_MUSIC,0);
        sound=soundPool.load(activity,R.raw.shoot,1);
        candyX=1100;
        candyY=400;
       this.activity=activity;
        screenRatioX=1920f/screenX;
        screenRatioY=1080/screenY;
        this.screenX=screenX;
         this.screenY=screenY;
        background1=new Background(screenX,screenY,getResources());
        background2=new Background(screenX,screenY,getResources());
        flight=new FlightActivity(this,screenY,getResources());
        bullets=new ArrayList<>();
        background2.x=screenX;
        paint=new Paint();
        paint.setTextSize(50);
        paint.setColor(Color.WHITE);
        birds=new BirdActivity[4];
        for(int i=0;i<4;i++){

            BirdActivity bird=new BirdActivity(getResources());
            birds[i]=bird;
        }
      random=new Random();

    }


    @Override
    public void run() {
        while(isPlaying){
        update();
        draw();
        sleep();
        }

    }
    private void update(){//change screen position
    background1.x-=50*screenRatioX;
    background2.x-=50*screenRatioX;
    if(background1.x+background1.background.getWidth()<0){
        background1.x=screenX;
    }
        if(background2.x+background2.background.getWidth()<0){
            background2.x=screenX;
        }
        if(flight.isGoingUp)
            flight.y-=40*screenRatioY;//put the player on the top of the screen
        else
            flight.y+=40*screenRatioY;//put the player on buttom
            if(flight.y<0)
                flight.y=0;//ensure the player wont fall from the screen
       if(flight.y>screenY-flight.height)//if player is already off the screen from the buttom
           flight.y=screenY-flight.height;//
        List<BulletActivity>trash=new ArrayList<>();//bullets which are off the screen are here
        for(BulletActivity bullet:bullets){
            if(bullet.x>screenX)
                trash.add(bullet);
            bullet.x+=50*screenRatioX;//falling off the screen
            for(BirdActivity bird:birds){
                if(Rect.intersects(bird.getCollisionShape(),bullet.getCollisionShape())){
                    score++;
                    bird.x=-500;
                    bullet.x=screenX+500;
                    bird.wasShot=true;
                }
            }


        }
        for(BulletActivity bullet:trash)
            bullets.remove(bullet);//remove bullets hence they are not in need any more
        for(BirdActivity bird:birds){
            bird.x-=bird.speed;
           if(bird.x+bird.width<0){

             int bound=(int)(30*screenRatioX);
             bird.speed=random.nextInt(bound);
             if(bird.speed<10*screenRatioX)
                 if(bird.speed<10*screenRatioX)//in case the speed is zero and bird wont move
                     bird.speed=(int)(10*screenRatioX);
                 bird.x=screenX;//replace the bird
                bird.y=random.nextInt(screenY-bird.height);
                bird.wasShot=false;
            }
            if(Rect.intersects(bird.getCollisionShape(),flight.getCollisionShape())){
                isGameOver=true;
                return;

                //rectangle calculate the collision between player and biird
            }
        }
    }

    private void draw(){
   if(getHolder().getSurface().isValid()){//in case we can allocate canva
       Canvas canvas=getHolder().lockCanvas();//lock current canvas in the same position

       canvas.drawBitmap(background1.background,background1.x
               ,background1.y,paint);
       canvas.drawBitmap(background2.background,background2.x,background2.y,paint);
       candyhouse1=BitmapFactory.decodeResource(getResources(),R.drawable.candi);
      canvas.drawBitmap(candyhouse1,candyX,candyY,null);
       canvas.drawBitmap(flight.getFlight(),flight.x,flight.y,paint);
       for(BirdActivity bird:birds)
           canvas.drawBitmap(bird.getBird(),bird.x,bird.y,paint);
       canvas.drawText(getContext().getString(R.string.your_score_txt)+score+"",screenX/2f,164,paint);
       if(isGameOver){

           isPlaying=false;
          canvas.drawBitmap(flight.getDied(),flight.x,flight.y,paint);
          saveIfHighScore();
          waitBeforeExiting();
       getHolder().unlockCanvasAndPost(canvas);//draw out backgrounds on screen

       }

       canvas.drawBitmap(flight.getFlight(),flight.x,flight.y,paint);
      for(BulletActivity bullet:bullets)
          canvas.drawBitmap(bullet.bullet,bullet.x,bullet.y,paint);
     getHolder().unlockCanvasAndPost(canvas);//draw out backgrounds on screen

   }

    }

    private void waitBeforeExiting() {
        try {
            Thread.sleep(3000);
            activity.startActivity(new Intent(activity,MainActivity.class));
            activity.finish();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void saveIfHighScore() {
        if(prefs.getInt("highscore",0)<score){
            SharedPreferences.Editor editor=prefs.edit();
            editor.putInt("highscore",score);
            editor.apply();

        }
    }


    private void sleep(){

        try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void resume(){
        isPlaying=true;
    thread=new Thread(this);
    thread.start();

    }
    public void pause(){
        try {
            isPlaying=false;
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN://if user press button of screen
                if(event.getX()<screenX/2){//if user type in the left side of the screen
                    flight.isGoingUp=true;

                }
            break;
            case  MotionEvent.ACTION_UP://if user leave the screen
                flight.isGoingUp=false;
                if(event.getX()>screenX/2)
                    flight.toShoot++;
            break;
        }
        return true;
    }

    public void newBullet() {
        if(prefs.getBoolean("isMute",false))
            soundPool.play(sound,1,1,0,0,1);
        BulletActivity bullet=new BulletActivity(getResources());
        bullet.x=flight.x+flight.width;
        bullet.y=flight.y+(flight.height/2);
        bullets.add(bullet);
    }


    public static int getScore(){
        return score;
    }
}


package com.example.gobirdgo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.NoCopySpan;

import androidx.appcompat.app.AppCompatActivity;

public class Background extends AppCompatActivity {
    int x=0,y=0;
   private GameView gameview;
   static int  score;
    Bitmap background;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        score = GameView.getScore();

    }

    Background(int screenX, int screenY,Resources res){

        if(score>=0&&score<=10)
             background= BitmapFactory.decodeResource(res,R.drawable.forest_stage);
            else
                 background= BitmapFactory.decodeResource(res,R.drawable.stage2);


        background=Bitmap.createScaledBitmap(background,screenX,screenY,false);
    }

}

Also the background always doing a problem and cut in the middle of the game


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...