Created
April 13, 2018 10:41
-
-
Save kt2/35bd04c383facd2b6a4664a4011893b8 to your computer and use it in GitHub Desktop.
JS simulate a C++ like game loop using async function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
myReq = null; | |
root = []; | |
count = 0; | |
run_menu = 1; | |
requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; | |
cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame; | |
c = {}; | |
c.element = function() { | |
this.resolve = null; | |
}; | |
c.element.prototype.constructor = c.element; | |
c.element.prototype.exit = function(v) { | |
cancelAnimationFrame(myReq); | |
root.splice(root.indexOf(this), 1); | |
//exit with value | |
this.resolve(v); | |
if (root.length) { | |
// continue the main scene | |
root[0].cycle(root[0].resolve); | |
} | |
}; | |
c.element.prototype.run = async function(callback) { | |
cancelAnimationFrame(myReq); | |
root.push(this); | |
var ret = await new Promise(resolve => { | |
this.cycle(resolve); | |
}); | |
if (ret) { | |
callback(ret); | |
} | |
}; | |
c.element.prototype.logic = function() { | |
}; | |
c.element.prototype.drawAll = function() { | |
root.forEach(function(i) { | |
i.draw(); | |
}); | |
}; | |
c.element.prototype.cycle = function(resolve) { | |
this.resolve = resolve; | |
myReq = requestAnimationFrame(this.cycle.bind(this, resolve)); | |
this.logic(); | |
this.drawAll(); | |
}; | |
c.mainscene = function() { | |
}; | |
c.mainscene.prototype = Object.create(c.element.prototype); | |
c.mainscene.constructor = c.mainscene; | |
c.mainscene.prototype.logic = function() { | |
if (run_menu) { | |
run_menu = 0; | |
var m = new c.menu(); | |
var callback = function(ret) { | |
console.log('menu callback ' + ret); | |
}; | |
m.run(callback); | |
} | |
}; | |
c.mainscene.prototype.draw = function() { | |
console.log('draw main'); | |
}; | |
c.menu = function() { | |
}; | |
c.menu.prototype = Object.create(c.element.prototype); | |
c.menu.constructor = c.menu; | |
c.menu.prototype.draw = function() { | |
console.log('draw menu'); | |
if (count > 100) { | |
this.exit(4); | |
} | |
count++; | |
}; | |
var main = new c.mainscene(); | |
main.run(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment