Today #Day57 of #100DaysOfCode, Completed coding and explaining the 'Rock Paper Scissors' code game project in JavaScript taught by [WebDevSimplified]
Note:
If You have followed my previous then use the 'Take Shortcut here' heading to continue,
HTML
let's create a div to hold three buttons,
<div class="selections"> <button class="selection">โ</button> <button class="selection">๐</button> <button class="selection">โ๏ธ</button> </div>
let's create a results div to hold the results section and a chid div to display you and span child to hold score,
<div class="results"> <div> You <span class="result-score">0</span> </div> <div> Computer <span class="result-score">0</span> </div>
Let's create a javascript file and use defer to load after our html page has loaded
<script src="/script.js" defer></script>
CSS
Let's center these selections div
.selections{ display: flex; justify-content: center; }
Let's Get rid of the buttons border and outline
.selection{ background: none; border: none; outline: none; cursor: pointer; font-size: 2em; }
Let's add a hover effect to these buttons and grow when hovered,
.selection:hover{ transform: scale(1.1); }
Let's center the results div
.results{ margin-top: 1rem; display: grid; justify-content: center; grid-template-columns: repeat(2,1fr); justify-items: center; align-items: center; }
Now, Let's Work on result-score section and make it smaller,
.result-score{ margin-left: .1rem; font-size: .5rem; color: #333; }
Then, Let's create a results selection div and in CSS differentiate between the winner and lost using opacity, but for now, comment it out because we will create these elements dynamically when a user makes a selection,
Tip: Use
Ctrl+/
to comment out multiple lines after selection..result-selection{ opacity: .5; } .result-selection.winner{ opacity: 1; font-size: 1.5rem; }
JavaScript
Let's Move on to JS,
- Before we move on, Let's add data attribute to buttons in HTML,
<button class="selection" data-selection="rock">โ</button>
<button class="selection"data-selection="paper">๐</button>
<button class="selection"data-selection="scissor">โ๏ธ</button>
- After that, Let's create a selection buttons const variable and pick all the data selection attributes using query selector,
const selectionButtons = document.querySelectorAll('[data-selection]')
- Next, let's add an add event listener for each button and access our data attribute given to the element in JS using dataset object and keyname property here the keyname is selection
selectionButtons.forEach(selectionButton => {
selectionButton.addEventListener('click', (e) => {
const selectionName = selectionButton.dataset.selection
makeSelection(selectionName)
})
});
- Now, Let's Create a makeSelection function and call it the above code to append it to click and write console log to check whether it is working or not
function makeSelection(selection) {
console.log(`You Clicked ${selection}`)
}
Take Shortcut here,
- Now, let's Define an array,
const SELECTION = [
{
name: 'rock',
emoji: 'โ',
beats: 'scissor'
},
{
name: 'paper',
emoji: '๐',
beats: 'rock'
},
{
name: 'scissor',
emoji: 'โ๏ธ',
beats: 'paper'
}
]
Array find() Method
let x = [1,2,3,4,5]
console.log(x.find((num)=>num == 7)) //null
console.log(x.find((num)=>num == 6)) //null
console.log(x.find((num)=>num == 5)) // 5
Code: Array find() Method [click]
- Then, Let's find the dataset key name in selection array using the array find a method,
const selection = SELECTION.find(selection => selection.name == selectionName)
- Next, Let's define computer selection,
function randomSelection(){
const randomIndex = Math.floor(Math.random() * SELECTION.length)
return SELECTION[randomIndex]
}
Function return
let x = ['a','b','c','d','e']
let str = (num,str)=>{
return x[num] === str
}
console.log(str(0,'g')) //false
console.log(str(0,'a')) //true
Code: functionreturn [click]
- After that, let's decide who the winner is based on the selection, the below code will return only true or false as I have demonstrated in the above link.
function isWinner(selection,opponentSelection){
return selection.beats === opponentSelection.name
}
- Then, let's pass the selection and computer selection
const yourWinner = isWinner(selection,computerSelection)
const computerWinner = isWinner(computerSelection,selection)
- Now, let's define a function addselectionResult to display in HTML,
function addselectionResult(selection,winner){
}
- Then, let's call this addselectionResult function inside makeSelection function,
addselectionResult(computerSelection,computerWinner)
addselectionResult(selection,yourWinner)
- Then, add the following data attribute to computer div,
<div data-final-column>
Computer
<span class="result-score">0</span>]
</div>
- After that, define a const variable to hold this data attribute
const finslColumn = document.querySelectorAll('[data-final-column]')
- Now, add a div,
function addselectionResult(selection,winner){
finalColumn.after(div)
}
Understanding creating elements after a grid div element in JS
I will explain tomorrow how I visually want to explain what @WebDevSimplified said in his video at [click], for now, I am adding only JavaScript Code that I wrote now,
const button = document.querySelector('button')
const box1 = document.querySelector('.box2')
let i = 2
const color = ['#A555EC','#460C68','#F8F988','#FB2576']
button.addEventListener('click',()=>{
const div = document.createElement('div')
//classname = `box${i++}`
div.classList.add('box1')
div.innerText=i++
div.style.backgroundColor = color[Math.floor(Math.random() * color.length)]
box1.after(div)
}
Code: createdivafter [click]
- Then, Let's create a div like the one which we commented in HTML,
const div = document.createElement('div')
div.innerText = selection.emoji
div.classList.add('result-selection')
if(winner) div.classList.add('winner')
finalColumn.after(div)
- Now, Let's add score,
[<span class="result-score" data-your-score>0</span>]
- After that, Let's create a const variable to hold these data attributes,
const computerScorespan = document.querySelector('[data-your-score]')
const yourScorespan = document.querySelector('[data-computer-score]')
- Now, Let's create a function to incrementScore,
function incrementScore(ScoreSpan){
scoreSpan.innerText = parseInt(scoreSpan.innerText)+1
}
Writing My Own Code,
- Then, I added my own logic here instead of following what kyle @webdev did,
Since I am checking the winner when addselectionResult function is called, so I inserted computerScorespan argument and send it to addselectionResult function,
if (winner){
div.classList.add('winner')
incrementScore(scoreSpan)
}
Adding a feature to the Rock Paper Scissor Game,
- The Scores should be capped at 5, and should display the user lost or won and then reload,
function scoreCheck(){
if(yourScorespan.innerText >=5 || computerScorespan.innerText >=5 ){
console.log(yourScorespan.innerText,computerScorespan.innerText)
if(yourScorespan.innerText > computerScorespan.innerText){
alert(`Yay! You Won`)
window.location.reload()
}
else{
alert(`Sorry, You lost`)
window.location.reload()
}
}
}
Finally,
Completed coding and explaining the 'Rock Paper Scissors' code game project in JavaScript taught by [WebDevSimplified]. Thanks, Kyle.
Conclusion
HTML Span Tag
CSS Display Flex
CSS Hover
CSS Display Grid
HTML Data attribute
JS querySelector
Array forEach
addEventListener method
Array find() Method
Understanding creating elements after a grid div element in JS and
Finally, a lot of Function Calls
Code
Code: Array find() Method [click]
Code: functionreturn [click]
Code: createdivafter [click]
Final Rock Paper Scissor Code