Home » Tutorials » Game Development » Learn Object Oriented JavaScript Via Game Development

Learn Object Oriented JavaScript Via Game Development

Learn Object Oriented JavaScript Via Game Development

In this article, you’ll learn to build a classic Rock–paper–scissors using Object-Oriented Programming in JavaScript.

Tutorial Details

  • Difficulty: Intermediate
  • Technology: Basic Knowledge of HTML & JavaScript

What is Object-Oriented Programming?

Object-Oriented Programming or better known as OOP is a programming style used to organize code. It helps to organize your code, to group all similar task into what are known as class and provide you greater flexibility, easier maintenance, easier to extend and share your code with your team-mates.

Today, many popular programming languages such as Java, C#, C++, Python, PHP, Ruby and Objective-C supports OOP too.

Before you start, you must have a basic understanding of objects and classes .

Class

A class is a template definition of an object’s properties and methods. For example, a well defined blueprint is a necessary thing, before the production start.

Object

An instance of a class. In the real world, we can take car manufacture as example, such as a car (object) is built according to the blueprint (class) that has been defined earlier.

How to apply Object-Oriented Programming in JavaScript?

Creating an Object in JavaScript is relatively simple, there are 2 ways for you to create it, either: “Constructor notation” or “Literal notation“.

// Literal notation
var myObject = {

};

// Constructor notation
function myObject(){
 
};

In this article, we’re going to build classic game “Rock–paper–scissors” using “Constructor notation”. If you’re new to Object-Oriented, I guessed you’ll be more familiar to “Constructor notation” instead of “Literal notation”.

Please be noted that I’ll skip HTML, CSS and focus only on explaining JavaScript throughout the entire article.

Everyone knows “Rock–paper–scissors”, it is a classic 2 players game. Each player chooses either rock, paper or scissors. The possible outcome are:

  • Rock beats scissors
  • Paper cover rock
  • Scissors cuts paper

And this is a 2 players game, we need to know the player’s choice, computer’s choice and determine who will win based on their choices.

rock paper scissor screenshot
rock paper scissor screenshot

Please take a look on how the HTML code looks like, before we get our hands dirty:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Classic Rock–paper–scissors</title>
</head>
<body>
Computer<br />
<div id="computer_choice"></div>
<div id="result"></div>

<br /><br />

Player<br />
<div id="player_choice"></div>
<div id="paper" class="button">paper</div>
<div id="rock" class="button">rock</div>
<div id="scissors" class="button">scissors</div>
</body>
</html>

First

Define several variables to store the player’s choice input, display player’s choice and computer’s choice on screen, followed by the game result. Those variables are:

var game; // a variable that we will use to create a game object later
var userChoice = "";
var computerChoice = "";
var result = "";
var buttons = document.getElementsByClassName("button"); // consists of 3 buttons: rock, paper & scissors
var playerChoiceDisplay = document.getElementById("player_choice"); // an element to display player's choice
var computerChoiceDisplay = document.getElementById("computer_choice"); // an element to display computer's choice
var resultDisplay = document.getElementById("result"); // an element to display the game result

Second

Declare a class called “game”, we will use it to handle the entire game play.

function game(){

};

Third

Define methods or known as functions to allows us to collect the player’s choice, computer’s choice and determine who will win the game later on.

The “this” keyword has been used inside a class / function to refer to the object the function is contained within.

function game(){
	this.computerInput = function(){

	};

	// choice1 is player's choice
	// choice2 is computer's choice
	this.compare = function(choice1, choice2){

	};
};

As you can seen above, we need to write a simple method “computerInput” to allows computer makes its choice, so our “computerInput” method looks likes:

function game(){
	this.computerInput = function(){
		this.computerChoice = Math.random();
		if (this.computerChoice < 0.34) {
			return this.computerChoice = "rock";
		} else if(this.computerChoice <= 0.67) {
			return this.computerChoice = "paper";
		} else {
			return this.computerChoice = "scissors";
		};
	};

	// choice1 is player's choice
	// choice2 is computer's choice
	this.compare = function(choice1, choice2){

	};
};

The Math.random will return a random number ranging from 0 ~ 1, in this case we will instructs the computer to select either rock, paper or scissors.

Fourth

Create an object called “game” using Constructor notation and assign it to the variable we created earlier.

var game = new game();

Fifth

Collect player’s input. We have 3 buttons displays on the screen to allow player to select either rock, paper or scissors.

for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function(){
		userChoice = this.id;
		playerChoiceDisplay.innerHTML = "player: " + userChoice;
	}, false);
}

Sixth

Compare both player and computer choices, then display the result on the screen.

for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function(){
		userChoice = this.id;
		playerChoiceDisplay.innerHTML = "player: " + userChoice;

		computerChoice = game.computerInput();
		computerChoiceDisplay.innerHTML = "computer: " + computerChoice;

		result = game.compare(userChoice, computerChoice);

		resultDisplay.innerHTML = "Result: " + result;
	}, false);
}

We already created an “game” object earlier, and to execute the object’s method is pretty simple, we just need to specify the object’s name follow by dot notation and method name. Example:

// object name follow by dot notation and method name
game.computerInput()

View Demo

Object-oriented programming in JavaScript is easy right? Let’s summarize the lesson here.

Summary

You have just learned:

  • What is Object-Oriented Programming
  • What is Class
  • What is Object
  • How to define class and method in JavaScript
  • How to create an object and execute its method.

Thanks for reading, and I do hope this tutorial can helps you to understood the basic of OOP concept and how to write OOP in JavaScript. Stay tuned for more upcoming OOP tutorials!


Android, iOS Development Tutorials