From 58806617e616509881f464ed80dd00a8d7d4b71f Mon Sep 17 00:00:00 2001 From: flifloo Date: Fri, 26 Mar 2021 23:50:47 +0100 Subject: [PATCH] Add no walls option --- sources/js/Game.js | 21 +++++++++++++++++---- sources/levels.json | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/sources/js/Game.js b/sources/js/Game.js index 5edae10..f13bc1b 100644 --- a/sources/js/Game.js +++ b/sources/js/Game.js @@ -2,6 +2,10 @@ import {Tile, tiles} from "./Tile.js" import {Snake, directions} from "./Snake.js"; +function mod_floor(a, n) { + return ((a % n) + n) % n; +} + export class Game { /** * Generate a new game of Snake @@ -150,17 +154,22 @@ export class Game { /** * Update the snake on the world and check for collision */ + updateSnake() { - for (const [x, y] of this.snake.body) + for (const i in this.snake.body) { + const [x, y] = this.snake.body[i]; if (!(x in this.world) || !(y in this.world[x])) - throw new GameOver(); + if (this.walls) + throw new GameOver(); + else + this.snake.body[i] = [mod_floor(x, this.size[0]), mod_floor(y, this.size[1])]; else { const t = this.world[x][y]; if (t.type === tiles.APPLE) { this.snake.eat(); this.appleGenerator(); this.score++; - if (!(this.score%5) && this.snakeSpeed > 50) { + if (!(this.score % 5) && this.snakeSpeed > 50) { this.snakeSpeed -= 10; } if (this.onEat && typeof this.onEat === "function") @@ -168,6 +177,7 @@ export class Game { } t.type = tiles.SNAKE; } + } } /** @@ -219,7 +229,7 @@ export class Game { * @param {int} appleSpeed * @param {int} lives */ - load({size = [15, 15], direction = directions.RIGHT, snakeSpeed = 500, lives = 3} = {}) { + load({size = [15, 15], direction = directions.RIGHT, snakeSpeed = 500, lives = 3, walls = true} = {}) { if (size && Array.isArray(size) && size.length === 2 && size.filter(s => typeof s === "number" && s > 0 && s % 1 === 0).length === size.length) this.size = size; else @@ -239,6 +249,9 @@ export class Game { this.lives = lives; else throw new InvalidGameOption("lives"); + + if (walls && typeof walls === "boolean") + this.walls = walls } } diff --git a/sources/levels.json b/sources/levels.json index af6a60e..bff0f7a 100644 --- a/sources/levels.json +++ b/sources/levels.json @@ -1,5 +1,21 @@ { "Level 1": { + "snakeSpeed": 300 + }, + "Level 2": { + "snakeSpeed": 250 + }, + "Level 3": { + "snakeSpeed": 200 + }, + "Level 4": { + "snakeSpeed": 150 + }, + "Level 5": { "snakeSpeed": 100 + }, + "No walls": { + "snakeSpeed": 100, + "walls": false } }