create account

Tank Fire Game Using HTML SVG (Part-1) by onepice

View this thread on: hive.blogpeakd.comecency.com
· @onepice ·
$20.16
Tank Fire Game Using HTML SVG (Part-1)
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmPDwua9k7WdodWnvs76NRGQSbyoEmJvbad6EdL9QB7VYS/Untitled-1.fw.png)

# 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/Tank-Fire-Game-Using-HTML-SVG-Part-1-">Tank Fire Game Using HTML SVG (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 to move the svg object.
- You will learn to access a family with more than one svg object.
- You will learn to reach the keyboard keys in `jquery`.

# Requirements
<a href="https://github.com/Microsoft/vscode">Visual Studio Code in GitHub</a>

# Difficulty
- Basic

# Tutorial Contents

We will enter into the construction of a tank game on this article. We will draw our tank and move this tank.

So our article was divided into two parts. 

In the first part I will determine the playing field and draw the tank.

In the second part I will move our tank according to the keyboard keys.

Let's start.

### Create Playground

First, we will prepare the playground.

I will use `bootstrap` to make it easier to prepare the playing field and I should use `jquery` and `pablojs` libraries.

```
<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="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <!--include jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!--include pablo.js-->
    <script src="./pablo.js"></script>
    <!--include custom script file-->
    <script src="script.js"></script>

    <title>Tank Fire Game</title>
</head>
```
<br>
I will define the `container` in the `<body>` because I want to center the page.

Let's define the jumbotron in it and let's write the game name in center.
```
<body>
   <div class="container">
     <div class="jumbotron text-center text-primary"><h1>TANK FIRE GAME</h1></div>
     <div id="ground">
     </div>
   </div>
</body>
```
<br>
### Screenshot 1
![jquery1.JPG](https://cdn.steemitimages.com/DQmWppwEnZMxWMjpP5pHpRq6jSPPMXjGKEZXns5fgecB88q/jquery1.JPG)
<br>
We can determine the playing area by giving style to the ground area.
```
<style>
    #ground {
        height: 700px;
        width:1100px;
        border: 1px solid #060;
        background-color: #ECF0F1;
    }
    </style>
```
<br>
I set the width of the play area to `700px` and the height to `1100px`.

We will use these values to make sure that the svg elements do not go out later.

The playing field is as follows.

### Screenshot 2
![jquery2.JPG](https://cdn.steemitimages.com/DQmeX8tBN9KG9kUm6dByrgu99Lqqw4GaqoYLTPV5yAARjGg/jquery2.JPG)
<br>

### Draw Tank

Since the tank does not consist of one svg object, we need to link several svg objects together.

We can define a function to perform this operation. This function can draw other parts according to a main value.

First, we will examine the svg objects we need to create.

### Screenshot 3
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmV9M9fipuhwmCuapkdKHoNict8VH4s2MZmxP4ERNvFV5h/Untitled-1.fw.png)
<br>
As you can see, the tank is formed by joining the above five objects.

We must place the body and hood objects on top of each other to combine these objects, and we must place other objects with reference to the midpoints.

We have to redesign these parts according to the direction of the tank and we must unite them.

__Direction Up__

We need to look at the picture below to draw a tank going up.

### Screenshot 4
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmfJU9pnHPPXDzFh29Qv5sBL6Lw4ZdbuV3ovL9cjXowsh7/Untitled-1.fw.png)
<br>
We draw up an upturn tank by plotting the svg elements as shown in this figure.

We are accessing the coordinates of the upper left point by doing `x-20` and `y-20` because the body area is `40x40` and because it is the exact center point center.

We can draw the other parts of the tank with this logic.

__Direction Down__

### Screenshot 5
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmVvMVk24w1EtgYQDkt8nPg2tz8mCSwUCXqb9cQaAnBd5o/Untitled-1.fw.png)
<br>
Change the y coordinates of the gun object needed to create the downward position of the tank.

__Direction Left and Right__

We have to redesign all the parts to adjust the left and right directions.

In such a drawing, the left and right sides are set up and down. I will carry the rectangle on the left side up and the rectangle on the right side down.

I also need to change the height and width.

### Screenshot 6
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmZ6bZP6pgvWWuwqdAThGrEZkZas5ccwEPQUhYFwgEnpfZ/Untitled-1.fw.png)
<br>
We are now ready to write our codes.

