This is the first complete “game” that I’m going to be making in JavaScript albeit a very simple one. The basic premise is to generate 6 or 3 (depending on difficulty) different colours and display one RGB value above the colours. The aim is for the player to correctly identify (hence improving their skills at recognising RGB colours) the correct colour from the ones displayed.

This is going to be tying together a lot of stuff that I’ve been learning recently in regards to HTML, CSS and JavaScript and this (tiny) project is going to be a showcase of all of the various things that I’ve learned so far (and serve as a reference for me in the future to come back and just copy and paste my own code for future projects – that’s what all these posts are about really – because my memory is so bad lol).

The first step was to create the 6 squares in the HTML file using “div’s” as shown in the following HTML:

<div id="container">
	<div class="square"></div>
	<div class="square"></div>
	<div class="square"></div>
	<div class="square"></div>
	<div class="square"></div>
	<div class="square"></div>
	<div class="square"></div>
</div>

The 6 “square” div’s were put inside a “container” div to neaten up the code and allow me to make the page responsive. Once the div’s were created I could begin to give them some properties in the CSS file. All of the squares are inside the container and I want them to each take up a third of the container (30% for the width of the square and 1.66% for the width of the margain gives 100%).

The first phase of CSS is as follows

body {
	background-color: #232323;
}

/* The container controls the size of 
   the box that contains the squares */
#container {
	width: 50%;
	margin-left: auto;
	margin-right: auto;
}

.square {
	width: 30%;
	background: purple;
	/* Square doesn't show up on page so padding added */
	padding-bottom: 30%;
	float: left;
	margin: 1.66%;

}

That gives us the following:

Now that we’ve got that we’re going to get JavaScript to randomise the colours in the grid. To do that we create a new JavaScript file and connect it to the HTML document. The colours were implemented by declaring an array of RGB colours (to begin with – I will randomise them later) as follows:

var colours = [
	"rgb(255, 0, 0)",
	"rgb(0, 255, 0)",
	"rgb(0, 0, 255)",
	"rgb(255, 0, 144)",
	"rgb(255, 78, 0)",
	"rgb(15, 88, 78)"
]

// querySelector takes a CSS variable hence the full stop
var squares = document.querySelectorAll(".square");

for(var i=0 ; i<squares.length ; i++){
	squares[i].style.backgroundColor = colours[i];
}

Then all of the “squares” that we defined earlier were selected and then looped through and assigned it’s respective colour (from the temporarily fixed colour array).

The next step in the development of the game is to display one of the RGB values for one of the colours randomly. That was done by selecting one of the colours (for now just one of them) and assigning it to a variable and then assigning the selected text on the HTML page (contained in the span of the h1 tag) with that variable as shown in the JaveScript code below.

var colourPicked = colours[3];
var winningColour = document.querySelector("#winningColour");

winningColour.textContent = colourPicked;

The HTML for the h1 tag is as follows:

<h1>The Great <span id="winningColour">RGB()</span> Game!</h1>

Adding the listeners to the game and the basic logic involved

So the way the game is going to work is like this. The user will be shown the colour and will then need to choose one of the colours on display. If the user picks the wrong colour it needs to be changed to the same colour as the background.

When the correct colour is chosen the game needs to change all of the squares to the winning colour as well as the background colour for the h1 tag.

The following is the for loop that checks to see what colour was picked and compares it to the winning colour and if it is different it changes the background of the wrongly selected square to be the same colour as the background colour (so it fades out).

for(var i=0 ; i<squares.length ; i++){
	// Add colours to squares
	squares[i].style.backgroundColor = colours[i];

	// Add click listeners to squares
	// Setup mouseover listener
	squares[i].addEventListener("click", function(){
    // Grab colour of picked square
    var clickedColour = this.style.backgroundColor;
    	// Compare colour to winningColour
	    if(clickedColour === colourPicked){

	    } else{
	    	this.style.backgroundColor = "#232323";
	    }
	    
	});
}

Another behaviour that we want to happen when the user clicks on a colour is for there to be a little message that pops up letting the user know how they did on their guess. This was done using a span tag inside of a div tag (which will be used later to create the navigation menu).

	<div>
		<span id="message"></span>
	</div>

Once we’ve done that we’re able to select this span tag in our JavaScript file (so we can update the text content of the tag to include our message).

var message = document.querySelector("#message");

With the tag now selected we can change the content to include our message. The original if statement that was used to change the colour of the background of the wrongly selected square was adapted to display a message to our user.

if(clickedColour === colourPicked){
     message.textContent = "Correct!";
     // Add function to change colours of all squares
     // shown below as changeColour()
} else{
     this.style.backgroundColor = "#232323";
     message.textContent = "Nope!";
}

Now that we’re this far we can look at changing the colour of the squares when the user selects the correct colour. Seeing as this will need to be done 6 times (all the squares will be changed to the winning colour) we may as well write a function that handles this for us so we aren’t writing out the same code loads of times.

function changeColours(colour){
	for (var i=0 ; i<squares.length ; i++){
		squares[i].style.backgroundColor = colour;		
	}
}

Now that happens, the next step is to randomise both the colours and the selected colour which means that we’re going to need a few random numbers so it would be best to write a couple of function to help us handle these.

The first step was to create a random number for the winner and to do that the “colourPicked” variable was changed to equal a fictitious function called pickColour().

var colourPicked = pickColour();

This pickColour function works by using the Math.random function (that generates a random number between 0 and 1) and we multiply that by the length of our squares array. The function Math.floor() is also used to remove the digits from the resulting Math.random() number.

function pickColour(){
	var number = Math.floor(Math.random() * colours.length);
	return colours[number];
}

Once this has been implemented the game selects one of the 6 squares at random as desired. The next step would be to randomise the colours in the squares instead of them always being the same colour and to do this another function was written.

function randomColours(amount){
	// Make an array
	var array = [];
	// Add "amount" number of colours to array
	for(var i=0 ; i<amount ; i++){
		array.push(randomColour());
	}
	// Return array 
	return array;
}

Inside the above function (that builds an array of “amount” colours) another function is called as seen below.

function randomColour(){
	// Random red from 0 - 255
	var red = Math.floor(Math.random() * 256);
	// Random green from 0 - 255
	var green = Math.floor(Math.random() * 256);
	// Random blue from 0 - 255
	var blue = Math.floor(Math.random() * 256);
	var colour = "rgb(" + red + ", " + green + ", " + blue + ")";
	return colour;
}

This is the function that returns a single colour to the previous function that is building an array for our program to use. Now the program selects random colours and allows us to try to guess the correct colour. The functionality is mostly there. Last thing is to change the background of the h1 tag when the user guesses the correct colour.

var h1 = document.querySelector("h1");

To do that the h1 tag was selected using querySelector() and then (in the conditional if statement in the game) when the user clicks the correct colour the h1 element changes colour.

h1.style.backgroundColor = clickedColour;

The last thing to do to the game before I’m finished is to style the page to make it look a bit more like a game and to add a menu to allow the player to choose the difficulty and see the feedback message.

You can see a working example of where this game is up to at this point before we add the styling to the page by visiting the colour game (before styling) link. Seeing that this post is so long I’m going to continue writing a part 2 for it.

I’ve finished writing the next post and it can be read by visiting Making a RGB Colour Guessing Game in JavaScript – Part 2


Here’s the code that I’ve written so far

As the game stands, the code for it is as follows. The JavaScript is:

var colours = randomColours(6);

// quesrSelector takes a CSS variable hence the full stop
var squares = document.querySelectorAll(".square");
var colourPicked = pickColour();
var winningColour = document.querySelector("#winningColour");
var message = document.querySelector("#message");
var h1 = document.querySelector("h1");


winningColour.textContent = colourPicked;


for(var i=0 ; i<squares.length ; i++){
	// Add colours to squares
	squares[i].style.backgroundColor = colours[i];

	// Add click listeners to squares
	// Setup mouseover listener
	squares[i].addEventListener("click", function(){
    // Grab colour of picked square
    var clickedColour = this.style.backgroundColor;
    	// Compare colour to winningColour
	    if(clickedColour === colourPicked){
	    	message.textContent = "Correct!";
	    	changeColours(clickedColour);
	    } else{
	    	this.style.backgroundColor = "#232323";
	    	message.textContent = "Try Again!";
	    }
	    
	});
}

function changeColours(colour){
	h1.style.backgroundColor = colour;
	for (var i=0 ; i<squares.length ; i++){
		squares[i].style.backgroundColor = colour;		
	}
}

function pickColour(){
	var number = Math.floor(Math.random() * colours.length);
	return colours[number];
}

function randomColours(amount){
	// Make an array
	var array = [];
	// Add "amount" number of colours to array
	for(var i=0 ; i<amount ; i++){
		array.push(randomColour());
	}
	// Return array 
	return array;
}

function randomColour(){
	// Random red from 0 - 255
	var red = Math.floor(Math.random() * 256);
	// Random green from 0 - 255
	var green = Math.floor(Math.random() * 256);
	// Random blue from 0 - 255
	var blue = Math.floor(Math.random() * 256);
	var colour = "rgb(" + red + ", " + green + ", " + blue + ")";
	return colour;
}

The HTML for the game is:

<!DOCTYPE html>
<html>
<head>
	<title>Colour Game</title>
	<link rel="stylesheet" type="text/css" href="game.css">
</head>
<body>
	<h1>The Great <span id="winningColour">RGB()</span> Game!</h1>
	<div>
		<span id="message"></span>
	</div>
	<div id="container">
		<div class="square"></div>
		<div class="square"></div>
	 	<div class="square"></div>
	 	<div class="square"></div>
	 	<div class="square"></div>
	 	<div class="square"></div>
	</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>

The CSS for the game is:

body {
	background-color: #232323;
}

/* The container controls the size of 
the box that contains the squares */
#container {
	width: 50%;
	margin: 0 auto;
}

.square {
	width: 30%;
	background: purple;
	/* Square doesn't show up on 
	page so padding added */
	padding-bottom: 30%;
	float: left;
	margin: 1.66%;

}

h1 {
	color: white;
}

span {
	color: white;
}

Leave a Comment

Your email address will not be published. Required fields are marked *