How to solve a coding problem
Let's create a JavaScript Game and harness the power of logical thinking
Table of contents
- The Game
- My approach to solving a problem
- 1- crack down the design
- 2- Generate a random array of images:
- 3- create the design:
- 4- Check if the clicked number is Less than its previous sibling:
- check_numbers function
- 5- if task 4 is true Let's switch the numbers :
- 6- Check if the user sorted the numbers from 1 to 10:
- 7- Call the function to start the Game :
- HERE IS THE FULL CODE SOURCE
First, read the problem and try to solve it on your own. In this article, I will walk you through my methodology to solve a problem if you follow this approach You will have strong problem-solving skills πͺ.
The Game
We want to create a game that challenges the user to sort the numbers in the right order firstly we are going to have numbers from 1 to 9 in random order once the user clicks on a number is going to see if it previous sibling is greater than it if the condition is true the numbers should be switched, If the numbers are correctly sorted from 1 to 9 we should tell the user that he/she smart π§ in this article we simply going to show an alert.
Be creative and innovative there are hundreds of ways to solve a problem I will share with you my way, Feel free to add different functionalities or change the design as you desire
My approach to solving a problem
Let's divide this game into smaller tasks and solve each one on its own.
you will be surprised how easy it is and enjoyable π
But first Remember understanding the question is half the answer
1- crack down the design
As you see in the image we have a container div that contains three rows each row we have three numbers images that each one of which has a parent div
π« note that you could use other HTML tags to replace the div container with a section or main etc ... be creative π§
So how can we do that dynamically with JavaScript π€?? well that leads us to task number 2
2- Generate a random array of images:
Let's create a function called getDataImage which stores an array of the images of our numbers then we will randomize the array
function getDataImage(){
let table = []
for(let i = 1 ; i <= 9; i++){
table.push(`img${i}.jpeg`)
}
// Randomize the element of the array
for(let i in table){
let temp = table[i]
let randIndex = Math.floor(Math.random() * table.length);
table[i] = table[randIndex]
table[randIndex] = temp
}
return table
}
- First, I declared an array and named it a table
then I created a for loop that goes from 1 to 9 in each iteration the table will append a string.
-> When i = 1 the table will be ['img1.jpeg']
-> When i = 2 the table will be ['img1.jpeg' , 'img2.jpeg'] etc ...
Then I created a for loop that iterates over each element in the table array
each element will create a variable called temp that stores the value of the element at the index of i suppose i = 1
-> then temp = 'img1.jpeg'
->
randIndex
is a variable that stores a random index from 0 to the length of the array-> Then a table[randIndex] will generate a random element from our array
-> Then assign that random element to our current element
-> Then assign the value of temp to that table[randIndex]
using this method on each element in the table we successfully randomize the elements of the array which we will use later to build our entire game πThe
getDataImage()
returns a random array that stores the src of our imagesπ« suppose that we have a folder called images in the directory in which our index.html exists.
3- create the design:
function create(){
let SrcImages = getDataImage()
let containerDiv = document.createElement('div')
containerDiv.setAttribute('class','container')
document.body.appendChild(containerDiv)
for(i of SrcImages){
containerDiv.innerHTML += `<div><img src="images/${i}" /></div>`
}
})
}
The function Create() do exactly as its name indicates it creates the design.
SrcImages
variables will store the returned array from getDataImage() function that we created previously.document.createElement('div')
creates a div tag.containerDiv.setAttribute('class','container')
it's doing this <divclass="container"></div>
I added the class to style it later.document.body.appendChild(containerDiv)
add the div that we created into our HTML documentsAfter we set a for loop that goes through each element in our
SrcImages
array
-> Then it sets the HTML code<div><img src="images/${i}" /></div>
-> Suppose that the first element in
SrcImages
is 'img4.jpeg'Γ¬ so inside our container div we will have<div><img src="images/img4.jpeg" /></div>
The process keeps up until all the elements inSrcImages
are inserted in our container div so we will have random images.Well done we successfully created the design we just need the CSS and we've done it π.
body{ display: flex; justify-content: center; align-items: center; } img{ width: 100px; height: 100px; } .container{ display: grid; grid-template-columns: repeat(3, auto); margin-top: 100px; }
--> the
.container
sets three columns in each row.
Be creative and change the style to fit your need and creativity.
4- Check if the clicked number is Less than its previous sibling:
Place the below code at the end of create() function
document.querySelectorAll('.container > div').forEach(div => {
div.addEventListener('click',()=>{
check_numbers(div)
})
The above code selects all the divs that have <div class="container"></div>
as there parent
-> Then for each div it's going to add an event listener for a click that call check_numbers()
which we will see in a few seconds and give it that clicked div as its parameter
First, we will see a function called
extractTheNumberFromTheSource()
which takes the clicked div as a parameter and returns the number that is in the image which the user has clicked on :function extractTheNumberFromTheSource(div){ let clickedNumber = div.querySelector('img'); clickedNumber = clickedNumber.outerHTML return clickedNumber.substring(20,21) // exctract the number out of the src attribute }
-> clickedNumber stores take the image inside the clicked div.
->
clickedNumber.outerHTML
converts the image to a string so that we will be allowed to use string methods on the clickedNumber.-> Extract the number out of the src attribute.
π« you can do that with regular expressions as well (just to give you an insight)
check_numbers function
function check_numbers(element) { const clickedNumber = extractTheNumberFromTheSource(element) // check the previousElementSibling let previousSibling = element.previousElementSibling const previousSiblingNumber = extractTheNumberFromTheSource(previousSibling) }
-> clickedNumber stores the clicked number let's suppose that we clicked on**4 .**
-> previousSibling stores the previous div
-> previousSiblingNumber stores the number in the previous div let's suppose that number is 9 .
5- if task 4 is true Let's switch the numbers :
if(clickedNumber < previousSiblingNumber){ let temp = element.innerHTML element.innerHTML = previousSibling.innerHTML previousSibling.innerHTML = temp }
Remember that we supposed that we clicked on 4 and before it is 9
-> Therefore
clickedNumber = 4
andpreviousSiblingNumber = 9
The condition is true so we will enter the if statements.
we have the variable temp which stores the HTML inside our clicked div in our case is the 4 images which will have a code like that "<img src="images/img4.jpeg" />
"
-> element.innerHTML = previousSibling.innerHTML
This line takes the HTML content of the div before the clicked div (previous sibling) and assigns it to the HTML content of the clicked div (current element). This effectively replaces the content of the clicked div with the content of the div before it.
-> previousSibling.innerHTML = temp
This line assigns the HTML content stored in the temp
variable (which is the HTML code of the clicked image) to the HTML content of the div before the clicked div (previous sibling). This replaces the content of the div before the clicked div with the clicked image.
Well done now we switched the images successfully π
6- Check if the user sorted the numbers from 1 to 10:
function isGameWon(){
// array which stores the sorted source languages
let sortedArray = []
for(let i = 1 ; i <= 9 ; i++){
sortedArray.push(`img${i}.jpeg`)
}
// let's get the source image of all the images
let currentArray = []
document.querySelectorAll('.container img').forEach(img => {
currentArray.push(img.outerHTML.substring(17,26))
})
if(sortedArray.every((element, index)=> element === currentArray[index])){
return true
}
return false
}
The function isGameWon()
checks whether the game has been won by comparing the source image filenames of a set of images with a pre-defined sorted array of filenames. Here's how it works:
An empty array called
sortedArray
is created.A for loop is used to iterate from 1 to 9 (inclusive). Within the loop, the filenames
"img1.jpeg"
,"img2.jpeg"
, ...,"img9.jpeg"
are generated and pushed into thesortedArray
. This creates an array with the expected sorted order of image filenames.Another empty array called
currentArray
is created.The
document.querySelectorAll('.container img')
statement selects all the<img>
elements within elements having the class "container". TheforEach()
method is then called on the selected images.Within the
forEach()
loop, the.outerHTML
property is used to retrieve the HTML code of each image as a string. The.substring(17,26)
method is applied to extract the substring that represents the source filename from the HTML code. This substring is then pushed into thecurrentArray
.After iterating through all the images, the function checks if every element in the
sortedArray
is equal to the corresponding element in thecurrentArray
using the.every()
method. If this condition is true for all elements, it means that the images are in the expected sorted order, and the function returnstrue
, indicating that the game has been won.If the condition in the previous step is not satisfied for any element, the function returns
false
, indicating that the game has not been won yet.
So, the isGameWon()
function essentially compares the source filenames of the images in the "container" class with the expected sorted filenames to determine if the game has been won.
Put this line of code inside the check_numbers() function if(isGameWon()){
if(isGameWon()){
setTimeout(()=>{
alert('Yeahh you won buddy')
}, 500)
}
If isGameWon()
returns true an alert will be shown on the page after 500ms passes.
7- Call the function to start the Game :
Call the create()
function just before the end script tag to initialize the Game
Congratulations you created a Game Well done see you in my next articles
I work as a freelance software developer. I've got you covered if you need a web application, desktop application, automation solutions, or even SEO and design improvements for your existing page! ππ»β¨
Contact me at code-with-amine@gmail.com and letβs build what youβre looking for. π
HERE IS THE FULL CODE SOURCE
Don't forget to create a folder called images and download images of the numbers from the web and name each one of them depending on the number. For Example image of number 1 name it img1.jpeg etc ...
Follow me on Instagram
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
display: flex;
justify-content: center;
align-items: center;
}
img{
width: 100px;
height: 100px;
}
.container{
display: grid;
grid-template-columns: repeat(3, auto);
margin-top: 100px;
}
</style>
</head>
<body>
<script>
function getDataImage(){
let table = []
for(let i = 1 ; i <= 9; i++){
table.push(`img${i}.jpeg`)
}
// Randomize the element of the array
for(let i in table){
let temp = table[i]
let randIndex = Math.floor(Math.random() * table.length);
table[i] = table[randIndex]
table[randIndex] = temp
}
return table
}
function create(){
let SrcImages = getDataImage()
let containerDiv = document.createElement('div')
containerDiv.setAttribute('class','container')
document.body.appendChild(containerDiv)
for(i of SrcImages){
containerDiv.innerHTML += `<div><img src="images/${i}" /></div>`
}
document.querySelectorAll('.container > div').forEach(div => {
div.addEventListener('click',()=>{
check_numbers(div)
})
})
}
function check_numbers(element) {
const clickedNumber = extractTheNumberFromTheSource(element)
// check the previousElementSibling
let previousSibling = element.previousElementSibling
const previousSiblingNumber = extractTheNumberFromTheSource(previousSibling)
// check if the clicked number is less then it's prevoius sibling
if(clickedNumber < previousSiblingNumber){
let temp = element.innerHTML
element.innerHTML = previousSibling.innerHTML
previousSibling.innerHTML = temp
}
if(isGameWon()){
setTimeout(()=>{
alert('Yeahh you won buddy')
}, 500)
}
}
function stringifyObj(obj) {
return obj.outerHTML;
}
function extractTheNumberFromTheSource(div){
let clickedNumber = div.querySelector('img'); // take the image inside the cliked number
clickedNumber = stringifyObj(clickedNumber); // convert the returned html element into a string
return clickedNumber.substring(20,21) // extract the number out of the src attribute
}
function isGameWon(){
// array which stores the sorted source languages
let sortedArray = []
for(let i = 1 ; i <= 9 ; i++){
sortedArray.push(`img${i}.jpeg`)
}
// let's get the source image of all the images
let currentArray = []
document.querySelectorAll('.container img').forEach(img => {
currentArray.push(img.outerHTML.substring(17,26))
})
if(sortedArray.every((element, index)=> element === currentArray[index])){
return true
}
return false
}
create()
</script>
</body>
</html>