Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gaogao-9/9b6b5af702c00ba99d0accb6e7ca643f to your computer and use it in GitHub Desktop.
Save gaogao-9/9b6b5af702c00ba99d0accb6e7ca643f to your computer and use it in GitHub Desktop.
GeneratorFunctionはゲームプログラミングに優しいんですよの回
let frame = 0;
const actions = [
actionA,
actionB,
];
function main(){
try{
frame++;
for(const action of actions){
action(frame);
}
}
finally{
requestAnimationFrame(main);
}
}
main();
function actionA(frame) {
if(frame % 180 !== 0) return;
console.log("3秒に1回なにかするアクション");
}
let isFirst = true;
function actionB(frame) {
if(isFirst && frame === 60) {
console.log("1秒に1回なにかするアクション(最初だけ表示)");
isFirst = false;
}
else if(!isFirst && (frame - 60) % 120 === 0) {
console.log("2秒に1回なにかするアクション(2回目以降)");
}
}
(async ()=> {
while(true){
for await(const actionResult of loop());
}
})();
function* loop() {
const actions = [actionA, actionB];
for(const actionResults of parallel(actions)) {
yield nextFrame();
}
}
function* actionA() {
console.log("actionAを起動しました");
yield;
while(true){
yield* wait(180);
console.log("3秒に1回なにかするアクション");
}
}
function* actionB() {
console.log("actionBを起動しました");
yield;
yield* wait(60);
console.log("1秒に1回なにかするアクション(最初だけ表示)");
while(true){
yield* wait(120);
console.log("2秒に1回なにかするアクション(2回目以降)");
}
}
function* wait(frame) {
for(let i=frame;i--;) yield;
}
function* parallel(generators, ...args) {
const iterators = [...generators].map((gen) => (typeof(gen.next) === "function") ? gen : gen(...args));
while(true) {
const results = iterators.map((iter) => iter.next());
if(results.every((res) => res.done)) break;
yield results.map((res) => res.value);
}
}
function nextFrame() {
return new Promise((resolve)=> requestAnimationFrame(resolve));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment