Compare commits

..

9 commits

8 changed files with 445 additions and 292 deletions

View file

@ -1,30 +1,46 @@
.timer {
font-size: 10em;
font-weight: bold;
text-align: center;
line-height: 1.2;
font-size: 10em;
font-weight: bold;
text-align: center;
line-height: 1.2;
}
@keyframes blinker {
50% {
opacity: 0.3;
}
50% {
opacity: 0.3;
}
}
.timer.my-turn {
color: #0f0;
animation: blinker 2s ease infinite;
color: #0f0;
animation: blinker 2s ease infinite;
}
.timer.over {
color: #f00;
animation: blinker 0.5s ease infinite;
color: #f00;
animation: blinker 0.5s ease infinite;
}
.timer.loading {
font-size: 2em;
margin: auto;
margin-bottom: 2.5em;
margin-top: 2.5em;
font-size: 2em;
margin: auto;
margin-bottom: 2.5em;
margin-top: 2.5em;
}
.first-details {
padding-top: var(--spacing);
border-bottom: var(--border-width) solid var(--accordion-border-color);
border-top: var(--border-width) solid var(--accordion-border-color);
}
:is(button, input[type="submit"], input[type="button"], [role="button"]).outline.invalid, input[type="reset"].outline {
--color: var(--form-element-invalid-border-color);
--background-color: transparent;
}
:is(button, input[type="submit"], input[type="button"], [role="button"]).invalid, input[type="reset"] {
--background-color: var(--form-element-invalid-border-color);
--border-color: var(--form-element-invalid-border-color);
cursor: pointer;
}

View file

