
# Repository
<a href="https://github.com/premasagar/pablo">PabloJs</a>
<a href="https://github.com/onepicesteem"> My GitHub Profile</a>
<a href="https://github.com/onepicesteem/Making-Snake-Game-Using-HTML-5-SVG-With-PabloJs-Part-1">Making Snake Game Using HTML 5 SVG With PabloJs (Part-1)</a>
# 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
<a href="https://github.com/Microsoft/vscode">Visual Studio Code in GitHub</a>
# 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">
<!--include bootstrap-->
<link href="bootstrap.css" rel="stylesheet">
<!--include jquery-->
<script src="./jquery.js"></script>
<!--include pablo.js-->
<script src="./pablo.js"></script>
<!--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>
```
<br>
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
});
```
<br>
### 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){
}
```
<br>
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;
```
<br>
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
}
}
```
<br>
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
```
<br>
#### Screenshot 1

<br>
If we want to examine the `arrayNode` array, we can print in console.
```
console.log(arrayNode);
```
<br>
#### Screenshot 2

<br>
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;
```
<br>
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'
});
```
<br>
The game will consist of a snake that changes colors when refresh.
#### Screenshot 3

<br>
### 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

<br>
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
}
}
```
<br>
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'
});
```
<br>
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
```
<br>
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);
```
<br>
Now the `snakeMove()` function will work one in `200 milliseconds`.
If `direction=1`
#### Screenshot 5

<br>
If `direction=2`
#### Screenshot 6

<br>
If `direction=3`
#### Screenshot 7

<br>
If `direction=4`
#### Screenshot 8

<br>
### 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;
});
```
<br>
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;
}
});
```
<br>
Now we can move the snake with the keyboard.
#### Screenshot 9

<br>
# Proof of Work Done
<a href="https://github.com/onepicesteem/Making-Snake-Game-Using-HTML-5-SVG-With-PabloJs-Part-1">Making Snake Game Using HTML 5 SVG With PabloJs (Part-1)</a>