jlars789
jlars789

Reputation: 153

My snake game is operating very slowly. Is there any way to optimize it?

I have had a persistent issue of my snake game running slowly as the snake gets larger. I have narrowed it down to this block of code that is causing the problems:

for(int i = 0 ; i < snake.size(); i++) {
    if(xCoor == snake.get(i).getxCoor() && yCoor == snake.get(i).getyCoor()) {
        if(i != snake.size() - 1) {
            stop();
            tries = 1;
            }
        }
    }

This is the collision detection of the snake's head hitting the snake's body. I haven't been able to think of another way to optimize this besides removing it, which removes the core of the game. I think the issue that this runs each tick. I could change off from using ticks, but I have no idea how to start doing that.

EDIT: Here is how I have my game timing set up:

public void tick() {
    if(snake.size() == 0) {
        b = new BodyPart(xCoor, yCoor, 10);
        snake.add(b);
        }
    ticks++;
    if(ticks > 750000) {

    }
}

EDIT2: Thread.sleep(60) worked wonders! My stop() method just doesn't work anymore, but all it really did was set running to false, so I just did that manually on anything that ended the game.

Upvotes: 2

Views: 422

Answers (1)

chandra
chandra

Reputation: 500

You could try the following approaches:

1.You could create a Map or Set of (x,y) co-ordinates which are already occupied and check against it. This would be updated much less frequently than access.

2.You could create a two-dimensional array of boolean for each board position. Checking would be very fast. Updating would take some time. It depends on the relative frequencies on which the two occur.

Upvotes: 2

Related Questions