Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Snake</title>
- </head>
- <body>
- <canvas id="snake" width="400" height="400"></canvas>
- <script type="text/javascript">
- (function (window, document) {
- function Snake(el) {
- this.el = el;
- this.ctx = this.el.getContext('2d');
- this.xv = 0;
- this.yv = 0;
- this.px = 10;
- this.py = 10;
- this.gs = 20;
- this.tc = 20;
- this.ax = 15;
- this.ay = 15;
- this.trail = [];
- this.tail = 5;
- document.addEventListener('keydown', this.onKeyDown.bind(this));
- this.interval = setInterval(this.game.bind(this), 1000/10);
- }
- Snake.prototype.game = function () {
- this.px += this.xv;
- this.py += this.yv;
- if (this.px < 0) { this.px = this.tc - 1; }
- if (this.px > this.tc - 1) { this.px = 0; }
- if (this.py < 0) { this.py = this.tc - 1; }
- if (this.py > this.tc - 1) { this.py = 0; }
- this.ctx.fillStyle = 'black';
- this.ctx.fillRect(0, 0, this.el.width, this.el.height);
- this.ctx.fillStyle = 'lime';
- for (var i = 0; i < this.trail.length; i++) {
- this.ctx.fillRect(
- this.trail[i].x * this.gs,
- this.trail[i].y * this.gs,
- this.gs - 2,
- this.gs - 2);
- if (this.trail[i].x == this.px && this.trail[i].y == this.py) {
- this.tail = 5;
- }
- }
- this.trail.push({
- x: this.px,
- y: this.py,
- });
- while (this.trail.length > this.tail) {
- this.trail.shift();
- }
- if (this.ax == this.px && this.ay == this.py) {
- this.tail++;
- this.ax = Math.floor(Math.random() * this.tc);
- this.ay = Math.floor(Math.random() * this.tc);
- }
- this.ctx.fillStyle = 'red';
- this.ctx.fillRect(
- this.ax * this.gs,
- this.ay * this.gs,
- this.gs - 2,
- this.gs - 2);
- }
- Snake.prototype.onKeyDown = function (e) {
- switch (e.keyCode) {
- case 37:
- this.xv = -1;
- this.yv = 0;
- break;
- case 38:
- this.xv = 0;
- this.yv = -1;
- break;
- case 39:
- this.xv = 1;
- this.yv = 0;
- break;
- case 40:
- this.xv = 0;
- this.yv = 1;
- break;
- }
- }
- window.Snake = Snake;
- })(window, document);
- document.addEventListener('DOMContentLoaded', function () {
- var snake = new Snake(document.getElementById('snake'));
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement