Making Snake Game Using HTML 5 SVG With PabloJs (Part-2)

in utopian-io •  6 years ago 

Untitled-1.fw.png

Repository

PabloJs

My GitHub Profile

Making Snake Game Using HTML 5 SVG With PabloJs (Part-2)

What Will I Learn?

  • You will learn how to build games using HTML5 SVG.
  • You will learn to create svg objects more easily using Pablojs.
  • You will learn to reach the boundaries of the playing field and touch the tail of the snake.
  • You will learn how to close the page's scroll property
  • You will learn clearInterval() in javascript.
  • You will learn the structure of the nested function.
  • You will learn confirm() function in javascript.

Requirements

Visual Studio Code in GitHub

Difficulty

  • Basic

Tutorial Contents

In my previous article we set the snake movement and snake was moving with the keyboard.

In this article I will adjust the food of the snake and determine the limits of the game field also I will end the game when the snake hits itself.

I will divide the article into 3 parts for a better understanding of the topic:

  • Eat Food
  • Playground Borders
  • Hit Itself

First of all, we need to close the scroll direction of keyboard direction keys.

We can change css overflow properties to close it.

Let's create a style.css file and change the style of the body.

body { 
  overflow:-moz-scrollbars-vertical; 
  overflow-x:hidden; 
  overflow:-moz-scrollbars-vertical; 
  overflow-y:hidden;
}



When we load this style.css page in index.html, we close the page's scroll property.

Eat Food

We were building the movement of the snake in a function.

I will define two functions to create food on the playground and eat this food. First create the food creation function.

Snake nodes formed in 15px squares and snake 15 and multiple coordinates are moving in the coordinates.

I will create the food using the rect() function and prepare the x and y coordinates as a random value of 15 and multiples thus, foods will be created in the areas within the movement of the snake.

var food;
var foodX;//x coordinate of the food
var foodY;//y coordinate of the food

function foodBuilder(){

      foodX=(Math.floor(Math.random() * 67) + 1)*15;//15 and multiples of values between 1100px and 0px
      foodY=(Math.floor(Math.random() * 45) + 1)*15;//15 and multiples of values between 700px and 0px

      var food=svg.rect({
          x:foodX, y:foodY,
          width:nodeSize, height:nodeSize,
          fill:  '#2345f6',
          stroke:'#006',
          'stroke-width': 2,
          'stroke-linejoin': 'round'
      });


      return food;
}



The reason we return the function of the rectangle we created here, because the snake ate this food in the future, we need to remove the food.

Now you can use this function to create food in the playground.

Screenshot 1

jquery1.JPG


Now let's write another function that we will feed these food to the snake.

In this function, we should check whether the x and y coordinates of the snake are equal to the x and y coordinates of the food.

After eating the snake, we must re-create food elsewhere on the playing field.

I will provide the eat food control with the help of a variable. Let’s create a variable for this.

var foodControl=1;



When this variable is equal to 1, the food found in the environment is defeated by the snake side and we must remove the rectangle of the food and create food again.

function snakeEat(){

  if(foodControl==1)
  {

    food=foodBuilder();
    foodControl=0;// food in the playground
    foodX=food.attr('x');
    foodY=food.attr('y');

  }
}



In this function, we will control the coordinates of the snake at the beginning rect equal of the food coordinates.

For this, we need to access the coordinates of the last element of the arrayNode array that contains the snake.

function snakeEat(){
…
  snakeX=arrayNode[arrayNode.length-1].attr('x');
  snakeY=arrayNode[arrayNode.length-1].attr('y');

    if(snakeX==foodX && snakeY==foodY)
        {
        // events that will occur when the snake eats food
}
}



Here is the first thing we need to do is remove the food and make the foodControl variable 1.

Thus, when this function is running again, control will be provided to create food elsewhere.

Later, it must grow because it eats food.

Since we store the nodes of our snake in a series, we can easily add nodes and remove nodes.

To add a knot to a snake, all we have to do is to create a random color rectangle and add this rectangle to the nodeArray array and we must increase the variable we hold the nodes of the snakes.

Here's the full function of snakeEat()

function snakeEat(){

  if(foodControl==1)
  {

    food=foodBuilder();
    foodControl=0;//food in the playground
    foodX=food.attr('x');
    foodY=food.attr('y');

  }

  snakeX=arrayNode[arrayNode.length-1].attr('x');
  snakeY=arrayNode[arrayNode.length-1].attr('y');

    if(snakeX==foodX && snakeY==foodY)
    {
      food.remove();
      foodControl=1;

      var snakeNode=svg.rect({
          x:snakeX, y:snakeY,
          width:nodeSize, height:nodeSize,
          fill:  arrayColor[colorIndex],
          stroke:'#006',
          'stroke-width': 2,
          'stroke-linejoin': 'round'
      });

      arrayNode.push(snakeNode);
      snakeNode=snakeNode+1;

    }
}



We must call this function in the setInterval so that we can check the status of the food each time the snake moves.

intervalValue=setInterval(function(){

snakeEat();
snakeMove();

}, speed);


Screenshot 2

ezgif1.gif

Playground Borders

We must define our game within certain limits. The game must end if the snake hits these limits.

We have created the game fields when create svg object and I set height 690px, width 1095px.

I'll define the slamming of the snake within a function and invoke this function in the setInterval.

We can compare the x and y coordinates of the snake with these limits.

If the x coordinate of the snake is less than 0 or greater than 1095px, the snake will strike the limits on the y-axis and also we have to control the snake's y coordinates in the x-axis walls.

Screenshot 3

aaaa.fw.png


Let's check according to the picture above, and let's create a confirm() function when the snake hits one of the walls.

function snakeDie(){

  snakeX=arrayNode[arrayNode.length-1].attr('x');
  snakeY=arrayNode[arrayNode.length-1].attr('y');

  if(snakeX<0||snakeX>1080||snakeY<0||snakeY>675){
    if (confirm('Would you like to play again')) {
               window.location.reload(false)
            } else {

            }
  }

}



Let's callback this function in setInterval.

intervalValue=setInterval(function(){

snakeEat();
snakeMove();
snakeDie();

}, speed);


Screenshot 4

ezgif2.gif

Hit Itself

In snakeDie() function, we control the snake's impact on walls and the game ends when the snake hits its own tail.

To check this, we must check the coordinates of each element of the array to see if the coordinates of the last element of the array are equal.

We set snakeX and snakeY variables for the coordinates of the last element of the array.

Let's check every element of the array in a for loop and if the equality is achieved we will finish the game.

In snakeDie()

  for (var i = 0; i < arrayNode.length-1; i++) {

    if(snakeX==arrayNode[i].attr('x') && snakeY==arrayNode[i].attr('y')){
      if (confirm('Would you like to play again')) {
                 window.location.reload(false)
              } else {

              }

    }
  }


Screenshot 5

ezgif3.gif


Finally, let's accelerate snake when ate food.

In snakeEat() function, when the food is eaten, decrease the speed variable and create a setInterval() function.

We need to stop the previous one when we run a new setInterval () function. We use the clearInterval() function to stop a running interval.

if(speed!=30){
        speed=speed-2;
      }

      console.log(speed);
      clearInterval(intervalValue);
      intervalValue=setInterval(function(){
        snakeEat();
        snakeMove();
        snakeDie();

      },speed)



Here we set the speed variable to 30 when fixed. We don't want it to be faster.

Screenshot 6

ezgif4.gif

Curriculum

Making Snake Game Using HTML 5 SVG With PabloJs (Part-1)

Proof of Work Done

Making Snake Game Using HTML 5 SVG With PabloJs (Part-2) in GitHub

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution @onepice.
After analyzing your tutorial we suggest the following:

  • At the end of the game there is an alert asking if you want to play again. If you click the cancel button the alert appears again. We suggest that the cancel button close the game window.

  • You could put the variable foodControl as Boolean.

  • The snake game area is not visible on smaller screens.
    Put your page with responsive gaming (visible to all devices and resolutions).
    See how it appears on my screen:

Screen Shot 2018-09-30 at 14.37.39.png

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin!

So far this week you've reviewed 3 contributions. Keep up the good work!

Hi @onepice!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @onepice!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!