Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>Snake</title>
- <!-- the follwing line of code optimizes for mobile screens -->
- <meta name="viewport" content="width=device-width, user-scalable=no">
- <style>
- button {
- background-color: #4CAF50; /* Green */
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- }
- </style>
- </head>
- <body>
- <h1>Snake</h1>
- <canvas id="gc" width="256" height="256"></canvas>
- <div style="text-align: center; margin: 10px; width: 300px">
- <button onclick="moveUp()">UP</button>
- <br>
- <button onclick="moveLeft()">LEFT</button>
- <button onclick="moveRight()">RIGHT</button>
- <br>
- <button onclick="moveDown()">DOWN</button>
- </div>
- </body>
- <script src="/script.js" defer></script>
- </html>
- <script>
- window.onload=function() {
- canvas=document.getElementById("gc");
- context=canvas.getContext("2d");
- document.addEventListener("keydown",keyPush);
- frameRate = 1000/15; // 15 frames per second (in milliseconds)
- setInterval(game, frameRate);
- }
- const KEY_LEFT = 37;
- const KEY_UP = 38;
- const KEY_RIGHT = 39;
- const KEY_DOWN = 40;
- // var px,py,gs,tc,ax,ay,xv,yv,trail,tail;
- px=py=10; // player
- gs=tc=16; // 16 by 16 // game size // tile count
- ax=ay=15; // apple
- xv=yv=0;
- trail = [];
- tail = 5;
- function game() {
- px+=xv;
- py+=yv;
- // wrap
- if (px<0) {
- px=tc-1;
- }
- if (px>tc-1) {
- px=0;
- }
- if (py<0) {
- py=tc-1;
- }
- if (py>tc-1) {
- py=0;
- }
- context.fillStyle="black";
- context.fillRect(0,0,canvas.width,canvas.height);
- context.fillStyle="lime";
- for(var i=0; i<trail.length; i++) {
- x = trail[i].x;
- y = trail[i].y;
- context.fillRect(x*gs, y*gs, gs-2, gs-2);
- if (x == px && y == py) {
- tail = 5;
- }
- }
- var new_trail_element = new Object();
- new_trail_element.x = px;
- new_trail_element.y = py;
- trail.push(new_trail_element);
- while (trail.length > tail) {
- trail.shift(); // ???
- }
- if (px == ax && py == ay) {
- tail++;
- ax=Math.floor(Math.random()*tc);
- ay=Math.floor(Math.random()*tc);
- }
- context.fillStyle="red";
- context.fillRect(ax*gs, ay*gs, gs-2, gs-2);
- }
- function keyPush(event) {
- if (event.keyCode == KEY_LEFT) {
- moveLeft();
- }
- else if (event.keyCode == KEY_UP) {
- moveUp();
- }
- else if (event.keyCode == KEY_RIGHT) {
- moveRight();
- }
- else if (event.keyCode == KEY_DOWN) {
- moveDown();
- }
- else {
- // do nothing
- }
- }
- function moveUp() {
- xv=0;yv=-1; // remember that 0,0 is top left
- }
- function moveLeft() {
- xv=-1;yv=0;
- }
- function moveRight() {
- xv=1;yv=0;
- }
- function moveDown() {
- xv=0;yv=1;
- }
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement