Sample code that shows how to make the popular game: Rock Paper Scissors. Make your choice by clicking on the appropriate icon and it will show who wins - you or the computer. This code was created during the shooting of the YouTube video, so it has not been tested for production purposes.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Rock Paper Scissors</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div id="game"></div>
<div id="score">
<div class="column">Won: <span id="won">0</span></div>
<div class="column">Lost: <span id="lost">0</span></div>
<div class="column">Draw: <span id="draw">0</span></div>
</div>
<div id="result"></div>
<style>
#game
{
margin:50px auto;
max-width:500px;
}
#game button
{
border:none;
opacity:0.8;
width:33.33%;
font-size:80px;
cursor:pointer;
background:transparent;
}
#game button:hover
{
opacity:1;
}
#score
{
font-size:26px;
max-width:500px;
min-height:32px;
margin:5px auto;
}
#score:before,
#score:after
{
content:'';
display:block;
clear:both;
}
.column
{
float:left;
width:33.33%;
text-align:center;
}
#result
{
font-size:30px;
margin:50px auto;
text-align:center;
min-height:75px;
}
</style>
<script>
var buttons =
[
{'name': 'Rock', 'icon': '✊🏻', 'beats': 'Scissors'},
{'name': 'Paper', 'icon': '✋🏻', 'beats': 'Rock'},
{'name': 'Scissors', 'icon': '✌🏻', 'beats': 'Paper'}
];
for(let i = 0; i < buttons.length; i++)
{
let button = document.createElement('button');
button.appendChild(document.createTextNode(buttons[i].icon));
document.getElementById('game').appendChild(button);
button.addEventListener('click', function() { choice(i); });
}
function choice(index)
{
let you = buttons[index];
let computer = buttons[Math.floor(Math.random() * buttons.length)];
let result = document.getElementById('result');
if(you.beats == computer.name)
{
increase('won');
result.innerHTML = 'You Won!<br>';
result.innerHTML += [you.icon, you.name, 'beats', computer.name, computer.icon].join(' ');
}
else if(computer.beats == you.name)
{
increase('lost');
result.innerHTML = 'You Lose!<br>';
result.innerHTML += [computer.icon, computer.name, 'beats', you.name, you.icon].join(' ');
}
else
{
increase('draw');
result.innerHTML = 'Draw!<br>';
result.innerHTML += [computer.icon, 'Nobody Wins', you.icon].join(' ');
}
}
function increase(id)
{
let element = document.getElementById(id);
element.innerHTML = Number(element.innerHTML) + 1;
}
</script>
</body>
</html>