June 30, 2015 12:48 pm

Creating a game with JavaScript and Processing.js part 2

We define all the methods that will run recursively and start defining them in the tutorial first part now its time to implement it in real, now the actual game part follows.

Creating a game with JavaScript and Processing.js part 1

We check if that particular game has ended, this happens if either the player or the enemy has 0 or less lives.

If the game has ended, we increment the winning party’s wins (which would be always a total of his wins, no matter if he exits and comes back to the site later because it is extracted from the local storage or is equal to 0 if the local storage is empty) and update the current local storage’s value. We set a message, end the game and display the game menu.

Creating a game with JavaScript and Processing.js part 1

Creating a game with JavaScript and Processing.js part 3

Next, we iterate over the number of hearts that the player has left and the enemy has left and display them (the heart image) in opposing sides of the screen.


Now, we are going to give the enemy a random direction to follow, when he reaches an edge of the screen he would bounce in a different direction.

If the player loses a life, we remove all of the stars that the player has shot, set the enemy’s stars position to 0, reverse the enemy’s direction and move him to its initial position and remove one life from the player’s lives.

At this point, we check if the player has pressed a key and if he has pressed:

-Move him to the left if he is not at the left edge of the screen

-Move him to the right if his X position combined with his width is not greater than the right edge of the screen.

– We do that with up/and down as well but check the player’s Y coordinates

– If the player is trying to shoot a star, we are checking if the milliseconds elapsed since the start of the program are greater than the milliseconds elapsed since his last shot combined with  the period in which the player cannot shoot again, and if they are greater he can shoot a star. The star’s x and y coordinates is added to an array of all his stars

You can check demo here Code for download will be aided in part 3.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter

Tutorial Categories: