snake-cli-ts
Version:
Nodejs cli snake game
106 lines (105 loc) • 3.47 kB
JavaScript
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Point_1 = __importDefault(require("../helpers/Point"));
var Snake = (function () {
function Snake(game) {
this.game = game;
this.x = 0;
this.y = 0;
this.dx = 0;
this.dy = 0;
this.lastDx = 0;
this.lastDy = 0;
this.body = [];
this.lastBody = [];
this.speed = 5;
this.reset();
}
Snake.prototype.reset = function () {
this.dx = 0;
this.dy = 0;
this.lastDx = 0;
this.lastDy = 0;
this.body = [];
this.lastBody = [];
this.x = Math.round(this.game.width / 2);
this.y = Math.round(this.game.height / 2);
this.body.push(new Point_1.default(this.x, this.y));
this.speed =
{
easy: 5,
medium: 10,
hard: 15,
}[this.game.get('difficulty')] || 5;
};
Snake.prototype.move = function () {
var _a;
this.x += this.dx;
this.y += this.dy;
(_a = this.game.foodManager.find(this.x, this.y)) === null || _a === void 0 ? void 0 : _a.use();
if (this.game.config.moveThroughWall) {
if (this.x === -1) {
this.x = this.game.width - 1;
}
if (this.x === this.game.width) {
this.x = 0;
}
if (this.y === this.game.height) {
this.y = 0;
}
if (this.y === -1) {
this.y = this.game.height - 1;
}
}
this.lastBody = __spread(this.body);
this.body.unshift(new Point_1.default(this.x, this.y));
this.body.pop();
this.lastDx = this.dx;
this.lastDy = this.dy;
return this;
};
Snake.prototype.eat = function (x, y) {
this.body.push(new Point_1.default(x, y));
return this;
};
Snake.prototype.collide = function (x, y) {
return this.body.slice(1).find(function (p) { return p.x === x && p.y === y; });
};
Snake.prototype.isOutOfBox = function (x, y) {
return x < 0 || x >= this.game.width || y < 0 || y >= this.game.height;
};
Snake.prototype.isDead = function () {
if (this.collide(this.x, this.y)) {
return true;
}
if (this.game.config.moveThroughWall === false && this.isOutOfBox(this.x, this.y)) {
return true;
}
return false;
};
return Snake;
}());
exports.default = Snake;