Today #day52 of #100daysofcode, I am coding and explaining 'Rock Paper Scissors' code project in JavaScript taught by @ania_kubow.
HTML
-
JavaScript
i. Target Event property
but[0].addEventListener('click',(e)=>document.write(e.target.innerHTML))
Explanation
Use innerHTML or id to target. [ ania_kubow used id, but I added my own idea here to export the button inner HTML instead of id]
target.innerHTML
possibleChoices.forEach(x => x.addEventListener('click',(e)=>{ userchoice = e.target.innerHTML userChoiceDisplay.innerHTML = userchoice }))
Now,
Let's generate a computer choice,
Create a function generatecomputerchoice and call this function inside the EventListener,
function generatecomputerchoice(){ }
ii. Random number
const p = [1,2,3]
let randomx = Math.random()
document.write(randomx)//
document.write(`<br>`)
let floorofx = Math.floor(randomx) //
document.write(floorofx)
document.write(`<br>`)
let y = randomx *3
document.write(y)
document.write(`<br>`)
y = Math.floor(randomx *3)
document.write(y)
Explanation
- Math.random() a random number generator will generate a number between zero and one which is a float type and to convert into an integer type use Math.floor method
Code: mathrandom[click]
Creating random number
const randomNumber = Math.floor(Math.random() * 3)+1 // or u can use possibleChoices.length
iii. Map()
A Map holds key-value pairs where the keys can be any datatype.
A Map remembers the original insertion order of the keys.
A Map has a property that represents the size of the map.
let n = 1
let choice = new Map([[1,'Rock'],[2,'paper'],[3,'Scissor']])
let res = choice.get(n)
console.log(res) //Rock
Code: mapget [click]
assign this random number, if 1 to rock.. using if the condition or advanced use map
if(randomNumber===1) computerChoice = 'Rock' or let rps = new Map([[1,'Rock'],[2,'Paper'],[3,'Scissor']])
or you can use
r = possibleChoices[0].innerHTML
to get rock ...let r = possibleChoices[0].innerHTML let p = possibleChoices[1].innerHTML let s = possibleChoices[2].innerHTML let rps = new Map([[1,r],[2,p],[3,s]]) //let rps = new Map([[1,'Rock'],[2,'Paper'],[3,'Scissor']])
now, export this computerChoice to computerChoiceDisplay which is holding the id computer-choice
computerChoiceDisplay.innerHTML = rpc.get(randomNumber)
Today, we have successfully taken user input and generated computer choices and displayed them.
Conclusion
Target Event property
Math.random()
Map()
Code