Jump to content

Dúvida, alterar Timer ou alterar step()


Recommended Posts

Posted (edited)

Boa tarde,

Neste troço de código, usado para que num aquário os peixes movam-se todos ao mesmo tempo

private void startMovements() {

timer = new Timer(TIMERDELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
step();
}
});
timer.start();
}
private void step() {
// HERE STEP to all
for (MovingElement mElement : moveElems) {
mElement.step();
}

no entanto preciso de fazer os peixes (inseridos numa ArrayList) moverem-se de forma independente, ou seja, cada um com o seu tempo.

o docenete da cadeira propôs que altera-se-mos o timer.

Já tentei que a variavel TIMERDELAY toma-se um valor random:

TIMERDELAY = rg.nextInt(2500);

mas sem sucesso pois os peixes continuam-se a mover todos ao mesmo tempo.

Será que alterando a função void step () para que a cada ciclo for cada peixe tenha um seu timer?

Agradeço respostas

Cumprimentos, Júlio Vieira

Edited by juliovieira
Posted

Assumindo que o moveElems é a tua ArrayList e que cada MovingElement é um peixe, como estás a chamar o step() quando um timer termina e o step() faz com que todos os peixes se movam... Eu diria que tens que criar um Timer para cada peixe.

Ou seja, crias um Timer para cada MovingElement:

for (MovingElement mElement : moveElems) {
   (new Timer(TIMERDELAY, new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           mElement.step();
       }
   })).start();
}

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Posted (edited)

tentei implementar esse código mas sem sucesso, também tentei fazer algumas alterações:

private void startMovements(final MovingElement mElement) {
 timer = new Timer(TIMERDELAY, new ActionListener() {
	 public void actionPerformed(ActionEvent e) {
		 mElement.step();
	 }
 });
 timer.start();
}

eliminando a função step() mas também sem sucesso

Edited by juliovieira
Posted

Pah, tens que gerar um número aleatório para cada iteração do ciclo. Eu não coloquei, porque praticamente só copiei e colei o código que puseste, mas achei que era óbvio. Erro meu...

for (MovingElement mElement : moveElems) {
   (new Timer(rg.nextInt(2500), new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           mElement.step();
       }
   })).start();
}

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Posted

o que podes fazer é tomar outro tipo de abordagem, é em vez de ter n timers, é teres "velocidades" diferentes dos peixes.

algo que seria codificado deste genero:

class Peixe
{
 protected int velocity;
 protected int last_move_time;

 void setVelocity(int vel)
 {
   velocity = vel
 }

 void timestep(int time)
 {
   if (time - last_move_time >= velocity)
   {
     // mover o peixe

     // guardar o tempo da última acção
     last_move_time = time;
   }
 }
}

for(i = 0; i < n_peixes; i++)
 peixes[i].setVelocidade(Random()); // Random daria o tempo necessário de espera para se poder movimentar

...
while (1)
{
 for(i = 0; i < n_peixes; i++)
   peixes[i].timestep(Time()); // Time daria o tempo actual em (nano|micro)segundos ...
}

isto é obviamente um pseudo-código arraçado a Java

IRC : sim, é algo que ainda existe >> #p@p

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.