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

in #utopian-io6 years ago

Untitled-1.fw.png

Repository

PabloJs

My GitHub Profile

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

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 rect() function with stroke in Pablojs.
  • You will learn parseInt() function in javascript.
  • You will learn setInterval() in javascript.
  • You will learn Math.floor() and Math.random functions in javascript.
  • You will learn how to assign elements when creating an array.
  • You will learn push() and shift() functions to array.

Requirements

Visual Studio Code in GitHub

Difficulty

  • Basic

Tutorial Contents

Hello to everyone!

We are starting a new game coding with this article. I will show you how to encode the snake game together with this article.

I'll create a snake that moves around constantly. This snake will consist of small rectangles. When creating rectangles, we will use rect() function in pablojs. I also will show how to use stroke to determine the boundaries of the rectangle.

In this article:

  • I will form the snake.
  • I'll move the snake.
  • I will change the direction of the snake.

Let’s start

First create the index.html page and set the playing field.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    (html comment removed: include bootstrap)
    <link href="bootstrap.css" rel="stylesheet">
    (html comment removed: include jquery)
    <script src="./jquery.js"></script>
    (html comment removed: include pablo.js)
    <script src="./pablo.js"></script>
    (html comment removed: include custom script file)
    <script src="script.js"></script>
    <style>
    #ground {
        height: 700px;
        width:1100px;
        border: 1px solid #060;
        background-color: #ECF0F1;
    }
    </style>
    <title>Snake Game</title>
</head>
<body>
   <div class="container">
     <div class="jumbotron text-primary"><h1>Snake GAME</h1></div>
     <div id="ground">
     </div>
   </div>
</body>
</html>



I need to have the Bootstrap, Jquery and pablojs libraries in the file directory and create the script.js file and define the svg object use pablojs.

var svg = Pablo('#ground').svg({ //create svg with height and width
         width: 1100,
        height: 700
      });


Snake Creation

I will perform the creation of a snake in a function.

Snake will consist of rectangles so I need to know how many rectangles.

Since these rectangles are linked to each other, if I know the x and y coordinates of one, I can create the x and y coordinates of the others.

I will transfer these rectangles to an array so it will be easier to access the nodes of the snake.

Let's create this function.

//create snake
function snakeBuilder(node,x,y){
}



This function take 3 parameters. With the node parameter we determine how many nodes in the snake and with the x and y parameters we determine the x and y coordinates of the first node.

I will set the width and height of the rectangles to the nodeSize variable so the height and width will be equal.

To determine the borders of the rectangle, I will use stroke in the rect() function.

With stroke, we adjust the edge color.

With stroke-width feature, we adjust the thickness of the edge.

I adjust the roundness of the edge with stroke-linejoin.

Lastly I will transfer the rectangle created to arrayNode array.

var arrayNode=new Array();
var nodeSize=15;



Let's turn in a loop according to the number of nodes and create the rectangle.

function snakeBuilder(node,x,y){

  for (var i = 0; i < node; i++) {

      var snakeNode=svg.rect({
          x:x, y:y,
          width:nodeSize, height:nodeSize,
          fill:'#eb4d4b',  
          stroke:'#006',
          'stroke-width': 2,
          'stroke-linejoin': 'round'
      });
      x=x+nodeSize;

      arrayNode.push(snakeNode);//add node
  }

}



Now we can create our snake by using this function.

Let's draw the snake on the 4-node and x = 100 and y = 100 points of the starting node.

snakeBuilder(4,100,100);//draw snake


Screenshot 1

jquery1.JPG


If we want to examine the arrayNode array, we can print in console.

console.log(arrayNode);


Screenshot 2

jquery2.JPG


So that the first node was the leftmost node of the snake.

The color of the snake will always remain constant when it moves and grows. If we want the snake nodes to change continuously, we can use a array of multiple colors.

The color of our snake changes continuously if we set a random color in this array to the new node to be inserted into the movement of the snake.

I'm going to create an array and I'll define the elements of this array when I'm creating the array.

var arrayColor=new Array("#ef5777","#ffc048","#575fcf","#05c46b","#8e44ad");
var colorIndex=0;



Let's set the colorIndex variable randomly and create the fill property from the arrayColor array in the rect () method.

var colorIndex=Math.floor(Math.random() * 5);// A random number between 0 and 5

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



