ReOrganizing the code

This commit is contained in:
2021-11-14 14:56:31 +01:00
parent b682ad199c
commit 0f4a403edb
7 changed files with 121 additions and 72 deletions

View File

@ -1,4 +1,6 @@
"use strict";
// import {Intro as game_intro} from "./Intro";
// import game_play from "./game.js";
document.addEventListener('DOMContentLoaded', init);
@ -10,70 +12,15 @@ function init() {
ctx = canvas.getContext('2d');
document.body.insertBefore(canvas, document.body.childNodes[0]);
function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
refresh();
requestAnimationFrame(run);
}
// -------------------------------------------------------------------
let gstate = 0;
let key = new Key(controls);
let intro = new Intro(ctx);
let gameOver = new GameOver(ctx);
let score = new Score(ctx);
let lives = new Lives(ctx);
let bar = new Bar(ctx, key);
let balls = [];
newGame();
function controls(e) {
switch (gstate) {
case 0: // Waiting to start
if (e.code == 'Space') newGame();
break;
case 1: // Playing...
if (e.code == 'Space' && balls.length>0) balls[balls.length - 1].start();
else
if (e.code == 'KeyX') { balls.push(new Ball(ctx, bar)); balls[balls.length - 1].start(); }
break;
case 2: // Game Over
if (e.code == 'Space') newGame();
break;
let key = new Key(), board;
function runBoard(stage) {
switch(stage) {
case 1: board = new GamePlay(ctx, key); break;
default: board = new GameIntro(ctx,key); break;
}
board
.run()
.then( stage=>runBoard(stage), e=>{} );;
}
function newGame() {
gstate = 1;
lives.reset();
score.reset();
bar.reset();
balls.push(new Ball(ctx, bar));
}
function refresh() {
switch (gstate) {
case 0: // Waiting to start
intro.update();
break;
case 1: // Playing...
case 2:
if(gstate==2) {
gameOver.update();
} else {
balls = balls.filter(ball => ball.update());
if (balls.length==0) {
if ( lives.lost() ) gstate=2;
else balls.push(new Ball(ctx, bar));
}
bar.update();
}
score.update();
lives.update();
break;
}
}
run();
runBoard(0);
}