syd
syd

Reputation: 197

Find out the exact time to sleep in each thread

I am making a snake game. I have two threads (MAIN, Snake) and one thread for each frog(food) that i created. Frogs are able to move too but slower then the snake(so i would be able to catch them). Here is when things start to get interesting. In order to control snake and frogs movement i do this:

Snake.java:

public void run() {
        while (isAlive){
            move();
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
}

I ask my thread to sleep for some time. I do the same with my MAIN thread so i dont have any problems with repainting my JPanel:

GameController.java:

void tick() {
        for (Frog frog : frogs) {
            if (CollisionChecker.checkFoodCollision(snake.getBody().get(0), frog)) {
                snake.grow();
                frog.respawn();
                score++;
            }
        }
        if (CollisionChecker.checkSnakeCollision(snake.getBody())){
            onStop();
        }
        try {
            Thread.sleep(snakeDelay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}

If i want to catch my frogs i have to make them sleep longer, so i did this:

Frog.java

public void run() {
        while (isAlive){
            try {
                Thread.sleep(snakeDelay * 3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            move();
        }
}

Game works but when I sent my project for a code review I was told that this 3 from method run() is a magic number and I totally agree. I don't know what to do though. How do I manage my threads here?

Edit: seems like I had a false view on what is a "magic number".

Upvotes: 3

Views: 125

Answers (1)

Andrew
Andrew

Reputation: 49626

A Frog constructor might take a long argument which defines the frogDelay:

class Frog {
    private long delay;

    public Frog(long delay) {
        this.delay = delay;
    }

    public void run() {
        Thread.sleep(delay);
    }
}

When you are creating a new Frog(calculateFrogDelay()), the value of this parameter can be calculated by the constants SHAKE_DELAY and RATIO:

private final long SHAKE_DELAY = 100;
private final int RATIO = 3;

private long calculateFrogDelay() {
    return SHAKE_DELAY * RATIO;
}

You could add the ability to change these values at runtime - then you would need listeners to correct frog values.

Upvotes: 2

Related Questions