@ -1,73 +1,98 @@
<!doctype html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script src="index.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
<link rel="stylesheet" href="index.css">
<script src="js/index.js"></script>
<script src="js/localState.js"></script>
<script src="js/remoteState.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css" />
<link rel="stylesheet" href="index.css" />
</head>
<body>
<main class="container">
<div x-data>
<div x-show="$store.localState.joined">
<div x-show="$store.remoteState.connected && $store.localState.room">
<hgroup>
<h1
x-text="'Currently playing: ' + ($store.remoteState.isMyTurn ? 'YOU!':$store.remoteState.players[$store.remoteState.currentPlayer])">
x-text="'It\'s ' + ($store.remoteState.isMyTurn ? 'YOUR':($store.remoteState.players[$store.remoteState.currentPlayer] + '\'s')) + ' turn!'">
</h1>
<h2 x-text="'You are ' + $store.localState.name"></h2>
<h2>You are <b x-text="$store.localState.name"></b> in the room <b
x-text="$store.localState.room"></b></h2>
</hgroup>
<div x-data="Timer">
<div x-show="!time">
<div class="timer loading" href="#" aria-busy="true">please wait</div>
</div>
<div x-show="time">
<p :class="'timer' + ($store.remoteState.isMyTurn ? ' my-turn':'') + (time < 0 ? ' over':'')"
x-text="time + 's'"></p>
</div>
</div>
<button @click="$store.remoteState.giveTurnToNextPlayer()"
x-bind:disabled="$store.remoteState.currentPlayer !== $store.localState.id">I'm done!</button>
x-bind:disabled="$store.remoteState.currentPlayer !== $store.localState.id">
I'm done!
</button>
<label for="nextPlayer_select">Player after me: <b
x-text="$store.remoteState.players[$store.localState.nextPlayer]"></b> </label>
<select x-model="$store.localState.nextPlayer" id="nextPlayer_select">
<template
x-for="playerId in Object.keys($store.remoteState.players).filter(id => id != $store.localState.id)"
:key="playerId">
<option x-bind:value="playerId" x-text="$store.remoteState.players[playerId]"></option>
</template>
</select>
<details class="first-details">
<summary>Options</summary>
<fieldset>
<label for="sound_enabled">
<input x-model="$store.audio.isEnabled" @click="$store.audio.testPermission()" type="checkbox" id="sound_enabled" name="sound_enabled" role="switch">
Enable sound
</label>
</fieldset>
<div class="grid">
<button class="secondary outline" @click="$store.localState.leave()">Leave</button>
<button class="secondary outline" @click="$store.remoteState.clear()">Clear</button>
</div>
<fieldset>
<label for="nextPlayer_select">Player after me:
<b x-text="$store.remoteState.players[$store.localState.nextPlayer]"></b>
</label>
<select x-model="$store.localState.nextPlayer" id="nextPlayer_select">
<template
x-for="playerId in Object.keys($store.remoteState.players).filter(id => id != $store.localState.id)"
:key="playerId">
<option x-bind:value="playerId" x-text="$store.remoteState.players[playerId]"></option>
</template>
</select>
<p>Other players:</p>
<ul>
<template x-for="playerId in Object.keys($store.remoteState.players)" :key="playerId">
<li x-text="$store.remoteState.players[playerId]"></li>
</template>
</ul>
<label for="sound_enabled">
<input x-model="$store.audio.isEnabled" @click="$store.audio.testPermission()"
type="checkbox" id="sound_enabled" name="sound_enabled" role="switch" />
Enable sound
</label>
</fieldset>
<button class="invalid outline" @click="$store.localState.leave()" type="submit">
Leave room
</button>
</details>
<details>
<summary>This room</summary>
<label for="roomForm_interval">Interval (seconds):</label>
<input id="roomForm_interval" type="number" x-model.throttle.1000ms="$store.remoteState.interval"
placeholder="Interval" />
<p>
Other players:
<ul>
<template x-for="playerId in Object.keys($store.remoteState.players)" :key="playerId">
<li x-text="$store.remoteState.players[playerId]"></li>
</template>
</ul>
</p>
<button class="secondary outline" @click="$store.remoteState.clear()">
Clear player list
</button>
</details>
</div>
<div x-show="!$store.localState.joined">
<div x-show="!$store.remoteState.connected && $store.localState.room">
<h1 class="timer loading" aria-busy="true">Connecting...</h1>
</div>
<div x-show="!$store.localState.room">
<form x-data="JoinForm()" @submit.prevent="submitForm">
<input type="text" x-model="formData.name" placeholder="Name">
<input type="text" x-model="formData.name" placeholder="Name" />
<input type="text" x-model="formData.room" placeholder="Room" />
<button type="submit">Join</button>
</form>
</div>

234
index.js
View file

