Facebook
From novice, 4 Years ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 95
  1. //index keeps track of boxes index which can help us move and manipulate the grid
  2. let index = 0;
  3. //box class creates box objects which have the properties of x postion ,y postion , state ,previousState and index
  4. //index helps us find new boxes
  5. //box has a method called changeState() which takes in 3 possible states^ : "snk","mpt","pnt" .
  6. // "note : the changeState() method can take in other states and will not result in an error
  7. // ,but will cause rendering and logic issues in the game"
  8. // states pnt for point, mpt for empty  , snk for snake.
  9. //the method changes the previousState to the current state and then changes the current state to the state we specifed
  10. //each box has an unique index which we can use to axcess it
  11. class box {
  12.   constructor(x,y,stt){
  13.     this.x = x;
  14.     this.y = y;
  15.     this.state = stt;
  16.     this.previousState = null;
  17.     this.index = index;
  18.     index++;
  19.   }
  20.   changeState(stt){
  21.   this.previousState = this.state;
  22.   this.state= stt;
  23.   }
  24. }
  25.  
  26. //the game object keeps track of the ingame grid ,if there is a point present in the game,
  27. //if the game has been lost  
  28.  
  29. const game = {
  30. grid : [],
  31. haslost : false,
  32. hasPoint : true,
  33. points : 0,
  34. }
  35. //snake object
  36.  
  37. //directions "p","l","d","r"
  38.  
  39. function findBox (box,dir){
  40.     if(dir == "p") return game.grid[box.index-9];
  41.     if(dir =="l") return game.grid[box.index-1];
  42.     if(dir == "d") return game.grid[box.index+9];
  43.     if(dir =="r") return game.grid[box.index+1];
  44.   return null;
  45. }
  46.  
  47.  
  48. const snake = {
  49.   headbox: {},
  50.   tailbox: {},
  51.   boxes: [],
  52.   previousMove : null,
  53.   move:function (dir) {
  54.     if(game.haslost) return 0;
  55.   //find the new box
  56.     let temp = findBox(this.headbox,dir);
  57.     if (temp == null) return 0;
  58.     if(temp === undefined) game.haslost = true;
  59.     let tempCord = temp.y;
  60.     if(dir == "l")tempCord++;
  61.     else tempCord--;
  62.     if(tempCord > 8 || tempCord < 0 && (dir == "l" || dir == "r"))  game.haslost = true;
  63.    if(temp.state == "snk") game.haslost = true;
  64.     temp.changeState("snk");
  65.   //add it to boxes
  66.     this.boxes.push(temp);
  67.   //change the headbox
  68.     this.headbox = temp;
  69.   //set tailbox
  70.     this.tailbox.changeState("mpt");
  71.     this.boxes.shift();
  72.     this.tailbox = this.boxes[0];
  73.     this.previousMove = dir;
  74.   }
  75.   ,
  76.   eat: function () {
  77.   if(this.headbox.previousState == "pnt"){
  78.     game.hasPoint = false;
  79.     game.points++;
  80.   //find new tailbox in opposite direction
  81.     let oppositeDir;
  82.       if(this.previousMove === "p") oppositeDir = "d";
  83.       if(this.previousMove === "l") oppositeDir = "r";
  84.       if(this.previousMove === "d") oppositeDir = "p";
  85.       if(this.previousMove === "r") oppositeDir = "l";
  86.     let temp = findBox(this.tailbox,oppositeDir);
  87.   //change state & push it into boxes
  88.     temp.changeState("snk");
  89.     this.boxes.unshift(temp);
  90.   // update tailbox
  91.     this.tailbox = temp;
  92.   }
  93.  }
  94. }
  95.  
  96. function start() {
  97.  
  98. let randX;
  99. let randY;
  100.  
  101. do{
  102. randX = Math.floor(Math.random()*9);
  103. randY = Math.floor(Math.random()*9);
  104. }while(randX == 4 && randY == 4)
  105.  
  106. for(let i = 0; i < 9; i++){
  107.   for(let j = 0 ; j  < 9 ; j++){
  108.     let tempbox;
  109.     if(i == 4 && j == 4){
  110.       tempbox = new box(j,i,"snk");
  111.       snake.headbox = tempbox;
  112.       snake.tailbox = tempbox;
  113.       snake.boxes.push(tempbox);
  114.     }else if ( i == randX && j == randY){
  115.       tempbox = new box(j,i,"pnt");
  116.       game.hasPoint = true;
  117.     }else{
  118.        tempbox = new box(i,j,"mpt");
  119.     }
  120.     game.grid.push(tempbox);
  121.   }
  122. }
  123. }
  124.  
  125.  
  126. function generatePoint(){
  127. let randIndex;
  128.  
  129. do randIndex = Math.floor(Math.random()*80);
  130.  
  131. while(game.grid[randIndex].state == "snk");
  132.  
  133. game.hasPoint = true;
  134. game.grid[randIndex].changeState("pnt");
  135. }
  136.  
  137. start();
  138. //logic rendering
  139.  
  140. //setup createsCanvas which will be rendered to
  141. function setup() {
  142. createCanvas(445,445);
  143. }
  144. //currentDirection is the direction the snake is moving and the nextDirectoin will be
  145. //the direction where the snake will go.
  146. let currentDirection = null;
  147. let nextDirection = null;
  148. //keyTyped() function handles the input/output of the game.It detects when a key is pressed
  149. //and checks if the key was ether a,d,w or s and it also checks what is the current direction.
  150. //If the current direction isn't the opposite of the next direction ,the next direction gets set to the
  151. //the coresponding direction
  152. function keyTyped() {
  153.   if (key === "a" && currentDirection != "r") nextDirection = "l";
  154.   else if (key === "d" &&currentDirection!= "l") nextDirection = "r";
  155.   else if (key === "w" &&currentDirection!= "d") nextDirection = "p";
  156.   else if (key === "s" &&currentDirection!= "p") nextDirection = "d";
  157. }
  158.   //wait time is time between each uptade in the game it will either be 300 or 1000 milliseconds
  159.  let waitTime = 300;
  160.  //setInterval waits for waitTime miliseconds then updates the snakes postion ,makes the snake
  161.  //eat and updates the direction
  162.  
  163.   setInterval(() => {
  164.     currentDirection = nextDirection;
  165.     snake.eat();
  166.     snake.move(nextDirection);
  167.   }, waitTime);
  168. //draw()^ handles the rendering of the game and a few of its logical components
  169. //"note:the draw function is in an infinte loop"
  170. function draw() {
  171.   // we initlize wait time to 300 ms
  172.   waitTime = 300;
  173.   //if the snakes head is at the edge of the grid^ we set the wait time to 1000 ms so that the player has more time to evade loss
  174.   //"note: we can tell wether or not if the player is at the edge by looking at the x and y cordinates of the snakes head.
  175.   //if we at least one of the cordinates is 8 or 0 we know that the
  176.   //head is at the edge since we are using a 9 by 9 grid (keep in mind that indexing both in the y and the x direction begins at 0)"
  177.  
  178.   if(snake.headbox.x == 8 || snake.headbox.x == 0 || snake.headbox.y == 8 || snake.headbox.y == 0) waitTime = 1000;
  179.   // if the game objects has lost property has been set to true we alret the user
  180.   if(game.haslost == true) alert('waage');
  181.   // if there are no new points in the grid we create one
  182.   if(game.hasPoint == false) generatePoint();
  183.   // we clear the screen of the prevous frame
  184.   background(155,122,33);
  185.   // counter helps us keep tract of which box we are rendering
  186.   let counter = 0;
  187.   //we use a nested loop itirate over each one of the grids elemnts in a way that we can have an easy time
  188.   //get the cordinates of the boxes which will match the i and j iterators  
  189.   for(let i = 0; i < 9; i++){
  190.    for(let j = 0; j < 9; j++){
  191.      //nostroke() stops the game from making strokes
  192.        noStroke();
  193.        //c by default will be 255 but will change if the boxes state is ethier "snk" or "pnt"
  194.        let c = color(255)
  195.        if(game.grid[counter].state == "snk") c = color(99,205,11);
  196.        if(game.grid[counter].state == "pnt") c = color(153,23,144);
  197.        fill(c);
  198.        //calucaltes the rectangles postion and draws it
  199.        rect(5+j*45,5+i*45,45,45);
  200.        //update the counter so that we can keep trac of things
  201.        counter++;
  202.       }
  203.     }
  204. }