Add no walls option
This commit is contained in:
parent
2199a6036c
commit
58806617e6
2 changed files with 33 additions and 4 deletions
|
@ -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]))
|
||||
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")
|
||||
|
@ -169,6 +178,7 @@ export class Game {
|
|||
t.type = tiles.SNAKE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the 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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue