PART 3 : [DIY Game Series] Create a simple game with JavaScript

in gaming •  7 years ago 

[DIY Game Series with @zulman]


img1.png

Hello guys, welcome back again. Let's continue our game development article. In today's DIY Game Series, I am going to continues the game that we have created in the previous two part of this article. Here is part 3 of the article. To check out my two previous article, you can go to it by clicking the link below:

Part 1 : DIY Game Series

Part 2 : DIY Game Series

So, what do we already have so far after following my two previous article on DIY Game Series? Here is the quick review on what have we created.

  • We have created a window area, character(in form of rectangle) and obstacle.
  • Our character can be controlled using up and down arrow keys.
  • The obstacle is already moving towards the character.
  • The logic has been applied where the game will over if the character hit the obstacle.

Alright Now, in this PART 3, here is what we are going to do to our existing html file.

  • Adding Multiple Obstacles.
  • Make the obstacles in random size.

Well, without further ado, let us start writing the code.

Step 1. Adding Multiple Obstacle

The existing html file that we have after following the two of previous article already have some gameplay to it. The game already have obstacle where our character need to avoid. However, the obstacle that we have so far is only one. We need to add more of them. In fact, these obstacles need to be always coming as long as the character does not hit them. To this, we are going to change a few things quite a bit.

  • First thing we need to do is to declare our obstacle variable as an array. We can do that by changing it to be like this var myObstacles = [];. And we need to remove this line myObstacle = new character(10, 200, "red", 300, 120); from startGame function.
  • Once we add the variable and remove the character creation, we need to make some change to our windowArea function, wee need to add this line this.frameNo = 0;. We need to set and declare a frame number. Now our windowArea function will look something like this:
var windowArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0; // This is what we add.
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            windowArea.key = e.keyCode;
        })
        window.addEventListener('keyup', function (e) {
            windowArea.key = false;
        })
    },
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    stop : function() {
      clearInterval(this.interval);
    }
}

  • The next step that we need to do is to change some code in our updateGameArea function. Our updateGameArea function should be like this.
function updateGameArea() {
  var x, y;
  for (i = 0; i < myObstacles.length; i += 1) {
      if (myCharacter.crashWith(myObstacles[i])) {
          windowArea.stop();
          return;
      }
  }
  windowArea.clear();
  windowArea.frameNo += 1;
  if (windowArea.frameNo == 1 || everyinterval(100)) {
    x = windowArea.canvas.width;
    y = windowArea.canvas.height - 200;
    myObstacles.push(new character(10, 200, "red", x, y));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  if (windowArea.key && windowArea.key == 38) {myCharacter.speedY = -1; } //up
  if (windowArea.key && windowArea.key == 40) {myCharacter.speedY = 1; } //down
  myCharacter.newPos();
  myCharacter.update();
}

  • One final step that we need to is to add another function to execute our frame number counting property. Add this function at the end of the JavaScript code.
function everyinterval(n) {
    if ((windowArea.frameNo / n) % 1 == 0) {return true;}
    return false;
  }

Now, if you run the code, you will see something like the image below.

img8.gif

Step 2. Make our obstacles in random size.

Aright, Now let's make the game more interesting. As for now, the game so far the we have is only very uninteresting right, The obstacles only appear with the same size and the same place. So, to make it more interesting, we are going to make the obstacles appear at the bottom and at the top with the size of the obstacles will be random. This way, the gameplay will be more interesting. To that, there is not much we should at to the existing code. We only need to change some code in our "updateGameArea" function.

  • First thing that we need to add are some variables that are going to hold the value that we need. Now, just under the function declaration, let's add these variables: var x, height, gap, minHeight, maxHeight, minGap, maxGap;.
  • After we add these variables, now we need to change the following code inside the function.
if (windowArea.frameNo == 1 || everyinterval(100)) {
  x = windowArea.canvas.width;
  y = windowArea.canvas.height - 200;
  myObstacles.push(new character(10, 200, "red", x, y));
}

become like this:

if (windowArea.frameNo == 1 || everyinterval(200)) {
    x = windowArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
    myObstacles.push(new character(10, height, "red", x, 0));
    myObstacles.push(new character(10, x - height - gap, "red", x, height + gap));
}

Now, after we make the change, if we run the code, it will look something like the gif below:

img9.gif

Alright, for the final step, let's put some description on how to play the game. We can do that by writing some html code outside the <script> tag. Let's add the following:

<h2>How to play the game</h2>
<br>
<ul>The game will start as soon as the page is loded. </ul>
<ul>Use "UP" and "DOWN" arrow keys to control the yellow rectangle. </ul>
<ul>To restart the game, just reload the page. </ul>

If you run the code now, you will see the change that you have met.


If you like to try to play it, I have put these game in my Github page. To try to play it, just click the link below.


Play The Game


Our final HTML file now should look like this:


<!DOCTYPE html>
<html>
<head>
<title>[DIY Game Series]</title>
<style>
canvas {
    border:1px solid black;
    background-color: grey;
}
</style>
</head>
<body onload="startGame()">
<script>

var myCharacter;
var myObstacles = [];

function startGame() {
    myCharacter = new character(30, 30, "yellow", 12, 122);
    windowArea.start();
}

var windowArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            windowArea.key = e.keyCode;
        })
        window.addEventListener('keyup', function (e) {
            windowArea.key = false;
        })
    },
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    stop : function() {
      clearInterval(this.interval);
    }
}