Open the script file and write the page loading code for `jquery`, then create the `svg` object.
```
$(function(){

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

});
```
<br>
Combine all the parts into one function.

This function must be such a function that `x`, `y` coordinates and `direction` properties must be taken as external parameters.

Let's check the direction variable in this function and draw the tank into this function.

```
function tankBuilder(x,y,direction){


if(direction=="up"){

  body=svg.rect({//draw body for up
    x:x-20,
    y:y-20,
    width:40, height:40,
    fill: '#6ab04c',
  });

  sideLeft=svg.rect({//draw sideLeft for up
    x:x-28,
    y:y-25,
    width:8, height:50,
    fill: '#2c3e50',
  });


  sideRight=svg.rect({//draw sideRight for up
    x:x+20,
    y:y-25,
    width:8, height:50,
    fill: '#2c3e50',
  });

  hood=svg.circle({//draw hood for up
    cx: x,
    cy: y,
    r: 10,
    fill:  '#2c3e50'
   });

   gun=svg.rect({//draw gun for up
     x:x-2,
     y:y-30,
     width:4, height:25,
     fill: '#2c3e50',
   });
}

if(direction=="down"){

   body=svg.rect({//draw body for down
    x:x-20,
    y:y-20,
    width:40, height:40,
    fill: '#6ab04c',
  });

  sideLeft=svg.rect({//draw sideLeft for down
    x:x-28,
    y:y-25,
    width:8, height:50,
    fill: '#2c3e50',
  });


  sideRight=svg.rect({//draw sideRight for down
    x:x+20,
    y:y-25,
    width:8, height:50,
    fill: '#2c3e50',
  });

   hood=svg.circle({//draw hood for down
    cx: x,
    cy: y,
    r: 10,
    fill:  '#2c3e50'
   });

    gun=svg.rect({//draw gun for down
     x:x-2,
     y:y+5,
     width:4, height:25,
     fill: '#2c3e50',
   });
}
if(direction=="left"){

  body=svg.rect({//draw body for left
   x:x-20,
   y:y-20,
   width:40, height:40,
   fill: '#6ab04c',
 });

 sideLeft=svg.rect({//draw sideLeft for left
   x:x-25,
   y:y-28,
   width:50, height:8,
   fill: '#2c3e50',
 });


 sideRight=svg.rect({//draw sideRight for left
   x:x-25,
   y:y+20,
   width:50, height:8,
   fill: '#2c3e50',
 });

  hood=svg.circle({//draw hood for left
   cx: x,
   cy: y,
   r: 10,
   fill:  '#2c3e50'
  });

   gun=svg.rect({//draw gun for left
    x:x-26,
    y:y-2,
    width:25, height:4,
    fill: '#2c3e50',
  });
}
if(direction=="right"){

  body=svg.rect({//draw body for right
   x:x-20,
   y:y-20,
   width:40, height:40,
   fill: '#6ab04c',
 });

 sideLeft=svg.rect({//draw sideLeft for right
   x:x-25,
   y:y-28,
   width:50, height:8,
   fill: '#2c3e50',
 });


 sideRight=svg.rect({//draw sideRight for right
   x:x-25,
   y:y+20,
   width:50, height:8,
   fill: '#2c3e50',
 });

  hood=svg.circle({//draw hood for right
   cx: x,
   cy: y,
   r: 10,
   fill:  '#2c3e50'
  });

   gun=svg.rect({//draw gun for right
    x:x,
    y:y-2,
    width:25, height:4,
    fill: '#2c3e50',
  });

}

}

```
<br>
Now that we have created the function to draw a tank, we can print it on the screen.