The game will consist of a snake that changes colors when refresh.

Screenshot 3

jquery3.JPG

Snake Movement

To move the snake, delete the first element of the array and add a new element.

We must first determine the directions. The following figure defines the values for the directions.

Screenshot 4

aaaa.png


When the direction value is 1 and 3, the snake is moving on the x-axis and when the direction value is 2 and 4, the snake is moving on the y-axis.

We need to scroll through the nodeSize amount when creating the next rectangle. By doing so, we move the snake within 15 and its multiples.

Then create a function to provide movement and move the coordinates of the last element of the arrayNode array by direction.

var direction=1;
function snakeMove(){
  var x;
  var y;

  x=arrayNode[arrayNode.length-1].attr('x');//access to the x property of the last rectangle of the array
  y=arrayNode[arrayNode.length-1].attr('y');//access to the y property of the last rectangle of the array

if(direction==1){
   x=parseInt(x)+nodeSize;//Move on the + X axis
}

if(direction==2){
   y=parseInt(y)+nodeSize;//Move on the +Y axis
}

if(direction==3){
   x=parseInt(x)-nodeSize;//Move on the - X axis
}
if(direction==4){
   y=parseInt(y)-nodeSize;//Move on the - Y axis
}
}



Since x and y variables are created in the function, they can be used within this function. These variables are not numbers because they have the x and y points of the svg object. These values must be integers because we move or subtract to move the x and y axes. With parseInt() method, we can create integer value.

Let's create the colorIndex value randomly and create the new rectangle.

var colorIndex=Math.floor(Math.random() * 5);

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



We must remove the rectangle from the first element of the array and remove it from the array to ensure the movement property.

To delete svg elements, we use the remove() method and we use the shift() method to discard the first element of the array.

If we delete the first element by using the shift() method, the index of all elements will be changed and the first element will be the second element before it is deleted.

Let's delete the first element and add the newly created rect element to the end of the array.

We use the push() method to add elements to the end of an array.

arrayNode[0].remove();//remove first svg element 
arrayNode.shift();//delete first element in array

  arrayNode.push(snakeNode);//add last element



We have completed the function now we can use.

This function must be run at certain time intervals since the snake will move continuously. The function setInterval() used to run certain functions at certain time intervals in javascript.

Let's create a variable to set the speed of the snake and use the setInterval().

var speed=200;
setInterval(function(){
  snakeMove();
}, speed);



Now the snakeMove() function will work one in 200 milliseconds.

If direction=1

Screenshot 5

ezgif1.gif


If direction=2

Screenshot 6

ezgif2.gif


If direction=3

Screenshot 7

ezgif3.gif


If direction=4

Screenshot 8

ezgif4.gif

Change the Direction

I'll use the direction keys on the keyboard to change the direction of the snake.

We can use the keydown() method to capture keyboard events with Jquery. When keydown() is executed, the keys on the keyboard have a code and we can capture the code of that key if the key is pressed. These codes can be reached with event.which.

$(document).keydown(function(event){
  //37 = left  - 38 = up - 39  = right - 40 = down

     var code =  event.which;

});



We do not want to turn in the opposite direction of the snake. Then we have to do the control.

For example; The snake should not go to 3 directions as it moves in direction 1 and should return to 4 and 2 directions only.

$(document).keydown(function(event){
  //37 left  - 38  up - 39  right - 40  down

     var code =  event.which;

     if(direction==1||direction==3){
       if(code==38) direction=4;
       if(code==40) direction=2;
     }

     if(direction==2||direction==4){
       if(code==39) direction=1;
       if(code==37) direction=3;
     }
});



Now we can move the snake with the keyboard.

Screenshot 9

ezgif5.gif

Proof of Work Done

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

Sort:  

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

  • We tested your game and saw that the page has scroll and when we move the snake the page also moves. Remove the header from the page to stay just the game.

  • In the next tutorial, put the snake to not go beyond the area of the game and make the game finish when it happens.

This game is very interesting, and the tutorial is very well explained. Thank you again for your good work.

We look forward to your next tutorial.

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 comment,
I will prevent page from scrolling in the next tutorial

Thank you for your review, @portugalcoin!

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

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!

Coin Marketplace

STEEM 0.22
TRX 0.21
JST 0.035
BTC 91569.43
ETH 3174.28
USDT 1.00
SBD 3.07