Skip to content

Instantly share code, notes, and snippets.

@Oshawk
Last active October 10, 2018 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oshawk/7534a31d645f9bd4f44442fe23db32f9 to your computer and use it in GitHub Desktop.
Save Oshawk/7534a31d645f9bd4f44442fe23db32f9 to your computer and use it in GitHub Desktop.
Dice game
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
class Player {
constructor(playerNumber, onClickGlobal) {
this.tally = 0;
this.roll = null;
this.number = playerNumber;
this.onClickGlobal = onClickGlobal;
this.createElement();
this.createListener();
this.unhide();
}
createElement() {
this.button = document.createElement('button');
document.body.appendChild(this.button);
this.p = document.createElement('p');
document.body.appendChild(this.p);
}
createListener() {
this.button.addEventListener('click', () => {
this.hidden = true;
this.roll = Math.ceil(Math.random() * 6);
this.button.disabled = true;
this.button.innerHTML = `${this.roll}`;
this.onClickGlobal();
});
}
unhide() {
this.hidden = false;
this.roll = null;
this.button.disabled = false;
this.button.innerHTML = `Player ${this.number} Roll`;
this.p.innerHTML = `Score: ${this.tally}`;
}
}
function onClick() {
// Make sure all players have rolled.
allRolled = true;
players.forEach(function (player) {
if (!player.hidden) {
allRolled = false;
}
});
if (!allRolled) {
return;
}
// Get an array of winners.
winners = [];
players.forEach(function (player) {
if (!winners.length || player.roll == winners[0].roll) {
winners.push(player);
} else if (player.roll > winners[0].roll) {
winners = [player];
}
});
if (winners.length == 1) { // No draw.
winners[0].tally += 1;
info.innerHTML = `Player ${winners[0].number} wins with a roll of ${winners[0].roll}.`;
} else { // Draw.
info.innerHTML = 'It is a draw, roll again!';
}
newRound.disabled = false;
}
const numOfPlayers = 2;
var players = [];
for (var i = 1; i <= numOfPlayers; i++) {
players.push(new Player(i, onClick));
}
var newRound = document.createElement('button');
newRound.innerHTML = 'New Round';
newRound.disabled = true;
document.body.appendChild(newRound);
newRound.addEventListener('click', function() {
players.forEach(function (player) {
player.unhide();
});
newRound.disabled = true;
});
var info = document.createElement('h3');
document.body.appendChild(info);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment