简体   繁体   中英

How can I restart a game in Processing?

So I wanted to write a processing game where you try to catch a falling ball with basketball ring. It all goes pretty well until at some point, when you win or lose and press "restart" the game won't restart. This is my setup() method (only the relevant part of initializing variables):

void setup() {
    game = new Game();
    scr = new SplashScreen();
    gameBackground = new Image();
    background = new DynamicBackground();
    button = new Rect();

    /* Music set */
    intro = new Music();
    lifeMusic = new Music();
    failMusic = new Music();

    /* Ball and ring set */
    ball = new Image();
    ring = new Image();

    /* Life points set */
    life1 = new Image();
    life2 = new Image();
    life3 = new Image();
    life4 = new Image();
    failCount = 3;
    sucCount =0;
    winStr = "YOU WON!";
    gameOverStr = "GAME OVER";
    restartStr = "Resetart";

    flag = true;
    win = new Text();
    gameOver = new Text();
    restart = new Text();

    size(710, 490);

    .....
}

and this is my mousePressed method:

void mousePressed(){
    if(mouseX>button.x && mouseX <button.x+button.width && mouseY>button.y && mouseY <button.y+button.height){
        loop();
        setup();
    }
}

as you see, I tried to do noLoop() when the game is over, and than when you press on the button I called "restart" it will loop() and setup() .

The game get stuck when I press "restart" why?

setup() is called by an internal callback. It is not intended to call setup . Note in setup the window is initialized ( size(710, 490); ). The call of setup causes the system to hang.

Keep the initialization of the static objects in setup , but move the initialization of all the dynamic objects (the "moving" ones) to an init function. Call this function in setup and mousePressed :

void init() {
    game = new Game();
    scr = new SplashScreen();
    gameBackground = new Image();
    background = new DynamicBackground();
    button = new Rect();

    /* Ball and ring set */
    ball = new Image();
    ring = new Image();

    // ...
}
void setup() {

    size(710, 490);

    // init static objects

    /* Music set */
    intro = new Music();
    lifeMusic = new Music();
    failMusic = new Music();

    // init dynamic objects
    init();
}
void mousePressed(){
    if(mouseX>button.x && mouseX <button.x+button.width && mouseY>button.y && mouseY <button.y+button.height){
        init();
        loop();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM