JavaScript RGB/Hex Color Game

jsnMy Projects0 Comments

I did this app a few months ago as part of a course to freshen up my javascript programming skills. The game is pretty simple, but while getting the game together I went through some core principles of the language:

– selectors
– event listeners
– variables scope
– dynamic style modification
– functions
– utilising various built-in methods

What is more, the game is responsive and fits different devices.

The game is played based on colors, generated in RGB, so a brief explanation of it would be useful.
What is RGB? RGB stands for “Red Green Blue” and is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue.

To form a color with RGB, three light beams (one red, one green, and one blue) must be combined. Each of the three beams is called a component of that color, and each of them can have an arbitrary intensity, from fully off – 0 to fully on – 255, in the mixture.

For example:
RGB(0, 0, 0) would be black – zero color intensity of each component.
RGB(255, 255, 255) would be white – full-color intensity of each component.
RGB(255, 0, 0) would be red – full red intensity and zero green and blue.
RGB(255, 255, 0) would be a combination of red and green – yellow
And so on, the values of each component, going from 0 to 255 together form a color.

How the game is played?
Depending on the game mode (easy/hard) you are given 3/9 sets of colored boxes. You have to guess which box the randomly generated RGB Color at the top is represented in.

How the game works?
The full code of the game is available at the bottom of the post, but here are two functions that might be useful and repurposed in other projects to create web design and development tools to convert colors.

RGB Generating function (random)

//Function to generate the rgb(x, x, x) string
function randomRGB(){
	var r = Math.floor(Math.random() * 255) + 0;
	var g = Math.floor(Math.random() * 255) + 0; 
	var b = Math.floor(Math.random() * 255) + 0;
	return "rgb("+r +", "+g+", "+b +")";
}

That color is then used to make the color of one of the 3 / 9 boxes. The remaining boxes are also randomly colored.

As an additional computation, the randomly generated main RGB color is converted to a hexadecimal one. Briefly Hexadecimal (also base 16, or just hex) is a positional numeral system. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen. Here are two additional functions that use the returned value from the RGB generating function above.

For example white in RGB is (255, 255, 255) and in HEX is #fffff

Here is how the RGB generated color is converted to HEX:

// Function to convert each number component into the hex code	
function componentToHex(c) {
   var hex = c.toString(16);
   return hex.length == 1 ? "0" + hex : hex;
	}
// combining the hex string from the converted components
function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
// slicing the rgb(number, number, number) string to 3 number variables and returning
// the hexed value
function hexedRGB(){
	var slicedRGB = randColor.substring(4, randColor.length - 1);
	var rgb = slicedRGB.split(',', 3);
	var r = Number(rgb[0]);
	var g = Number(rgb[1]);
	var b = Number(rgb[2]);
	return rgbToHex(r, g, b);
}

And that is the full code of the game:

var reset = document.querySelector("#reset");
var squares = document.querySelectorAll(".square");
var heading = document.querySelector("#rgbHeading");
var hexHeading = document.querySelector("#hexHeading");
var userMessage = document.querySelector("#userMessage")
var easy = document.querySelector("#easy")
var hard = document.querySelector("#hard")
var headerCol = document.querySelector("body");
var numSq = 6;
var colors = generateRandomColors(numSq);
var randColor = randomPicker();
var clickedCol;
heading.textContent = randColor;
hexHeading.textContent = hexedRGB();

//Initializing the game logic
gameLogic();

reset.addEventListener("click", function(){
	colors = generateRandomColors(numSq);
	init();
	reset.innerHTML = "<i class=\""+ "fa fa-refresh fa-2x\""+"aria-hidden="+"true>";
	gameLogic();
	resetAttr();
});

easy.addEventListener("click", function(){
	easy.classList.add("active");
	hard.classList.remove("active");
	numSq = 3
	colors = generateRandomColors(numSq);
	init();
	resetAttr();
	for(var i = 0; i < squares.length ; i++){
		if(colors[i]){
			squares[i].style.backgroundColor = colors[i];
		}
		else{
			squares[i].classList.add("hide");
		}
	}
	gameLogic();
});

hard.addEventListener("click", function(){
	hard.classList.add("active");
	easy.classList.remove("active");
	numSq = 6;
	colors = generateRandomColors(numSq);
	init();
	gameLogic();
	resetAttr();
	for(var i = 0; i < squares.length ; i++){
		squares[i].style.backgroundColor = colors[i];
		squares[i].classList.remove("hide");
		}
});

function init(){
	randColor = randomPicker();
	heading.textContent = randColor;
	hexHeading.textContent = hexedRGB();
	userMessage.textContent = "GUESS THE RGB";
}
// Function to reset the background colors
function resetAttr() {
	heading.setAttribute("style", "background-color: transparent");
	hexHeading.setAttribute("style", "background-color: transparent");
	userMessage.setAttribute("style", "background-color: transparent");
}
//Function that runs the game logic
function gameLogic(){
	for (var i = 0; i < squares.length; i++){
	squares[i].style.backgroundColor = colors[i];

	squares[i].addEventListener("click", function(){
		clickedCol = this.style.backgroundColor;
		if(clickedCol === randColor){
			userMessage.textContent = "Correct";
			updateColors(clickedCol);
			reset.textContent = "Play again?";
		}
		else {
			this.style.backgroundColor = "#2c3e50";
			this.setAttribute("style", "border: 3px solid #81cfe0");
			userMessage.textContent = "Try again";
		}
	});
}

}
//Function to update boxes and heading colors
function updateColors(color){
	for (var i = 0; i < squares.length; i++){
		squares[i].style.backgroundColor = color;
	}
	heading.setAttribute("style", "background-color: " +color+"");
	hexHeading.setAttribute("style", "background-color: " +color+"");
	userMessage.setAttribute("style", "background-color: " +color+"");
}
//Function to pick a random index from an array
function randomPicker(){
	randomGeneratedColor = colors[Math.floor(Math.random() * colors.length)];
	return randomGeneratedColor;
}
//Function to generate the random colors array
function generateRandomColors(num){
	array = [];
	for(var i = 0 ; i < num ; i++){
		array.push(randomRGB());
	}
	return array;
}
//Function to generate the rgb(x, x, x) string
function randomRGB(){
	var r = Math.floor(Math.random() * 255) + 0;
	var g = Math.floor(Math.random() * 255) + 0; 
	var b = Math.floor(Math.random() * 255) + 0;
	return "rgb("+r +", "+g+", "+b +")";
	 
}
// Function to convert each number component into the hex code	
function componentToHex(c) {
   var hex = c.toString(16);
   return hex.length == 1 ? "0" + hex : hex;
	}
// combining the hex string from the converted components
function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
// slicing the rgb(number, number, number) string to 3 number variables and returning
// the hexed value
function hexedRGB(){
	var slicedRGB = randColor.substring(4, randColor.length - 1);
	var rgb = slicedRGB.split(',', 3);
	var r = Number(rgb[0]);
	var g = Number(rgb[1]);
	var b = Number(rgb[2]);
	return rgbToHex(r, g, b);
}

The game is also available here.

Share this Post

Leave a Reply

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