@ -1,234 +0,0 @@
function JoinForm() {
return {
formData: {
name: ""
},
submitForm() {
Alpine.store("localState").join(this.formData.name)
}
}
}
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
function Timer() {
return {
time: 0,
init() {
setInterval(() => {
const lastPlayerSwitch = Alpine.store("remoteState").lastPlayerSwitch
console.log(lastPlayerSwitch)
if(!lastPlayerSwitch) {
this.time = null
}
else {
this.time = parseInt((90000 - ((new Date()).getTime() - lastPlayerSwitch)) / 1000);
}
}, 100);
},
}
}
document.addEventListener('alpine:init', () => {
console.log("Alpine.js is ready to go!")
Alpine.store("localState", {
joined: false,
nextPlayer: null,
name: "",
id: "",
init() {
Alpine.effect(() => {
if (this.joined) {
Alpine.store("remoteState").connect();
}
})
this.restore();
},
join(name) {
this.joined = true;
this.name = name;
this.id = uuidv4();
localStorage.clear();
localStorage.setItem("joined", this.joined)
localStorage.setItem("name", this.name);
localStorage.setItem("id", this.id)
},
leave() {
this.joined = false;
this.name = "";
localStorage.clear();
localStorage.setItem("id", this.id)
Alpine.store("remoteState").disconnect();
},
restore() {
const joined = localStorage.getItem("joined");
if (joined) {
this.joined = true;
this.name = localStorage.getItem("name");
this.id = localStorage.getItem("id");
}
},
})
Alpine.store("remoteState", {
players: [],
currentPlayer: null,
lastPlayerSwitch: null,
connected: false,
isMyTurn: false,
_client: null,
init() {
Alpine.effect(() => {
if (this.connected && Object.keys(this.players).indexOf(Alpine.store("localState").id) === -1) {
this._client.publish('im.dorian.whos-turn-is-it.players', JSON.stringify({
[Alpine.store("localState").id]: Alpine.store("localState").name,
...this.players
}), { qos: 1, retain: true })
}
})
Alpine.effect(() => {
if (this.currentPlayer == Alpine.store("localState").id) {
this.isMyTurn = true;
}
else {
this.isMyTurn = false;
}
})
Alpine.effect(() => {
if (Alpine.store("localState").nextPlayer == null || Alpine.store("localState").nextPlayer == Alpine.store("localState").id || !Object.keys(this.players).includes(Alpine.store("localState").nextPlayer)) {
const players = Object.keys(this.players).sort();
const nextPlayer = players[(players.indexOf(Alpine.store("localState").id) + 1) % players.length]
Alpine.store("localState").nextPlayer = nextPlayer;
}
})
Alpine.effect(() => {
if (this.isMyTurn) {
Alpine.store("audio").playDing()
}
})
},
connect() {
const url = 'wss://broker.emqx.io:8084/mqtt'
const options = {
// Clean session
clean: true,
connectTimeout: 4000,
// Authentication
clientId: Alpine.store("localState").id,
}
this._client = mqtt.connect(url, options)
const client = this._client;
this._client.on('connect', function () {
// Subscribe to a topic
client.subscribe('im.dorian.whos-turn-is-it.players')
client.subscribe('im.dorian.whos-turn-is-it.currentPlayer')
})
this._client.on('message', function (topic, message) {
// message is Buffer
console.log(topic, message.toString())
if (topic === "im.dorian.whos-turn-is-it.players") {
const data = JSON.parse(message.toString());
if (!Alpine.store("remoteState").connected) {
Alpine.store("remoteState").connected = true;
}
Alpine.store("remoteState").players = data;
}
else if (topic === "im.dorian.whos-turn-is-it.currentPlayer") {
const data = JSON.parse(message.toString());
Alpine.store("remoteState").currentPlayer = data.id;
Alpine.store("remoteState").lastPlayerSwitch = data.since;
}
})
},
giveTurnToNextPlayer() {
this._client.publish('im.dorian.whos-turn-is-it.currentPlayer', JSON.stringify({
id: Alpine.store("localState").nextPlayer,
since: new Date().getTime()
}), { qos: 1, retain: true })
},
disconnect() {
this._client.end(true);
},
clear() {
this._client.publish('im.dorian.whos-turn-is-it.players', JSON.stringify({
[Alpine.store("localState").id]: Alpine.store("localState").name,
}), { qos: 1, retain: true })
this._client.publish('im.dorian.whos-turn-is-it.currentPlayer', JSON.stringify({
id: Alpine.store("localState").id,
since: new Date().getTime()
}), { qos: 1, retain: true })
}
})
Alpine.store("audio", {
hasBeenTested: false,
isAvailable: false,
isEnabled: false,
audioPlayer: null,
init() {
this.audioPlayer = new Audio('silence.mp3');
Alpine.effect(() => {
localStorage.setItem("audio_enabled", this.isEnabled)
})
},
testPermission() {
if (this.isEnabled) return;
this.audioPlayer.src = 'silence.mp3';
this.audioPlayer.play().then(() => {
this.isAvailable = true
this.isEnabled = localStorage.getItem("audio_enabled") === false ? false : true
this.hasBeenTested = true
}).catch((error) => {
console.warn("Audio permission not granted!")
this.isAvailable = false
this.isEnabled = false
this.hasBeenTested = true
})
},
playDing() {
if (!this.isEnabled) return;
this.playSound('ding.mp3')
},
playSound(soundFile) {
if (!this.audioPlayer.paused || !this.isAvailable) {
return;
}
if (!this.audioPlayer.src.endsWith(soundFile)) {
this.audioPlayer.src = soundFile;
}
this.audioPlayer.play();
},
})
})

112
js/index.js Normal file
View file

@ -0,0 +1,112 @@
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
}
function JoinForm() {
return {
formData: {
name: "",
room: "",
},
init() {
this.formData.name = Alpine.store("localState").name;
this.formData.room = Alpine.store("localState").room;
},
submitForm() {
Alpine.store("localState").join(this.formData.name, this.formData.room);
},
};
}
function RoomForm() {
return {
formData: {
interval: null,
},
init() {
this.formData.interval = Alpine.store("remoteState").interval;
},
submitForm() {
Alpine.store("remoteState").updateInterval(this.formData.interval);
},
};
}
function Timer() {
return {
time: 0,
init() {
setInterval(() => {
const lastPlayerSwitch = Alpine.store("remoteState").lastPlayerSwitch;
if (!lastPlayerSwitch) {
this.time = null;
} else {
this.time = Math.floor(
(Alpine.store("remoteState").interval * 1000 -
(new Date().getTime() - lastPlayerSwitch)) /
1000
);
}
}, 100);
},
};
}
document.addEventListener("alpine:init", () => {
console.log("Alpine.js is ready to go!");
Alpine.store("audio", {
hasBeenTested: false,
isAvailable: false,
isEnabled: false,
audioPlayer: null,
init() {
this.audioPlayer = new Audio("sound/silence.mp3");
Alpine.effect(() => {
localStorage.setItem("audio_enabled", this.isEnabled);
});
},
testPermission() {
if (this.isEnabled) return;
this.audioPlayer.src = "sound/silence.mp3";
this.audioPlayer
.play()
.then(() => {
this.isAvailable = true;
this.isEnabled =
localStorage.getItem("audio_enabled") === false ? false : true;
this.hasBeenTested = true;
})
.catch((error) => {
console.warn("Audio permission not granted!");
this.isAvailable = false;
this.isEnabled = false;
this.hasBeenTested = true;
});
},
playDing() {
if (!this.isEnabled) return;
this.playSound("sound/ding.mp3");
},
playSound(soundFile) {
if (!this.audioPlayer.paused || !this.isAvailable) {
return;
}
if (!this.audioPlayer.src.endsWith(soundFile)) {
this.audioPlayer.src = soundFile;
}
this.audioPlayer.play();
},
});
});

52
js/localState.js Normal file
View file

@ -0,0 +1,52 @@
document.addEventListener("alpine:init", () => {
Alpine.store("localState", {
room: null,
nextPlayer: null,
name: "",
id: "",
init() {
Alpine.effect(() => {
const remoteState = Alpine.store("remoteState");
if (this.room) {
remoteState.connect();
} else if (remoteState && remoteState.connected) {
remoteState.disconnect();
}
});
this.restore();
Alpine.effect(() => {
// write stuff to local storage
if (this.room) {
localStorage.setItem("room", this.room);
} else {
localStorage.removeItem("room");
}
localStorage.setItem("name", this.name);
localStorage.setItem("id", this.id);
});
},
join(name, room) {
this.room = room;
this.name = name;
},
leave() {
this.room = null;
},
restore() {
this.id = localStorage.getItem("id");
if (!this.id) {
this.id = uuidv4();
}
this.name = localStorage.getItem("name");
this.room = localStorage.getItem("room");
},
});
});

182
js/remoteState.js Normal file
View file

