window.addEventListener("DOMContentLoaded", () => {
const ctx = document.getElementById("scores");
const output = document.querySelector("#output");
const buttons = document.querySelectorAll("button");
buttons.forEach((button) => button.addEventListener("click", clicked));
const history = [];
const scores = {
p: 1,
c: 1
};
const scoreChart = displayScores(scores, ctx);
function clicked(event) {
const pthrow = event.target.id;
const cthrow = chooseThrow(history);
const winner = determineWinner(pthrow, cthrow);
const timestamp = Date.now();
const round = {
pthrow,
cthrow,
winner,
timestamp
};
history.push(round);
displayResult(scores, scoreChart, output, round);
}
});
function determineWinner(pthrow, cthrow) {
if (pthrow === cthrow) return "t";
else if (pthrow == "r") return cthrow == "p" ? "c" : "p";
else if (pthrow == "p") return cthrow == "s" ? "c" : "p";
else if (pthrow == "s") return cthrow == "r" ? "c" : "p";
}
function getThrowLabel(code) {
return {
r: "Rock",
p: "Paper",
s: "Scissors"
}[code];
}
function getResultLabel(code) {
return {
t: "tie.",
p: "win!",
c: "lose."
}[code];
}
function displayResult(scores, scoreChart, output, round) {
if (round.winner === "c") scores.c++;
if (round.winner === "p") scores.p++;
updateScores(scores, scoreChart);
displayText(output, round);
}
function displayScores(scores, ctx) {
return new Chart(ctx, {
type: "doughnut",
data: {
labels: ["Player", "Computer"],
datasets: [{
data: [scores.p, scores.c],
backgroundColor: ["rgb(255, 205, 86)", "rgb(255, 99, 132)"],
}, ],
},
options: {
rotation: 0.5 * Math.PI,
},
});
}
function updateScores(scores, chart) {
chart.data.datasets[0].data = [scores.p, scores.c];
chart.update();
}
function displayText(output, round) {
// TODO: yack about player history to make them think
output.append(`You threw ${getThrowLabel(round.pthrow)}
`);
output.append(`Computer threw ${getThrowLabel(round.cthrow)}
`);
output.append(`You ${getResultLabel(round.winner)}
`);
output.scrollTop = output.scrollHeight;
}
function chooseThrow(_history) {
// TODO: use history to choose a better throw?
// pick one at random
return ["r", "p", "s"][~~(Math.random() * 3)];
}
#scoresContainer {
position: relative;
height: 300px;
}
#output {
white-space: pre;
height: 72px;
overflow: hidden;
overflow-y: scroll;
scroll-behavior: smooth;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<h1>Roshambo</h1>
</div>
<div class="row">
<div class="eight columns">
<button id="r">Rock</button>
<button id="p">Paper</button>
<button id="s">Scissors</button>
<div class="row" id="output"></div>
</div>
<div class="four columns">
<h5>Scores</h5>
<div id="scoresContainer">
<canvas id="scores" width="100%" height="100%"></canvas>
</div>
</div>
</div>
</div>