Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>Pastime</title>
- </head>
- <body>
- <canvas id="canvas">This text is displaying if your browser is unable to display HTML5 canvas.</canvas>
- </body>
- <style>
- *
- {
- margin: 0;
- padding: 0;
- }
- body, html
- {
- overflow: hidden;
- }
- #canvas
- {
- position: absolute;
- width: 100%;
- height: 100%;
- border: 3px solid red;
- }
- </style>
- <script>
- var Box = function(x, y, direction)
- {
- this.x = x;
- this.y = y;
- this.direction = direction;
- }
- var canvas = document.getElementById("canvas");
- var ctx = canvas.getContext("2d");
- var snake = [];
- var head = new Box(100, 100, -1);
- ctx.fillStyle = "red";
- snake.push(head);
- //addBox();
- //addBox();
- //addBox();
- Box.prototype.draw = function()
- {
- ctx.fillRect(this.x, this.y, 20, 20);
- }
- function drawSnake()
- {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- for (var i = 0; i < snake.length; i++)
- {
- switch (snake[i].direction)
- {
- case 0:
- snake[i].x -= 20;
- break;
- case 1:
- snake[i].y -= 20;
- break;
- case 2:
- snake[i].x += 20;
- break;
- case 3:
- snake[i].y += 20;
- break;
- }
- snake[i].draw();
- }
- }
- function addBox()
- {
- var lastBox = snake[snake.length - 1];
- var direction = lastBox.direction;
- var x, y;
- switch (direction)
- {
- case 0:
- x = lastBox.x + 20;
- y = lastBox.y;
- break;
- case 1:
- x = lastBox.x;
- y = lastBox.y + 20;
- break;
- case 2:
- x = lastBox.x - 20;
- y = lastBox.y;
- break;
- case 3:
- x = lastBox.x;
- y = lastBox.y - 20;
- break;
- }
- snake.push(new Box(x, y, direction));
- }
- document.addEventListener("keydown", function (event)
- {
- switch (event.keyCode)
- {
- case 37:
- head.direction = 0;
- break;
- case 38:
- head.direction = 1;
- break;
- case 39:
- head.direction = 2;
- break;
- case 40:
- head.direction = 3;
- break;
- }
- }, false);
- function gameLoop()
- {
- setTimeout("gameLoop()", 100);
- drawSnake();
- }
- gameLoop();
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement