Controlling while loops in Dart -


i stuck trying simple. want able count upwards until click on screen @ point want counting stop. in reality code carrying out complex ai calculations game, first want understand how control while loop. in android trivial.

here code looks like

bool ok = true;  main() async{  html.queryselector('#content').onmouseup.listen((e){    ok = false;  });   await for(int in naturals){    print(i);    await sleep();  } }  stream naturals async* {  int k = 0; while (ok) { yield await k++; } }  future sleep() {  return new future.delayed(const duration(milliseconds: 1), () => "1"); } 

i put sleep() method in way ensure control passed event loop.

is possible control while loop without sleep() method?

to provide more general answer - instead of loop, want schedule sequence of future tasks each executes 1 iteration or step of ai code (or whatever background process want have running).

you can have step task recursively schedule itself:

dynamic dosomething(_) {   print('doing ...');    if(!stop) {     new future.delayed(delay, (){}).then(dosomething);   }   return null; }  main() async {    dosomething(null);  } 

although don't recommend doing this. it's awkward control - step code has check flag variable see if should continue or stop , it's free running.

alternatively use timer:

void dosomething(timer timer) {   print('doing ...');   }  main() async {   new timer.periodic(delay, dosomething);  } 

this throttled @ constant rate , has uniform time step, , easier stop (call cancel() on timer).

another approach might synchronize browser's draw refresh cycle requesting future animation frames:

import 'dart:html';  dosomething(num delta) {   print('doing ...');     window.animationframe.then(dosomething); }  void main() {   window.animationframe.then(dosomething); } 

time steps not constant time delta. advantage of approach animation frame futures not scheduled if browser window hidden.

see how drive animation loop @ 60fps dart?

those simple examples. setting proper background processes physics simulation , ai in web games surprisingly (to me @ least) non-trivial. here 2 resources found helpful.

http://gameprogrammingpatterns.com/ - nice free online book of game programming patterns. http://gameprogrammingpatterns.com/game-loop.html - chapter on game loops.

http://gafferongames.com/game-physics/fix-your-timestep/ - part of sequence of articles on physics simulation in games.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -