James McDowell
James McDowell

Reputation: 2768

JFrame skipping some repaint() calls

I'm making a snake game and I've encountered an error.
I have tried two different loops: thread.sleep and Timer.schedule.
I have gotten the same problem.
It will be working fine, but at random intervals, it will start to skip every other frame for 6-10 frames.
In case I wasn't clear, 1 frame is

@Override public void paintComponent(Graphics G){...}

being called. (I have also tried paint)
This has occurred in some other games I've created, but not all. What can I do to fix it?

Here's a full copy of the code: https://github.com/jnmcd/Snake/blob/master/Code.java

EDIT: I've done some debugging. It appears that the it's not a problem with the paint. The JPanel doesn't always update. What can I do to fix it?

Upvotes: 1

Views: 420

Answers (2)

Madhan
Madhan

Reputation: 5818

Also In the checkKillCollisions you have to break the loop right after you found the losing condition.

Also if the game ends it keeps on showing the error message[Dialog] for which there i no end.So I have created a flag gameOver to check is game is over or not in Snake Class

 static Boolean gameOver = false;//Defined in Snake Class


 public void checkKillCollisions() {
    boolean lose = false;
    for (int i = 1; i < Snake.segments.size(); i++) {
        if (Snake.segments.get(i).x == x && Snake.segments.get(i).y == y) {
            lose = true;
            break;//Have to do this
        }
    }
    if (x >= 60 || x < 0 || y >= 60 || y < 0) {
        lose = true;
    }
    if (lose) {
        Snake.window.popUp("You Lose");
    }
    Snake.gameOver = lose;//Will set the gameOVer flag in Snake class
}

And I've modified the Loop class to stop running right after the gameOver flag is set to true

 class Loop extends TimerTask {

@Override
public void run() {
    if (!Snake.gameOver) {
        Snake.updates();
        Snake.window.render();
    } else {
        System.out.println("Game Over");
        cancel();
        Snake.window.dispose();
    }
}
}

Upvotes: 0

James McDowell
James McDowell

Reputation: 2768

I found what I needed to do. I had to add a revaidate() after the repaint().

Upvotes: 1

Related Questions