lunedì 8 febbraio 2016

Movimenti asincroni e sincroni

Alcuni programmi, come ad esempio i videogiochi, debbono muovere molti oggetti contemporaneamente. Se questi movimenti debbono essere sincronizzati, livecode permette di bloccare i movimenti con i comandi lock moves e unlock moves.
In pratica si bloccano tutti i movimenti (lock moves), si danno a tutti gli oggetti il comando di muoveri (move) e poi si lancia unlock moves. In questo modo i comandi di movimento verranno eseguiti contemporaneamente.
Esempio:

Se poi noi vogliamo mandare dei comandi asincroni, la questione è più complicata.
Ad esempio per ottenere il seguente programma:

bisogna considerare questo:
  • solo un movimento per messaggio
  • utilizzare l'opzione without waiting
  • calcolare il tempo del movimento
  • alla fine del messaggio, se servono altri movimenti, utilizzare send in xx sec per lanciare un altro messaggio contenente il nuovo movimento. La variabile xx deve essere il tempo per eseguire il movimento del messaggio corrente.
Il codice del programma asincrono è:

on mouseUp
   put the number of me into temp
   if the label of me is not "stop" then
      set the label of me to "STOP"
      set the backgroundColor of me to "red"
      set the muovi of me to true   
      movimento temp
   else
      stop moving graphic temp
      repeat for each line tLine in the dafare of me
         cancel tLine         
      end repeat
      set the dafare of me to empty
      set the label of me to "START"
      set the backgroundColor of me to "green"
      set the muovi of me to false
   end if   
end mouseUp

on movimento ogg
   #put ogg, temp
   put the loc of me into temp
   if the direzione of graphic ogg is "+" then
      set the direzione of graphic ogg to "-"
      add -70 to item 2 of temp
      move graphic ogg to temp   without waiting
   else
      set the direzione of graphic ogg to "+"
      add -156 to item 2 of temp
      move graphic ogg to temp   without waiting
   end if
   if the muovi of me then
      put the dafare of me into temp2
      send ("movimento " & ogg ) to me in 0.5 sec
      put the result & return after temp2
      set the dafare of me to temp2   
   end if
   #put temp
end movimento


mentre il codice del programma sincrono è:

on mouseUp
   lock moves
   repeat with i=1 to 8      
      send "movimento " & i to button i
   end repeat
   unlock moves
end mouseUp

Nessun commento:

Posta un commento