如何暂停和取消暂停游戏中的线程?

时间:2015-02-24 22:30:43

标签: java android multithreading

我是开发游戏的新手,我试图开发一款简单的射击太空游戏,一切都很完美。现在,我想在用户点击后退按钮时创建一个Dialog弹出窗口,游戏应该暂停,直到用户按下简历。游戏暂停但是当我点击恢复按钮时,游戏仍然暂停在这里是我的游戏循环类:

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

    public static  MyPreferences pref;
    public static Levels level;
    public static int SCREEN_W;
    public static int SCREEN_H;
    public static  boolean running;
    private static Thread thread = null;
    private SurfaceHolder holder;
    private Canvas canvas;
    private Paint p = new Paint();
    public static Handler handler = new Handler();
    public static Resources res;
    public static Timer timer;






    public Game(Context context) {
        super(context);
        res = getResources();
        holder = getHolder();
        holder.addCallback(this);

        level = new Levels();
        timer = new Timer();
        pref = new MyPreferences(context);
        System.out.println("Create Game instance");

    }



    public void run() {
        init();

        long lastTime = System.nanoTime();
        double delta = 0;
        double ns = 1000000000.0 / 30.0;

        System.out.println("Run method" + running);
        while (running) {
            System.out.println("+++++++++++++++++++++++++++++++++++");
            long now = System.nanoTime();
            delta+=(now - lastTime) / ns;
            lastTime = now;

            if(!holder.getSurface().isValid()){continue;}

            canvas = holder.lockCanvas();
            SCREEN_W = canvas.getWidth();
            SCREEN_H= canvas.getHeight();

            while (delta >-1) {
                tick();
                delta--;
            }

            level.level1();
            render(canvas); 
            holder.unlockCanvasAndPost(canvas);


            if(ControlPanel.PLAYER_POWER <=0){
                System.out.println("Loose!");
                ControlPanel.PLAYER_POWER  = 100;
                stop();
                start();
            }
        }
    }



    private void render(Canvas c) {
        handler.render(c);
        textOnScreen(c);
    }


    public void tick(){
        handler.tick();
    }


    public void init(){
        System.out.println("Init game...");
        ControlPanel.COINS = pref.getInt("coins");
        MainActivity.music.backgroundMusic();
        handler.addSpaceShip(new Player(500, 500, 10, 10, handler, Sprite.getSprite(0)));

//      handler.addKing(new King(Game.SCREEN_W / 2, 100,
//              40, 40, handler, Sprite.getSprite(18), 0));
    }



    public  void start() {
        if(thread==null){
        System.out.println("Start thread");
        thread = new Thread(this);
        thread.start();     

        timer.start();
        }
        if(!running)    running = true;
        System.out.println("Running = " + running);
    }


    public static  void stop() {
        System.out.println("Stop thread");
        running = false;
        timer.stop();
        pref.putInt("coins", ControlPanel.COINS);
        System.out.println("Running = " + running);
    }






    public  void destroyed() {
        System.out.println("Stop");
        running = false;
        try {
            thread.join(300);
            thread.interrupt();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    public void textOnScreen(Canvas c){
        p = new Paint();
        p.setColor(Color.YELLOW);
        p.setTextSize(50);
        c.drawText("POWER = " + ControlPanel.PLAYER_POWER, SCREEN_W / 2 ,50 , p);
        c.drawText("Time = " + timer.timeFormat(), 100  ,50 , p);
        c.drawText("Coins = " + ControlPanel.COINS, 10 ,SCREEN_H - 10 , p);
        p.setColor(Color.WHITE);
        c.drawText("Bullets = " +ControlPanel.BULLET, SCREEN_W - 390,SCREEN_H - 10 , p);
        p.setColor(Color.WHITE);
        c.drawText(ControlPanel.Distance + " km ", SCREEN_W  /2  - 200,SCREEN_H - 10 , p);
    }







    @Override
    public void surfaceCreated(SurfaceHolder holder) {
System.out.println("###surface created!");

    }







    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        System.out.println("###surface Changed!");

    }







    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        System.out.println("###surface Destroid!");

    }
} 

这是我的Dialog类:

public class DialogPause extends Dialog implements android.view.View.OnClickListener{

    Button btn;

    public DialogPause(Context context) {
        super(context);
        setContentView(R.layout.pause_game);
        Game.running = false;

        btn = (Button) findViewById(R.id.resume);
        btn.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
if(v.getId() == R.id.resume){
    Game.running = true;

    this.dismiss();
}
    }
}

和我的MainActivity类:

  public class MainActivity extends Activity implements OnTouchListener {

    public Game game;
    public static Music music;


    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Full screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        music = new Music(this);
        game = new Game(this);
        game.setOnTouchListener(this);
        setContentView(game);

    }




    protected void onStart() {
    game.start();
        super.onStart();
    }


    @Override
    protected void onStop() {
        music.StopBackgroundMusic();
        game.destroyed();
        super.onStop();
    }



    @Override
    public void onBackPressed() {
        new DialogPause(this).show();
    }




    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            //the x and y point 
            float x  = event.getX();
            float y = event.getY();

            //The w and h of the space ship
            int spaceShipW = Game.handler.spaceShip.get(0).getSprite().getWidth();
            int spaceShipH = Game.handler.spaceShip.get(0).getSprite().getWidth();

            //Moving 
            if( x > 10 || x > Game.SCREEN_W - spaceShipW ){
                Game.handler.spaceShip.get(0).setX((int) x - (spaceShipW / 2) - 64);
                Game.handler.spaceShip.get(0).setY((int) y -  (spaceShipH +200) );
            }

            //Shooting
            Bullet.shoot(y, x);

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN :
                //Change sprite image when click
                Game.handler.spaceShip.get(0).getSprite().setWhatColumnX(0);
                Game.handler.spaceShip.get(0).getSprite().setFramesToAnimate(2);

            case MotionEvent.ACTION_MOVE :
                break;
            case MotionEvent.ACTION_UP :
                //Change sprite image when release
                Game.handler.spaceShip.get(0).getSprite().setWhatColumnX(1);
                Game.handler.spaceShip.get(0).getSprite().setFramesToAnimate(0);

                break;

            default:
                break;
            }

        } catch (Exception e) { 

        }
        return true;

    }

}

顺便说一句,我希望听到更多关于我创建的游戏循环代码的意见,因为我退出游戏时有时会崩溃。

如何在游戏加载完成后使用一些asyncTask,因为它需要4秒才能加载游戏。 感谢所有帮助我的人,我非常感谢!

1 个答案:

答案 0 :(得分:5)

添加布尔值paused,每当按下后退按钮切换值(paused = !paused;

在你拨打tick之前循环添加一个条件:

if(!paused) tick();

最好不要乱用线程。