function character(width, height, color, x, y) {
    this.areaofthegame = windowArea;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.update = function() {
        ctx = windowArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
      if (myCharacter.crashWith(myObstacles[i])) {
          windowArea.stop();
          return;
      }
  }
  windowArea.clear();
  windowArea.frameNo += 1;
  if (windowArea.frameNo == 1 || everyinterval(200)) {
      x = windowArea.canvas.width;
      minHeight = 20;
      maxHeight = 200;
      height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
      minGap = 50;
      maxGap = 200;
      gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
      myObstacles.push(new character(10, height, "red", x, 0));
      myObstacles.push(new character(10, x - height - gap, "red", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  if (windowArea.key && windowArea.key == 38) {myCharacter.speedY = -1; } //up
  if (windowArea.key && windowArea.key == 40) {myCharacter.speedY = 1; } //down
  myCharacter.newPos();
  myCharacter.update();
}

function everyinterval(n) {
    if ((windowArea.frameNo / n) % 1 == 0) {return true;}
    return false;
  }

</script>
<h2>How to play the game</h2>
<br>
<ul>The game will start as soon as the page is loded. </ul>
<ul>Use "UP" and "DOWN" arrow keys to control the yellow rectangle. </ul>
<ul>To restart the game, just reload the page. </ul>
</body>
</html>


Alright, that is all for this part 3. We have created something that user can play. However, there are still thing to add to make the game such as the score. We will do that in my next article. Stay tune...

Please follow for me @zulman for my next article.



Notice:
This is could be not the best article about creating game with Javascript. I am currently starting to learn javascript and what I share here is something that I have learnt. Perhaps, you will find some similarities with the source in term of the code. Remember that I write the article as my experience in learning javascript. If you want to learn more about javascript and html game, you can go to the original source as the link in the reference.


Reference : Here


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:  

WARNING! The comment below by @syarkawi20 leads to a known phishing site that could steal your account.
Do not open links from users you do not trust. Do not provide your private keys to any third party websites.

WARNING - The message you received from @syarkawi20 is a CONFIRMED SCAM!
DO NOT FOLLOW any instruction and DO NOT CLICK on any link in the comment!
For more information, read this post: https://steemit.com/steemit/@arcange/phishing-site-reported-autosteemer-dot-com
Please consider to upvote this warning if you find my work to protect you and the platform valuable. Your support is welcome!

  ·  7 years ago Reveal Comment