Merge pull request #94 from dirtbags/neale

Track Participant IDs
This commit is contained in:
int00h5525 2019-11-12 15:41:44 -06:00 committed by GitHub
commit ac242d0aa9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 603 additions and 146 deletions

View File

@ -8,5 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- A changelog
- Support for embedding Python libraries at the category or puzzle level
- Embedded graph in scoreboard
- Optional tracking of participant IDs
- New `notices.html` file for sending broadcast messages to players
### Changed
- Use native JS URL objects instead of wrangling everything by hand

View File

@ -224,8 +224,9 @@ sessionStorage.setItem("id", "devel-server")
},
)
url = urllib.parse.urlparse(self.path)
for pattern, function in self.endpoints:
result = parse.parse(pattern, self.path)
result = parse.parse(pattern, url.path)
if result:
self.req = result.named
seed = self.req.get("seed", "random")

7
theme/Chart.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

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

View File

@ -10,11 +10,18 @@
<body>
<h1 id="title">MOTH</h1>
<section>
<div id="messages"></div>
<div id="messages">
<div id="notices"></div>
</div>
<form id="login">
Team name: <input name="name">
<!--
<span id="pid">
Participant ID: <input name="pid"> (optional) <br>
</span>
-->
Team ID: <input name="id"> <br>
Team name: <input name="name"> <br>
<input type="submit" value="Sign In">
</form>

