1
0
Fork 0

Add no walls option

This commit is contained in:
Ethanell 2021-03-26 23:50:47 +01:00
parent 2199a6036c
commit 58806617e6
2 changed files with 33 additions and 4 deletions

View file

@ -2,6 +2,10 @@ import {Tile, tiles} from "./Tile.js"
import {Snake, directions} from "./Snake.js"; import {Snake, directions} from "./Snake.js";
function mod_floor(a, n) {
return ((a % n) + n) % n;
}
export class Game { export class Game {
/** /**
* Generate a new game of Snake * Generate a new game of Snake
@ -150,17 +154,22 @@ export class Game {
/** /**
* Update the snake on the world and check for collision * Update the snake on the world and check for collision
*/ */
updateSnake() { 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])) 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 { else {
const t = this.world[x][y]; const t = this.world[x][y];
if (t.type === tiles.APPLE) { if (t.type === tiles.APPLE) {
this.snake.eat(); this.snake.eat();
this.appleGenerator(); this.appleGenerator();
this.score++; this.score++;
if (!(this.score%5) && this.snakeSpeed > 50) { if (!(this.score % 5) && this.snakeSpeed > 50) {
this.snakeSpeed -= 10; this.snakeSpeed -= 10;
} }
if (this.onEat && typeof this.onEat === "function") if (this.onEat && typeof this.onEat === "function")
@ -168,6 +177,7 @@ export class Game {
} }
t.type = tiles.SNAKE; t.type = tiles.SNAKE;
} }
}
} }
/** /**
@ -219,7 +229,7 @@ export class Game {
* @param {int} appleSpeed * @param {int} appleSpeed
* @param {int} lives * @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) 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; this.size = size;
else else
@ -239,6 +249,9 @@ export class Game {
this.lives = lives; this.lives = lives;
else else
throw new InvalidGameOption("lives"); throw new InvalidGameOption("lives");
if (walls && typeof walls === "boolean")
this.walls = walls
} }
} }

View file

@ -1,5 +1,21 @@
{ {
"Level 1": { "Level 1": {
"snakeSpeed": 300
},
"Level 2": {
"snakeSpeed": 250
},
"Level 3": {
"snakeSpeed": 200
},
"Level 4": {
"snakeSpeed": 150
},
"Level 5": {
"snakeSpeed": 100 "snakeSpeed": 100
},
"No walls": {
"snakeSpeed": 100,
"walls": false
} }
} }