From ff95308e299eadf80cd5767015bd4917608677fb Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 15 Oct 2018 18:02:12 +0100 Subject: [PATCH] Gravity:tm: --- JavaScript/Snetris/index.js | 60 ++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/JavaScript/Snetris/index.js b/JavaScript/Snetris/index.js index 01903c4..56b9861 100644 --- a/JavaScript/Snetris/index.js +++ b/JavaScript/Snetris/index.js @@ -31,7 +31,6 @@ class Apple { update() { if (ActiveSnake.head.x == this.pos.x && ActiveSnake.head.y == this.pos.y) { - // freeze snake and return state return 'collide'; } } @@ -102,9 +101,43 @@ class Block { constructor(tail) { this.blocks = tail; this.falling = true; - this.pixelPos; - this.targetGamePos; - this.targetPixelPos; + this.pixelPos = {x: tail[0].x * BLOCK_SIZE.x, y: tail[0].y * BLOCK_SIZE.y}; + this.lastPixelPos = {x: 0, y: 0}; + this.targetGamePos = {x: 6, y: 11}; + this.targetPixelPos = {x: 6 * BLOCK_SIZE.x, y: 11 * BLOCK_SIZE.y}; + + this.velocity = 0; + this.gravity = 5.81; + } + + fall() { + this.lastPixelPos = this.pixelPos; + if (this.falling) { + this.velocity += this.gravity; + this.pixelPos.y += this.velocity; + } + if (this.pixelPos.y >= this.targetPixelPos.y) { + this.falling = false; + this.pixelPos.y = this.targetPixelPos.y; + } + + // for (peice of this.blocks) { + + // } + } + + draw() { + if (this.falling) { + ctx.fillStyle = BACKGROUND_COLOUR; + ctx.fillRect(this.lastPixelPos.x, this.lastPixelPos.y, BLOCK_SIZE.x, BLOCK_SIZE.y); + ctx.fillStyle = SNAKE_COLOUR; + ctx.fillRect(this.pixelPos.x, this.pixelPos.y, BLOCK_SIZE.x, BLOCK_SIZE.y); + } else { + GameGrid[this.targetGamePos.x][this.targetGamePos.y] = 1; + // for (let i = 0; i < this.tail.length; i++) { + // GameGrid[this.tail[i].x][this.tail[i].y] = 1; + // } + } } } @@ -136,7 +169,12 @@ function gameLoop() { ActiveApple = new Apple(); ActiveSnake = new Snake(); } - + + for (block of Blocks) { + if (!block.falling) { + block.draw(); + } + } ActiveSnake.draw(); ActiveApple.draw(); draw(); @@ -145,15 +183,15 @@ function gameLoop() { function animationLoop() { if (!stop) { - // loop through Boxes and if a box is in the falling - // state, then apply animation + for (block of Blocks) { + if (block.falling) { + block.fall(); + block.draw(); + } + } } } -function drawAnimation() { - -} - function draw() { for (let i = 0; i < GAME_SIZE.x; i++) { for (let j = 0; j < GAME_SIZE.y; j++) {