```
  tankBuilder(100,100,"up");
  tankBuilder(200,100,"down");
  tankBuilder(300,100,"left");
  tankBuilder(400,100,"right");
```
<br>
### Screenshot 7
![jquery3.JPG](https://cdn.steemitimages.com/DQmW1Tr7qFcthmmz72QZHcWcxvWU2DfVy1WydEHKa8a3oRY/jquery3.JPG)
<br>
### Tank Movement

There are two steps to moving the tank.

The first step is to capture the moment when the selected keys of the keyboard are pressed and redraw the center points of the tank by moving a certain unit in this direction.

The second step is to erase the old tank.

I will use `keydown()` function in `jquery` to catch keyboard keys.

With the `keydown()` method, we can capture the keystroke of the key on the keyboard.

Here are the keys we need to know are expressed by numbers. We have access to with the `which` feature.

The number keys of the arrow keys are down.
```
left--->37
up---->38
right--->39
down--->40
```
<br>
We can set directions relative to this number.

Let's go coding.

First of all keep the initial values of the tank variable and draw one tank.
```
var tankX=550;
var tankY=600;
var tankDirection="up";

tankBuilder(tankX,tankY,tankDirection);
```
<br>
Let's catch the key stroke from the keyboard and redraw the tank in that direction.
```
  $(document).keydown(function(event){
  //37 left  - 38  up - 39  right - 40  down

     var code =  event.which;//I get the key number value

     if(code==37){

       tankX=tankX-3;
       tankBuilder(tankX,tankY,"left");

     }
     if(code==38){

       tankY=tankY-3;
       tankBuilder(tankX,tankY,"up");
     }
     if(code==39){

       tankX=tankX+3;
       tankBuilder(tankX,tankY,"right");
     }
     if(code==40){

       tankY=tankY+3;
       tankBuilder(tankX,tankY,"down");
     }


  });

```
<br>
I changed the variable X and y according to the key pressed and redrawed the tank.

### Screenshot 8
![ezgif.com-crop.gif](https://cdn.steemitimages.com/DQmeoPGQMRG9kEbkxA7bhcancDytcvgRSLA2GverFALPiRU/ezgif.com-crop.gif)
<br>
There is something wrong with the above picture.

We have to delete the old tank objects when the arrow keys are pressed to overcome this problem.

We need to delete the `body, sideLeft, sideRight, hood and gun` objects when each key is pressed.
```
   if(code==37){

       body.remove();
       sideLeft.remove();
       sideRight.remove();
       hood.remove();
       gun.remove();
       tankX=tankX-3;
       tankBuilder(tankX,tankY,"left");

     }
     if(code==38){
       body.remove();
       sideLeft.remove();
       sideRight.remove();
       hood.remove();
       gun.remove();
       tankY=tankY-3;
       tankBuilder(tankX,tankY,"up");
     }
     if(code==39){
       body.remove();
       sideLeft.remove();
       sideRight.remove();
       hood.remove();
       gun.remove();
       tankX=tankX+3;
       tankBuilder(tankX,tankY,"right");
     }
     if(code==40){
       body.remove();
       sideLeft.remove();
       sideRight.remove();
       hood.remove();
       gun.remove();
       tankY=tankY+3;
       tankBuilder(tankX,tankY,"down");
     }
```
<br>
### Screenshot 9
![ezgif.com-crop.gif](https://cdn.steemitimages.com/DQmP7VsC6ooY8USbhCi3gAK33Em18xDzgCWYfLmD47UgDEn/ezgif.com-crop.gif)
<br>

So that we got the tank to move.

# Proof of Work Done

<a href="https://github.com/onepicesteem/Tank-Fire-Game-Using-HTML-SVG-Part-1-">Tank Fire Game Using HTML SVG (Part-1) </a>
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 44 others
properties (23)
authoronepice
permlinktank-fire-game-using-html-svg-part-1
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","jquery","pablojs","game-developer"],"image":["https://cdn.steemitimages.com/DQmPDwua9k7WdodWnvs76NRGQSbyoEmJvbad6EdL9QB7VYS/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmWppwEnZMxWMjpP5pHpRq6jSPPMXjGKEZXns5fgecB88q/jquery1.JPG","https://cdn.steemitimages.com/DQmeX8tBN9KG9kUm6dByrgu99Lqqw4GaqoYLTPV5yAARjGg/jquery2.JPG","https://cdn.steemitimages.com/DQmV9M9fipuhwmCuapkdKHoNict8VH4s2MZmxP4ERNvFV5h/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmfJU9pnHPPXDzFh29Qv5sBL6Lw4ZdbuV3ovL9cjXowsh7/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmVvMVk24w1EtgYQDkt8nPg2tz8mCSwUCXqb9cQaAnBd5o/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmZ6bZP6pgvWWuwqdAThGrEZkZas5ccwEPQUhYFwgEnpfZ/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmW1Tr7qFcthmmz72QZHcWcxvWU2DfVy1WydEHKa8a3oRY/jquery3.JPG","https://cdn.steemitimages.com/DQmeoPGQMRG9kEbkxA7bhcancDytcvgRSLA2GverFALPiRU/ezgif.com-crop.gif","https://cdn.steemitimages.com/DQmP7VsC6ooY8USbhCi3gAK33Em18xDzgCWYfLmD47UgDEn/ezgif.com-crop.gif"],"links":["https://github.com/premasagar/pablo","https://github.com/onepicesteem","https://github.com/onepicesteem/Tank-Fire-Game-Using-HTML-SVG-Part-1-","https://github.com/Microsoft/vscode"],"app":"steemit/0.1","format":"markdown"}
created2018-09-11 11:52:12
last_update2018-09-11 11:52:12
depth0
children5
last_payout2018-09-18 11:52:12
cashout_time1969-12-31 23:59:59
total_payout_value15.310 HBD
curator_payout_value4.853 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11,514
author_reputation9,626,549,398,383
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id70,978,240
net_rshares19,607,623,435,350
author_curate_reward""
vote details (108)
@portugalcoin ·
$8.32
Thank you for your contribution.
After reviewing your tutorial we suggest the following:

- We suggest that you create a function that has the general code where you only get the move parameter. With this function, the code is not too long. For example:
```
    if(code==37){
      my_function("up");
     }
     if(code==38){
      my_function("up");
     }
     if(code==39){
       my_function("right");
     }
     if(code==40){
      my_function("down");
     }

my_function(movement){
     body.remove();
     sideLeft.remove();
     sideRight.remove();
     hood.remove();
     gun.remove();
     tankX=tankX-3;
     tankBuilder(tankX,tankY, movement);
}
```
<br>
Very intuitive tutorial to learn HTML, CSS, Javascript and SVG. Thanks for your contribution, we look forward to the next tutorials.

Thank you and good work.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/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](https://review.utopian.io/result/8/23311314).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-onepice-tank-fire-game-using-html-svg-part-1-20180911t204504898z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/23311314","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-09-11 20:45:06
last_update2018-09-11 20:45:06
depth1
children1
last_payout2018-09-18 20:45:06
cashout_time1969-12-31 23:59:59
total_payout_value6.293 HBD
curator_payout_value2.025 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,321
author_reputation607,353,005,815,420
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,019,681
net_rshares8,118,191,780,799
author_curate_reward""
vote details (11)
@utopian-io ·
Thank you for your review, @portugalcoin!

So far this week you've reviewed 11 contributions. Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-onepice-tank-fire-game-using-html-svg-part-1-20180911t204504898z-20180916t025330z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-09-16 02:53:30
last_update2018-09-16 02:53:30
depth2
children0
last_payout2018-09-23 02:53:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length116
author_reputation152,955,367,999,756
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,411,198
net_rshares0
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-tank-fire-game-using-html-svg-part-1-20180912t050020z
categoryutopian-io
json_metadata"{"app": "beem/0.19.54"}"
created2018-09-12 05:00:21
last_update2018-09-12 05:00:21
depth1
children0
last_payout2018-09-19 05:00:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length286
author_reputation23,214,230,978,060
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,049,376
net_rshares0
@steemitboard ·
Congratulations @onepice! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/voted.png)](http://steemitboard.com/@onepice) Award for the number of upvotes received

<sub>_Click on the badge to view your Board of Honor._</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/steemitboard-witness-update-2018-09-07"><img src="https://steemitimages.com/64x128/http://i.cubeupload.com/7CiQEO.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/steemitboard-witness-update-2018-09-07">SteemitBoard - Witness Update</a></td></tr></table>

> Support [SteemitBoard's project](https://steemit.com/@steemitboard)! **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-onepice-20180911t164329000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-09-11 16:43:27
last_update2018-09-11 16:43:27
depth1
children0
last_payout2018-09-18 16:43:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,083
author_reputation38,975,615,169,260
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,002,634
net_rshares0
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-tank-fire-game-using-html-svg-part-1-20180916t104518z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-09-16 10:45:21
last_update2018-09-16 10:45:21
depth1
children0
last_payout2018-09-23 10:45:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length589
author_reputation152,955,367,999,756
root_title"Tank Fire Game Using HTML SVG (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,437,466
net_rshares0