@ -0,0 +1,182 @@
document.addEventListener("alpine:init", () => {
Alpine.store("remoteState", {
players: [],
interval: null,
currentPlayer: null,
lastPlayerSwitch: null,
connected: false,
isMyTurn: false,
_client: null,
_currentPlayerTopic: null,
_gameStateTopic: null,
_lastGameState: null,
init() {
Alpine.effect(() => {
if (
this.connected &&
Object.keys(this.players).indexOf(Alpine.store("localState").id) ===
-1
) {
this._updatePlayers({
[Alpine.store("localState").id]: Alpine.store("localState").name,
...this.players,
});
}
});
Alpine.effect(() => {
if (this.currentPlayer == Alpine.store("localState").id) {
this.isMyTurn = true;
Alpine.store("audio").playDing();
} else {
this.isMyTurn = false;
}
});
Alpine.effect(() => {
if (
Alpine.store("localState").nextPlayer == null ||
Alpine.store("localState").nextPlayer ==
Alpine.store("localState").id ||
!Object.keys(this.players).includes(
Alpine.store("localState").nextPlayer
)
) {
const players = Object.keys(this.players).sort();
const nextPlayer =
players[
(players.indexOf(Alpine.store("localState").id) + 1) %
players.length
];
Alpine.store("localState").nextPlayer = nextPlayer;
}
});
Alpine.effect(() => {
if (this.connected) {
this.updateInterval(this.interval);
}
});
},
connect() {
const that = this;
const url = "wss://broker.emqx.io:8084/mqtt";
const topicPrefix = `im.dorian.whos-turn-is-it.${btoa(
Alpine.store("localState").room
)}`;
this._gameStateTopic = `${topicPrefix}.gameState`;
this._currentPlayerTopic = `${topicPrefix}.currentPlayer`;
const options = {
// Clean session
clean: true,
connectTimeout: 4000,
// Authentication
clientId: Alpine.store("localState").id,
};
this._client = mqtt.connect(url, options);
this._client.on("connect", () => {
setTimeout(() => {
if (!that.connected) {
// reset game if not connected after 5 seconds
that.clear();
}
}, 1000 * 5);
that._client.subscribe(that._gameStateTopic);
that._client.subscribe(that._currentPlayerTopic);
});
this._client.on("message", (topic, message) => {
// message is Buffer
console.log(topic, message.toString());
if (topic === that._gameStateTopic) {
const data = JSON.parse(message.toString());
if (!that.connected) {
that.connected = true;
}
that._lastGameState = data;
that.players = data.players;
that.interval = data.interval;
} else if (topic === that._currentPlayerTopic) {
const data = JSON.parse(message.toString());
that.currentPlayer = data.id;
that.lastPlayerSwitch = data.since;
}
});
},
giveTurnToNextPlayer() {
this._updateCurrentPlayer(Alpine.store("localState").nextPlayer);
},
disconnect() {
this._client.end(true);
this._client = null;
this.players = [];
this.currentPlayer = null;
this.lastPlayerSwitch = null;
this.connected = false;
this.isMyTurn = false;
this._gameStateTopic = null;
this._currentPlayerTopic = null;
Alpine.store("localState").nextPlayer = null;
},
clear() {
this._updatePlayers({
[Alpine.store("localState").id]: Alpine.store("localState").name,
});
this._updateCurrentPlayer(Alpine.store("localState").id);
},
updateInterval(interval) {
this._updateGameState(this.players, interval);
},
_updatePlayers(players) {
if (!this.interval) {
this.interval = 30;
}
this._updateGameState(players, this.interval);
},
_updateGameState(players, interval) {
const newGameState = {
version: 1,
players: players,
interval: interval,
};
if (
this._lastGameState &&
JSON.stringify(this._lastGameState) === JSON.stringify(newGameState)
)
return;
this._client.publish(this._gameStateTopic, JSON.stringify(newGameState), {
qos: 1,
retain: true,
});
},
_updateCurrentPlayer(id) {
this._client.publish(
this._currentPlayerTopic,
JSON.stringify({
id: id,
since: new Date().getTime(),
}),
{ qos: 1, retain: true }
);
},
});
});