1
theme/moment.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -14,6 +14,13 @@ function toast(message, timeout=5000) {
)
}
function renderNotices(obj) {
let ne = document.getElementById("notices")
if (ne) {
ne.innerHTML = obj
}
}
function renderPuzzles(obj) {
let puzzlesElement = document.createElement('div')
@ -81,13 +88,26 @@ function renderPuzzles(obj) {
container.appendChild(puzzlesElement)
}
function heartbeat(teamId) {
function heartbeat(teamId, participantId) {
let noticesUrl = new URL("notices.html", window.location)
fetch(noticesUrl)
.then(resp => {
if (resp.ok) {
resp.text()
.then(renderNotices)
.catch(err => console.log)
}
})
.catch(err => console.log)
let url = new URL("puzzles.json", window.location)
url.searchParams.set("id", teamId)
if (participantId) {
url.searchParams.set("pid", participantId)
}
let fd = new FormData()
fd.append("id", teamId)
fetch("puzzles.json", {
method: "POST",
body: fd,
})
fetch(url)
.then(resp => {
if (resp.ok) {
resp.json()
@ -104,22 +124,27 @@ function heartbeat(teamId) {
})
}
function showPuzzles(teamId) {
function showPuzzles(teamId, participantId) {
let spinner = document.createElement("span")
spinner.classList.add("spinner")
sessionStorage.setItem("id", teamId)
if (participantId) {
sessionStorage.setItem("pid", participantId)
}
document.getElementById("login").style.display = "none"
document.getElementById("puzzles").appendChild(spinner)
heartbeat(teamId)
heartbeat(teamId, participantId)
setInterval(e => { heartbeat(teamId) }, 40000)
}
function login(e) {
e.preventDefault()
let name = document.querySelector("[name=name]").value
let id = document.querySelector("[name=id]").value
let teamId = document.querySelector("[name=id]").value
let pide = document.querySelector("[name=pid]")
let participantId = pide?pide.value:""
fetch("register", {
method: "POST",
@ -131,10 +156,10 @@ function login(e) {
.then(obj => {
if (obj.status == "success") {
toast("Team registered")
showPuzzles(id)
showPuzzles(teamId, participantId)
} else if (obj.data.short == "Already registered") {
toast("Logged in with previously-registered team name")
showPuzzles(id)
showPuzzles(teamId, participantId)
} else {
toast(obj.data.description)
}
@ -156,9 +181,10 @@ function login(e) {
function init() {
// Already signed in?
let id = sessionStorage.getItem("id")
if (id) {
showPuzzles(id)
let teamId = sessionStorage.getItem("id")
let participantId = sessionStorage.getItem("pid")
if (teamId) {
showPuzzles(teamId, participantId)
}
document.getElementById("login").addEventListener("submit", login)

1
theme/notices.html Normal file
View File

@ -0,0 +1 @@
<!-- notices.html: contents will be rendered verbatim in the puzzles overview. -->

File diff suppressed because one or more lines are too long

54
theme/puzzles.json Normal file
View File

@ -0,0 +1,54 @@
{
"__comment__": [
"This file is to help debug themes.",
"MOTHd will ignore it."
],
"codebreaking": [
[1,"37117e6b034696b86c6516477cc0bc60bc1e642e"],
[2,"546b586428979771b061608489327da4940086a7"],
[4,"6f2a33c93f56b4f29cc79e6576ba4d1000aa1756"],
[5,"c654fe263909b1940d7aad8c572363a0569c07c6"],
[6,"f30bd32bf940f2bb03506ec334d2d204efc4695b"],
[7,"128b119083b6ae70c380a8eb70ec6a518425e7af"],
[8,"edd4f57aeb565b3b053fa194f5e677cb77ef0285"],
[15,"9781863bca9f596972e2a10460932ec5ec6be3fe"]
],
"nocode": [
[1,"37117e6b034696b86c6516477cc0bc60bc1e642e"],
[2,"546b586428979771b061608489327da4940086a7"],
[3,"79c08697a1923da1118fd0c2e922b5d3899cabcc"],
[4,"6f2a33c93f56b4f29cc79e6576ba4d1000aa1756"],
[10,"bf4fae263bf6e4243b143f4ecd64e471f3ec75dd"],
[20,"9f374f6dac9f972fac4693099a7bfa7c535f7503"],
[30,"02de1196d43976b2d050c6c597f068623d2df201"],
[50,"9acb3af947cb4aa10a9c1221c04518f956cdc0d0"],
[80,"78f807ac44f3cbf537861e7cdf1ac53937e4ee47"],
[90,"6d537653aa599178c72528f7e1f2fbb36e6333f9"],
[100,"4f5982a3a7cc9b9af0320130132e8cab39a1fd2c"]
],
"sequence": [
[1,"37117e6b034696b86c6516477cc0bc60bc1e642e"],
[2,"546b586428979771b061608489327da4940086a7"],
[8,"edd4f57aeb565b3b053fa194f5e677cb77ef0285"],
[16,"a9ace4b773f045c422260edefaa8563dcd80ac59"],
[19,"f11ca0172451f37ba6f4d66ff9add80013480a49"],
[25,"0458533d28705548829e53d686215cc6fbeec8f5"],
[35,"91aac06bae090ae7d1699b5a78601ef8d29e9271"],
[50,"9acb3af947cb4aa10a9c1221c04518f956cdc0d0"],
[60,"bf84beed9e382268ab40d0113dfeb73c96aa919a"],
[100,"4f5982a3a7cc9b9af0320130132e8cab39a1fd2c"],
[200,"3b9b8993fe639cf0c19a58b39ebbf6077828887a"],
[300,"0f13c4d19bc5d2e10d43e8cd2e40f759e731cece"],
[400,"db7a59f313818fc9598969d2a0a04e21bd26697f"],
[500,"81c5389eb5406aa44053662f6482f246b8a12e0c"]
],
"steg": [
[1,"200e8cd902ba7304765c463f6ed1322bc25f3454"],
[2,"707328988c3986d450d8fe419eb49f078fb7998c"],
[3,"d0b336ad59cbcd4415ddf200c6c099db5c3fea1d"],
[4,"f071503b403ffee2b38e186e800bfd5dd28e8f0e"],
[5,"186f425fa5762ef37f874cc602fe0edc4325a5d2"],
[6,"c6527c3c30c4e6a33026192d358d83d259cd17a7"],
[10,"84973f77a1b14e4666f3d8a8bdeead7633c4ed56"]
]
}

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="moment.min.js" async></script>
<script src="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()
}