Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>Snake Game</title>
- </head>
- <body>
- <canvas id="stage" width="600" height="600"></canvas>
- <script type="text/javascript">
- window.onload = function () {
- var stage = document.getElementById('stage');
- var context = stage.getContext("2d");
- document.addEventListener("keydown", keyPush);
- setInterval(game, 80);
- const vel = 1;
- var speedX = speedY = 0;
- var startPointX = 10;
- var startPointY = 15;
- var lenghtPiece = 30;
- var tileCount = 20;
- var appleX = appleY = 15;
- var trail = [];
- tail = 5;
- function game() {
- move();
- teleportPosition();
- drawBacktround();
- drawApple();
- drawSnake();
- eat();
- }
- function drawBacktround() {
- context.fillStyle = "black";
- context.fillRect(0, 0, stage.width, stage.height);
- }
- function drawApple() {
- context.fillStyle = "red";
- context.fillRect(appleX * lenghtPiece, appleY * lenghtPiece, lenghtPiece, lenghtPiece);
- }
- function drawSnake() {
- context.fillStyle = "gray";
- for (var i = 0; i < trail.length; i++) {
- context.fillRect(trail[i].x * lenghtPiece, trail[i].y * lenghtPiece, lenghtPiece - 1, lenghtPiece - 1);
- if (trail[i].x == startPointX && trail[i].y == startPointY) {
- gameOver();
- }
- }
- trail.push({ x: startPointX, y: startPointY });
- while (trail.length > tail) {
- trail.shift();
- }
- }
- function eat() {
- if (appleX == startPointX && appleY == startPointY) {
- tail++;
- generateApple();
- }
- }
- function generateApple() {
- appleX = Math.floor(Math.random() * tileCount);
- appleY = Math.floor(Math.random() * tileCount);
- }
- function move() {
- startPointX += speedX;
- startPointY += speedY;
- }
- function teleportPosition() {
- if (startPointX < 0) {
- startPointX = tileCount - 1;
- }
- if (startPointX > tileCount - 1) {
- startPointX = 0;
- }
- if (startPointY < 0) {
- startPointY = tileCount - 1;
- }
- if (startPointY > tileCount - 1) {
- startPointY = 0;
- }
- }
- function gameOver() {
- speedX = speedY = 0;
- tail = 5;
- }
- function keyPush(event) {
- switch (event.keyCode) {
- case 37: // Left
- speedX = -vel;
- speedY = 0;
- break;
- case 38: // up
- speedX = 0;
- speedY = -vel;
- break;
- case 39: // right
- speedX = vel;
- speedY = 0;
- break;
- case 40: // down
- speedX = 0;
- speedY = vel;
- break;
- default:
- break;
- }
- }
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement