70 Snake - JcerelusDev/CanvasGameJs GitHub Wiki

Snake class. && Food class

They are useful if ever you want to create old snake game with no effort at all.

Snake(x,y,cellSize,color)
Food(cellSize,color )

let snake= new Snake(20,200,10,"green")
let food = new Food(10,"red") // 10 is the size of the food

If you want to use image for food it has boolean (useImage) set to false by default , but you can set it to true as follow :

let food = new Food(10)
food.useImage = true
food.image.src="apple.png"

Important

Snake and food has an update and draw method and the food has a generateFood method attach to it.

To move the snake

You have a built-in .dir method to control the direction of the snake.

CollidedFood

It is used to check collision between the snake and the food.

for(let snb of snake.body)
if(collidedFood(snb,food)){
// do something
}

how do we know the player lost

The snake class has lost boolean method that is set to false at start, but you can set it to true if snake is collided with the game border or itself. Then stop the game with the method stopAnimation

A huge code base :

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0">
<style type="text/css">
body{
background:darkslategrey;
}

button{
color:white;
}


</style>
</head>
<body>

<script src="https://cdn.jsdelivr.net/gh/JcerelusDev/canvas00/Js/canvas.min.js"></script>
<script src="uicontrol.js"></script>
<script type="text/javascript">

const game = new Stage()
      game.add(game.stage)
      game.setSize(400,400)
      game.setAnimation(12)
      
    
let snake= new Snake(20,200,10,"green")


let food = new Food(10,"red")
  // food.useImage = true
   //food.image.src="apple.png"
    

//handle eaten food
function eatFood(){
 for(let sb of snake.body){
 if(collidedFood(sb,food)){
  food.generateFood()
   const tail = [...snake.body,snake.body[snake.body.length-1]]//snake.body[snake.body.length - 1];
   snake.body.push({x: tail.x, y: tail.y });

 }
 
 }

}


//handle game over

function GameOver(){
 if(snake.lost){
  game.stopAnimation()
  
  setTimeout(()=>{
  location.reload()
  },1500)
  
 }

}


//move snake
function moveSnake(){
  //handle direction
if (leftPress && snake.dir.x!=1 ) {
     snake.dir = { x: -1, y: 0 };
  } else if (rightPress && snake.dir.x!=-1) {
       snake.dir = { x: 1, y: 0 };
  } else if (upPress && snake.dir.y!=1) {
    snake.dir = { x: 0, y: -1 };
  } else if (downPress && snake.dir.y!= -1) {
     snake.dir = { x: 0, y: 1 };
  }

}
      
      game.update = function(){
        
        snake.update()
        food.update()
        moveSnake()
        eatFood()
       
       GameOver()
      
      }
      
      game.render = function(){
         snake.draw()
         food.draw()
         
      }






</script>
</body>
</html>
⚠️ **GitHub.com Fallback** ⚠️