Player color distribution
by phloe
HTML
<div id="playerChart"></div>
<p>
Players: <span id="playerCount"></span>
</p>
CSS
body {
background: #333;
color: #EEE;
font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif;
}
div {
width: 50vw;
height: 50vw;
min-width: 100px;
min-height: 100px;
}
JavaScript
const players = [];
window.players = players;
function create() {
let player;
if (players.length === 0) {
player = { hue: Math.random() * 360 };
}
else if (players.length === 1) {
player = { hue: (players[0].hue + 180) & 360 };
}
else {
const spaces = players.map((current, index) => Math.abs(current.hue - (players[(index + 1) % players.length].hue + ((index + 1) % players.length ? 0 : 360))));
const widestSpace = spaces.reduce((result, space) => Math.max(space, result), 0);
const widestIndex = spaces.indexOf(widestSpace);
console.log("spaces", spaces, "widestSpace", widestSpace, "widestIndex", widestIndex);
player = { hue: (players[widestIndex].hue + (widestSpace / 2)) % 360 };
}
players.push(player);
players.sort((a, b) => a.hue - b.hue);
console.log("players", players);
}
function update () {
const gradient = players.map((current, index) => {
const prev = players[(index || players.length) - 1];
const next = players[(index + 1) % players.length];
const stopStart = current.hue - Math.abs(prev.hue - current.hue) / 2;
const stopEnd = next.hue - Math.abs(current.hue - next.hue) / 2;
return `hsl(${current.hue}, 100%, 50%) ${stopStart}deg ${(stopEnd > stopStart) ? `${stopEnd}deg` : ""}`;
});
if (players.length && players[0].hue > 0) {
const prev = players[players.length - 1];
const current = players[0];
const stopStart = current.hue - Math.abs(prev.hue - current.hue) / 2;
gradient.unshift(`hsl(${prev.hue}, 50%, 50%) ${stopStart}deg`);
}
playerChart.style.backgroundImage = `conic-gradient(${gradient.join(", ")})`;
playerCount.innerText = players.length;
}
addEventListener("keydown", (event) => {
switch (event.key) {
case "Enter":
create();
update();
break;
case "Backspace":
players.pop();
update();
break;
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
break;
...