breakout/assets/js/GamePlay.js

80 lines
2.6 KiB
JavaScript

class GamePlay extends Board {
constructor(ctx, key) {
super(ctx, key);
this.controls = {
'KeyS': ()=>{
this.nextLevel(++this.level);
},
'KeyX': ()=>{
let b = new Ball();
b.update(this.ctx, this.bar.x + this.bar.w/2, this.bar.y);
this.balls.push(b);
this.balls[this.balls.length - 1].start();
},
'Space': ()=>{
this.balls[0].moving = true;
},
'KeyN': ()=>{
if(this.lives.get()==0) this.next(1);
}
}
this.gameOver = new GameOver();
this.score = new Score();
this.lives = new Lives();
this.bar = new Bar(ctx, key);
this.levels = new Levels();
this.newGame();
}
newGame() {
this.lives.reset();
this.score.reset();
this.nextLevel(1);
}
nextLevel(lvl) {
this.level = lvl;
this.bricks = this.levels.load(lvl);
this.bar.reset();
this.balls = [];
this.balls.push(new Ball());
}
update() {
if(this.lives.get()==0) {
this.loopStop();
this.gameOver.update(this.ctx);
// this.next(2);
} else {
this.balls = this.balls.filter(ball => {
let r = ball.update(this.ctx, this.bar.x + this.bar.w/2, this.bar.y);
ball.collide( this.bar.x, this.bar.y, this.bar.x + this.bar.w, this.bar.y + this.bar.h );
this.bricks.forEach(b=>{
if(b.lives>0){
if ( ball.collide(b.x,b.y,b.x+b.w,b.y+b.h) ) {
this.score.add(1);
b.crack();
}
}});
return r;
}
);
if (this.bricks.length==0) {
this.nextLevel(++this.level);
}
if (this.balls.length==0) {
if ( !this.lives.lost() ) this.balls.push(new Ball());
}
this.bricks = this.bricks.filter(brick => brick.update(this.ctx));
// if ( this.bricks.length == 0 ) this.nextLevel();
this.bar.update();
}
this.score.update(this.ctx);
this.lives.update(this.ctx);
}
}