Advertisement
Transformator

snake

Mar 30th, 2015
1,091
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE HTML>
  2. <head>
  3.     <meta charset="utf-8">
  4.     <title>Snake</title>
  5.  
  6.     <style>
  7.     canvas {
  8.         margin: auto;
  9.         position: absolute;
  10.  
  11.         top: 0;
  12.         bottom: 0;
  13.         left: 0;
  14.         right: 0;
  15.  
  16.         border: 2px solid black;
  17.     }
  18.     </style>
  19. </head>
  20.  
  21. <body>
  22. <script>
  23.  
  24. // width and height of canvas
  25. var WIDTH = 800;
  26. var HEIGHT = 600;
  27.  
  28. // the width of every block
  29. var SECTION = 20;
  30.  
  31. // the speed (milliseconds between the frames)
  32. var SPEED = 125;
  33.  
  34. // how many segments the player starts with
  35. var SEGMENTS = 5;
  36.  
  37. // creating global variables, where ever they needed
  38. var canvas, ctx, keystate, runid, applecounter, bannanacounter, pause, cooldown;
  39.  
  40. // Key-Codes of used keys
  41. var UpArrow=38, DownArrow=40, RightArrow=39, LeftArrow=37, WKey=87, SKey=83, AKey=65, DKey=68, ESC=27;
  42.  
  43. ////////////////////////////// GAME
  44.  
  45. // all stuff about the player
  46. var player = {
  47.     // x position of player (*20 = pixels for canvas)
  48.     x: null,
  49.     // y position of player (*20 = pixels for canvas)
  50.     y: null,
  51.     // the velority (where the player looks to)
  52.     // 4 = up | 3 = right | 2 = down | 1 = left
  53.     vel: null,
  54.     // count of elements added to snake
  55.     addelement: 0,
  56.  
  57.     // array of all segments the player has
  58.     segs: [],
  59.  
  60.     // function, executed every new frame (before draw function)
  61.     update: function() {
  62.         // if the "up" key or the "w" key pressed, and the player is not going down
  63.         if(keystate[UpArrow] && this.vel != 2 || keystate[WKey] && this.vel != 2)
  64.             // setting velority
  65.             this.vel = 4;
  66.         // if the "right" key or the "d" key pressed, and the player is not going left
  67.         if(keystate[RightArrow] && this.vel != 1 || keystate[DKey] && this.vel != 1)
  68.             // setting velority
  69.             this.vel = 3;
  70.         // if the "down" key or the "s" key pressed, and the player is not going up
  71.         if(keystate[DownArrow] && this.vel != 4 || keystate[SKey] && this.vel != 4)
  72.             // setting velority
  73.             this.vel = 2;
  74.         // if the "left" key or the "a" key pressed, and the player is not going right
  75.         if(keystate[LeftArrow] && this.vel != 3 || keystate[AKey] && this.vel != 3)
  76.             // setting velority
  77.             this.vel = 1;
  78.  
  79.         // reset the array for all pressed keys
  80.         keystate = {};
  81.  
  82.         // adding the acctual player position to segs array (in the end of the array)
  83.         this.segs.unshift([player.x, player.y]);
  84.  
  85.         // if no segment is added this frame
  86.         if(!this.addelement > 0)
  87.             // deleting last part of snake
  88.             this.segs.pop();
  89.         // if a segment is added this frame
  90.         else
  91.             // counting addelement down
  92.             this.addelement--;
  93.  
  94.         // if the velority is 1 (left)
  95.         if(this.vel == 1)
  96.             // counting the player-x down
  97.             player.x -= 1;
  98.         // if the velority is 2 (down)
  99.         if(this.vel == 2)
  100.             // counting the player-y up
  101.             player.y += 1;
  102.         // if the velority is 3 (right)
  103.         if(this.vel == 3)
  104.             // counting the player-x up
  105.             player.x += 1;
  106.         // if the velority is 4 (up)
  107.         if(this.vel == 4)
  108.             // counting the player-y down
  109.             player.y -= 1;
  110.  
  111.         // for every segment the player has
  112.         for(var i=0; i<this.segs.length; i++) {
  113.             // if it equals the player position the player loses
  114.             if(this.segs[i][0] == player.x && this.segs[i][1] == player.y)
  115.                 // executing lose function
  116.                 lose();
  117.         }
  118.  
  119.         // if the player hits upper or left rim
  120.         if(this.x < 0 || this.y < 0)
  121.             // executing lose function
  122.             lose();
  123.         // if the player hits right or bottom rim
  124.         if(this.x > WIDTH/SECTION-1 || this.y > HEIGHT/SECTION-1)
  125.             // executing lose function
  126.             lose();
  127.     },
  128.     // function, executed every new frame (after update function)
  129.     // draws the player to the canvas
  130.     draw: function() {
  131.         // setting color to darkgreen
  132.         ctx.fillStyle = "#050";
  133.         // drawing the snakes head
  134.         ctx.fillRect(this.x*20, this.y*20, SECTION, SECTION);
  135.  
  136.         // setting color to lightgreen
  137.         ctx.fillStyle = "#0F0";
  138.         // for each segment the snake has
  139.         for(var i=0; i<this.segs.length; i++) {
  140.             // drawing the snake
  141.             ctx.fillRect(this.segs[i][0]*20, this.segs[i][1]*20, SECTION, SECTION);
  142.         }
  143.     }
  144. }
  145.  
  146. // all stuff about the random spawned food (apples)
  147. var apples = {
  148.     // list of all existing apples
  149.     list: [],
  150.  
  151.     // function, executed every new frame (before draw function)
  152.     update: function() {
  153.         // for every existing apple (or deleted)
  154.         for(var j=0; j<this.list.length; j++) {
  155.             // if the apple has the same position as the player head (and if its not "undefined")
  156.             if(this.list[j] != undefined && this.list[j][0] == player.x && this.list[j][1] == player.y) {
  157.                 // set this segment to "undefined"
  158.                 delete this.list[j];
  159.  
  160.                 // say the script, that the player has one more segment
  161.                 player.addelement++;
  162.                 // counts score one up
  163.                 score.points++;
  164.             }
  165.         }
  166.     },
  167.     // function, executed every new frame (after update function)
  168.     // draws the apples to the canvas
  169.     draw: function() {
  170.         // for every existing apple (or deleted)
  171.         for(var i=0; i<this.list.length; i++) {
  172.             // if this apple is not "undefined" (deleted)
  173.             if(this.list[i] != undefined) {
  174.                 // setting color to lightred
  175.                 ctx.fillStyle = "#F00";
  176.                 // drawing the apple
  177.                 ctx.fillRect(this.list[i][0]*20, this.list[i][1]*20, SECTION, SECTION);
  178.             }
  179.         }
  180.     }
  181. };
  182.  
  183. // all stuff about the random spawned food (bannanas)
  184. var bannanas = {
  185.     // list of all existing bannanas
  186.     list: [],
  187.  
  188.     // function, executed every new frame (before draw function)
  189.     update: function() {
  190.         // for every existing bannana (or deleted)
  191.         for(var j=0; j<this.list.length; j++) {
  192.             // if the bannana has the same position as the player head (and if its not "undefined")
  193.             if(this.list[j] != undefined && this.list[j][0] == player.x && this.list[j][1] == player.y) {
  194.                 // set this segment to "undefined"
  195.                 delete this.list[j];
  196.  
  197.                 // say the script, that the player has two more segments
  198.                 player.addelement += 2;
  199.                 // counts score two up
  200.                 score.points += 2;
  201.             }
  202.         }
  203.     },
  204.     // function, executed every new frame (after update function)
  205.     // draws the bannanas to the canvas
  206.     draw: function() {
  207.         // for every existing bannana (or deleted)
  208.         for(var i=0; i<this.list.length; i++) {
  209.             // if this apple is not "undefined" (deleted)
  210.             if(this.list[i] != undefined) {
  211.                 // setting color to yellow
  212.                 ctx.fillStyle = "#FF0";
  213.                 // drawing the bannana
  214.                 ctx.fillRect(this.list[i][0]*20, this.list[i][1]*20, SECTION, SECTION);
  215.             }
  216.         }
  217.     }
  218. };
  219.  
  220. // all stuff which has to do with the score
  221. var score = {
  222.     // amound of points the player has in the moment
  223.     points: 0,
  224.  
  225.     // function, executed every new frame
  226.     // draws the score to the canvas
  227.     draw: function() {
  228.         // setting color to white
  229.         ctx.fillStyle = "#FFF";
  230.         // setting font style to "20px Calibri"
  231.         ctx.font = '20pt Calibri';
  232.  
  233.         // drawing the score on the canvas
  234.         ctx.fillText("Score: " + this.points, 5, 20);
  235.         // drawing the highscore on the canvas (which is saved in the "localStorage")
  236.         ctx.fillText("Highscore: " + localStorage.getItem("highscore"), WIDTH-175, 20);
  237.     },
  238.     // function, executed if the player dies.
  239.     // if the score of this round is a highscore, the highscore get saved.
  240.     setHighscore: function() {
  241.         // if there is no highscore now
  242.         if(localStorage.getItem("highscore") == null)
  243.             // setting highscore to 0
  244.             localStorage.setItem("highscore", 0);
  245.         // if this game was a highscore
  246.         if(this.points > localStorage.getItem("highscore"))
  247.             // setting new highscore
  248.             localStorage.setItem("highscore", this.points);
  249.     }
  250. };
  251.  
  252. // main function, does all the control stuff. mother of all coming functions
  253. function main() {
  254.     // creates the canvas
  255.     canvas = document.createElement("canvas");
  256.     // set it's width
  257.     canvas.width = WIDTH;
  258.     // set it's height
  259.     canvas.height = HEIGHT;
  260.     // getting the ctx from canvas (to make editing possible)
  261.     ctx = canvas.getContext("2d");
  262.     // adding canvas to html-body
  263.     document.body.appendChild(canvas);
  264.  
  265.     // running init function
  266.     init();
  267.  
  268.     // if a key is pressed down
  269.     document.addEventListener("keydown", function(evt) {
  270.         // saving all pressed keys in keystate-array
  271.         keystate[evt.keyCode] = true;
  272.     });
  273.  
  274.     // function, executed every frame
  275.     var loop = function() {
  276.         // if there is a cooldown for pause-menu
  277.         if(cooldown > 0)
  278.             // counting cooldown one down
  279.             cooldown--;
  280.  
  281.         // if ESC pressed and there is no cooldown
  282.         if(keystate[ESC] && cooldown <= 0) {
  283.             // reseting all pressed keys
  284.             keystate = {};
  285.  
  286.             // if pause, continueing game
  287.             if(pause) {
  288.                 // setting pause to false
  289.                 pause = false;
  290.                 // adding cooldown for pause menu
  291.                 cooldown = 3;
  292.             // if game is running (not in pause menu)
  293.             } else {
  294.                 // setting pause to true
  295.                 pause = true;
  296.                 // adding cooldown for pause menu
  297.                 cooldown = 3;
  298.             }
  299.         }
  300.  
  301.         // if game is running (no pause)
  302.         if(!pause) {
  303.             // updating everything
  304.             update();
  305.             // drawing everything to canvas
  306.             draw();
  307.  
  308.             // every 25 frame spawning an apple
  309.             if(applecounter > 25) {
  310.                 spawanfood("apple");
  311.                 // reseting counter
  312.                 applecounter = 0;
  313.             }
  314.             // every 50 frame spawning an banana
  315.             if(bannanacounter > 50) {
  316.                 spawanfood("banana");
  317.                 // reseting counter
  318.                 bannanacounter = 0;
  319.             }
  320.  
  321.             // counting counter one up
  322.             applecounter++;
  323.             bannanacounter++;
  324.         // if game not running (pause)
  325.         } else {
  326.             // draw to canvas
  327.             draw();
  328.  
  329.             // adding an "PAUSE" to canvas (in the middle)
  330.  
  331.             // setting color to red
  332.             ctx.fillStyle = "#F00";
  333.             // setting font to "60px Calibri"
  334.             ctx.font = '60pt Calibri';
  335.             // drawing text to canvas
  336.             ctx.fillText("PAUSE", WIDTH/2-100, HEIGHT/2);
  337.         }
  338.     }
  339.     // setting interval for loop function (saving interval id to "runid")
  340.     runid = setInterval(loop, SPEED);
  341. }
  342.  
  343. // this function initinates the game
  344. // setting all standard values and so on
  345. function init() {
  346.     // creating variable which saves all pressed keys
  347.     keystate = {};
  348.  
  349.     // setting applecounter and bananacounter to standard values
  350.     applecounter = 0;
  351.     bannanacounter = 0
  352.  
  353.     // disable the pause menu
  354.     pause = false;
  355.  
  356.     // disable cooldown
  357.     cooldown = 0;
  358.  
  359.     // setting players position somewere in the middle
  360.     player.x = WIDTH / SECTION / 2;
  361.     player.y = HEIGHT / SECTION / 2;
  362.  
  363.     // player starts going to the right
  364.     player.vel = 3;
  365.  
  366.     // for every segment the player starts with
  367.     for(var i=1; i<SEGMENTS+1; i++) {
  368.         // adding segment to list
  369.         player.segs.push([player.x-i, player.y]);
  370.     }
  371. }
  372.  
  373. // this function updates everything every new frame
  374. function update() {
  375.     player.update();
  376.     apples.update();
  377.     bannanas.update();     
  378. }
  379.  
  380. // this function draws everything to the canvas (every new frame)
  381. function draw() {
  382.     // if the game is running
  383.     if(runid) {
  384.         // setting color to black
  385.         ctx.fillStyle = "#000";
  386.         // drawing the background
  387.         ctx.fillRect(0, 0, WIDTH, HEIGHT);
  388.  
  389.         // run all draw functions
  390.         player.draw();
  391.         apples.draw();
  392.         bannanas.draw();
  393.         score.draw();
  394.     }
  395. }
  396.  
  397. // spawns new food at random position
  398. function spawanfood(what) {
  399.     // creates new random position
  400.     var getPosition = function() {
  401.         // creates random x
  402.         var xpos = Math.floor(Math.random() * WIDTH / SECTION);
  403.         // creates random y
  404.         var ypos = Math.floor(Math.random() * HEIGHT / SECTION);
  405.  
  406.         // returning both as array
  407.         return [xpos, ypos];
  408.     }
  409.  
  410.     // helperfunction, does the rest
  411.     var insertFood = function() {
  412.         // setting run to true
  413.         var run = true;
  414.         // getting new position
  415.         var pos = getPosition();
  416.  
  417.         // for every segment of the snake
  418.         for(var i=0; i<player.segs.length; i++) {
  419.             // if this position is occupied, don't run
  420.             if(pos[0] == player.segs[i][0] && pos[1] == player.segs[i][0])
  421.                 run = false;
  422.         }
  423.         // for every existing apple (or deleted)
  424.         for(var i=0; i<apples.list.length; i++) {
  425.             // if this position is occupied, don't run
  426.             if(apples.list[i] != undefined && pos[0] == apples.list[i][0] && pos[1] == apples.list[i][0])
  427.                 run = false;
  428.         }
  429.         // for every existing banana (or deleted)
  430.         for(var i=0; i<bannanas.list.length; i++) {
  431.             // if this position is occupied, don't run
  432.             if(bannanas.list[i] != undefined && pos[0] == bannanas.list[i][0] && pos[1] == bannanas.list[i][0])
  433.                 run = false;
  434.         }
  435.  
  436.         // if everything gone well
  437.         if(run) {
  438.             // spawn ether apple or banana
  439.             if(what=="apple")
  440.                 apples.list.push([pos[0], pos[1]]);
  441.             if(what=="banana")
  442.                 bannanas.list.push([pos[0], pos[1]]);
  443.         // if this position is occupied, try again
  444.         } else
  445.             insertFood();
  446.     }
  447.     // running helperfunction
  448.     insertFood();
  449. }
  450.  
  451. // function, executed if the player loses
  452. function lose() {
  453.     // clearing interval for loop function
  454.     clearInterval(runid);
  455.     // disable run (don't draw this frame)
  456.     runid = false;
  457.  
  458.     // setting color to red
  459.     ctx.fillStyle = "#F00";
  460.     // setting font to "60px Calibri"
  461.     ctx.font = '60pt Calibri';
  462.     // drawing text
  463.     ctx.fillText("YOU LOSE", WIDTH/2-160, HEIGHT/2);
  464.  
  465.     // if this was a highscore, save it
  466.     score.setHighscore();
  467. }
  468.  
  469. // running that all
  470. main();
  471.  
  472. </script>
  473. </body>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement