-1
I have a small group of classes that implement a game of Snake with two players, the game is working as expected. But I’m using one while
infinity that is operating at the maximum speed that the JVM allows, so leaving the application open for 10 seconds already starts to give problem pro processor.
Currently it is like this:
public void tick() {
if (p1.snakeBody.size() == 0) {
p1.criarSnake(new Right(), new Coordenada(10, 10));
p2.criarSnake(new Left(), new Coordenada(30, 5));
}
ticks++;
if (ticks > 200000) { //aqui está o problema
ticks = 0;
p1.proximaPosicao();
p2.proximaPosicao();
if (p1.snakeBody().size() > 15) {
p1.snakeBody().remove(0);
p2.snakeBody().remove(0);
}
}
/**
* Cria a Thread que inicia o jogo
*/
public void start() {
Thread t = new Thread(this, "game loop");
t.start();
}
/**
* O jogo fica rodando enquanto os dois jogadores tiverem mais de zero vidas.
*/
public void run() {
while(p1.vidas != 0 && p2.vidas != 0) {
tick();
repaint();
}
JOptionPane.showMessageDialog(null, "\nThe winner is: " + p1.vitorioso(p2) + "!");
System.exit(0);
}
But in this way the computer needs to calculate loops and conditionals 200000 times for just one move! I read the documentation on Threads, but there are some competition things that I didn’t understand very well, I think what I’m looking for is simpler.
You can use the method Thread.sleep()
to prevent the processor from working so hard for so little?
What you want to do will only make the situation worse. You cannot stay in a loop doing this all the time, just do it when necessary. The whole architecture is wrong.
– Maniero
Do you have any reading recommendation? I would like to learn to architect correctly
– Pirategull
I don’t remember anything about that.
– Maniero
don’t have a mode to only run after a timer? Kind to do once every 250ms
– Pirategull
Yes, but I don’t know Java well enough to tell you about.
– Maniero
I don’t know if it’s what you’re looking for, but have you tried using one
Timer
?– hkotsubo