Scoreboard: attempt to make a more universal javascript

This commit is contained in:
Neale Pickett 2019-10-24 22:21:42 -06:00
parent d5e7ce98c3
commit 9be527fa8f
4 changed files with 240 additions and 129 deletions

View File

@ -5,6 +5,9 @@ body {
background: #282a33;
color: #f6efdc;
}
body.wide {
max-width: 100%;
}
a:any-link {
color: #8b969a;
}

File diff suppressed because one or more lines are too long

View File

@ -4,130 +4,14 @@
<title>Scoreboard</title>
<link rel="stylesheet" href="basic.css">
<meta name="viewport" content="width=device-width">
<script>
function update(state) {
let element = document.getElementById("scoreboard");
let teamnames = state["teams"];
let pointslog = state["points"];
let highscore = {};
let teams = {};
// Every machine that's displaying the scoreboard helpfully stores the last 20 values of
// points.json for us, in case of catastrophe. Thanks, y'all!
//
// We have been doing some letiation on this "everybody backs up the server state" trick since 2009.
// We have needed it 0 times.
let pointshistory = JSON.parse(localStorage.getItem("pointshistory")) || [];
if (pointshistory.length >= 20){
pointshistory.shift();
}
pointshistory.push(pointslog);
localStorage.setItem("pointshistory", JSON.stringify(pointshistory));
// Dole out points
for (let i in pointslog) {
let entry = pointslog[i];
let timestamp = entry[0];
let teamhash = entry[1];
let category = entry[2];
let points = entry[3];
let team = teams[teamhash] || {__hash__: teamhash};
// Add points to team's points for that category
team[category] = (team[category] || 0) + points;
// Record highest score in a category
highscore[category] = Math.max(highscore[category] || 0, team[category]);
teams[teamhash] = team;
}
// Sort by team score
function teamScore(t) {
let score = 0;
for (let category in highscore) {
score += (t[category] || 0) / highscore[category];
}
return score;
}
function teamCompare(a, b) {
return teamScore(a) - teamScore(b);
}
// Figure out how to order each team on the scoreboard
let winners = [];
for (let i in teams) {
winners.push(teams[i]);
}
winners.sort(teamCompare);
winners.reverse();
// Clear out the element we're about to populate
Array.from(element.childNodes).map(e => e.remove());
let maxWidth = 100 / Object.keys(highscore).length;
for (let i in winners) {
let team = winners[i];
let row = document.createElement("div");
let ncat = 0;
for (let category in highscore) {
let catHigh = highscore[category];
let catTeam = team[category] || 0;
let catPct = catTeam / catHigh;
let width = maxWidth * catPct;
let bar = document.createElement("span");
bar.classList.add("category");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
}
let te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
function once() {
fetch("points.json")
.then(resp => {
return resp.json();
})
.then(obj => {
update(obj);
})
.catch(err => {
console.log(err);
});
}
function init() {
let base = window.location.href.replace("scoreboard.html", "")
document.querySelector("#location").textContent = base
setInterval(once, 60000);
once();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js" async></script>
<script src="scoreboard.js" async></script>
</head>
<body>
<h1 class="Success">Scoreboard</h1>
<body class="wide">
<h4 id="location"></h4>
<section>
<canvas id="chart"></canvas>
<div id="scoreboard"></div>
</section>
<nav>

224
theme/scoreboard.js Normal file
View File

@ -0,0 +1,224 @@
// jshint asi:true
chartColors = [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
]
function update(state) {
let element = document.getElementById("scoreboard")
let teamNames = state.teams
let pointsLog = state.points
// Every machine that's displaying the scoreboard helpfully stores the last 20 values of
// points.json for us, in case of catastrophe. Thanks, y'all!
//
// We have been doing some variation on this "everybody backs up the server state" trick since 2009.
// We have needed it 0 times.
let pointsHistory = JSON.parse(localStorage.getItem("pointsHistory")) || []
if (pointsHistory.length >= 20) {
pointsHistory.shift()
}
pointsHistory.push(pointsLog)
localStorage.setItem("pointsHistory", JSON.stringify(pointsHistory))
let teams = {}
let highestCategoryScore = {} // map[string]int
// Initialize data structures
for (let teamId in teamNames) {
teams[teamId] = {
categoryScore: {}, // map[string]int
overallScore: 0, // int
historyLine: [], // []{x: int, y: int}
name: teamNames[teamId],
id: teamId
}
}
// Dole out points
for (let entry of pointsLog) {
let timestamp = entry[0]
let teamId = entry[1]
let category = entry[2]
let points = entry[3]
let team = teams[teamId]
let score = team.categoryScore[category] || 0
score += points
team.categoryScore[category] = score
let highest = highestCategoryScore[category] || 0
if (score > highest) {
highestCategoryScore[category] = score
}
}
for (let entry of pointsLog) {
let timestamp = entry[0]
let teamId = entry[1]
let category = entry[2]
let points = entry[3]
let team = teams[teamId]
let score = team.categoryScore[category] || 0
score += points
team.categoryScore[category] = score
let overall = 0
for (let cat in team.categoryScore) {
overall += team.categoryScore[cat] / highestCategoryScore[cat]
}
team.historyLine.push({t: new Date(timestamp * 1000), y: overall})
}
// Compute overall scores based on current highest
for (let teamId in teams) {
let team = teams[teamId]
team.overallScore = 0
for (let cat in team.categoryScore) {
team.overallScore += team.categoryScore[cat] / highestCategoryScore[cat]
}
}
// Sort by team score
function teamCompare(a, b) {
return a.overallScore - b.overallScore
}
// Figure out how to order each team on the scoreboard
let winners = []
for (let teamId in teams) {
winners.push(teams[teamId])
}
winners.sort(teamCompare)
winners.reverse()
// Clear out the element we're about to populate
Array.from(element.childNodes).map(e => e.remove())
let maxWidth = 100 / Object.keys(highestCategoryScore).length
for (let team of winners) {
let row = document.createElement("div")
let ncat = 0
for (let category in highestCategoryScore) {
let catHigh = highestCategoryScore[category]
let catTeam = team.categoryScore[category] || 0
let catPct = catTeam / catHigh
let width = maxWidth * catPct
let bar = document.createElement("span")
bar.classList.add("category")
bar.classList.add("cat" + ncat)
bar.style.width = width + "%"
bar.textContent = category + ": " + catTeam
bar.title = bar.textContent
row.appendChild(bar)
ncat += 1
}
let te = document.createElement("span")
te.classList.add("teamname")
te.textContent = team.name
row.appendChild(te)
element.appendChild(row)
}
let datasets = []
for (let i in winners) {
if (i > 5) {
break
}
let team = winners[i]
let color = chartColors[i % chartColors.length]
datasets.push({
label: team.name,
backgroundColor: color,
borderColor: color,
data: team.historyLine,
lineTension: 0,
fill: false
})
}
let config = {
type: "line",
data: {
datasets: datasets
},
options: {
responsive: true,
scales: {
xAxes: [{
display: true,
type: "time",
time: {
tooltipFormat: "ll HH:mm"
},
scaleLabel: {
display: true,
labelString: "Time"
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: "Points"
}
}]
},
tooltips: {
mode: "index",
intersect: false
},
hover: {
mode: "nearest",
intersect: true
}
}
}
let ctx = document.getElementById("chart").getContext("2d")
window.myline = new Chart(ctx, config)
window.myline.update()
}
function once() {
fetch("points.json")
.then(resp => {
return resp.json()
})
.then(obj => {
update(obj)
})
.catch(err => {
console.log(err)
})
}
function init() {
let base = window.location.href.replace("scoreboard.html", "")
let location = document.querySelector("#location")
if (location) {
location.textContent = base
}
setInterval(once, 60000)
once()
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init)
} else {
init()
}