diff --git a/source/game.js b/source/game.js index 2ee16b8..5570c16 100644 --- a/source/game.js +++ b/source/game.js @@ -23,8 +23,8 @@ class Game { this._cameraFace = this._world._faceVectors[3]; this._cameraUpCached = this._camera.up.clone(); - this._snake = new Snake(this._world, this._camera.up.clone(), this._cameraFace, { name: 'player' }); - this._snakeEnemy = new Snake(this._world, this._camera.up.clone(), this._cameraFace.clone().negate(), { name: 'enemy', color: Const.Colors.ENEMY }); + this._snake = this._initSnake({ type: 'player' }); + this._snakeEnemy = this._initSnake({ type: 'enemy', color: Const.Colors.ENEMY }); this._lastTime = window.performance.now(); @@ -61,6 +61,11 @@ class Game { this._animate(); } + _initSnake(options) { + assertTruthy(this._world, this._camera, this._cameraFace); + return new Snake(this._world, this._camera.up.clone(), this._cameraFace, options); + } + // TODO(maros): Move camera to its own class. _setupScene(container) { let scene = new THREE.Scene(); diff --git a/source/snake.js b/source/snake.js index 5b9591f..1a089c7 100644 --- a/source/snake.js +++ b/source/snake.js @@ -12,14 +12,14 @@ let assertTruthy = require('./utils/assert-truthy'); let { Graph } = require('./graph'); module.exports = class Snake { - constructor(world, direction, face, { startPosition = null, color = Const.Colors.SNAKE, name = '' } = {}) { + constructor(world, direction, face, { startPosition = null, color = Const.Colors.SNAKE, type = 'player' } = {}) { if (!startPosition) { startPosition = Voxel.middleVoxel(face); } this.world = world; this.speed = 0.15; - this.name = name; + this.type = type; this.color = color; this.face = face; this.size = 6; @@ -161,18 +161,22 @@ module.exports = class Snake { assertTruthy(this.position, this._direction); const voxel = Voxel.findOrCreate(this.position); - const next = voxel.next(this._direction); + const nextVoxel = voxel.next(this._direction); - if (next.type === 'snake') { + if (this.type === 'player' && nextVoxel.type === 'snake') { + return this.die(); + } + + if (nextVoxel.type === 'snake') { for (let neighbor of voxel._next.values()) { if (neighbor.type !== 'snake') { return neighbor.position; } } - this.die(); + return this.die(); } else { - return next.position; + return nextVoxel.position; } }