8 Commits

7 changed files with 201 additions and 89 deletions

3
.gitignore vendored
View File

@@ -81,3 +81,6 @@ TAGS
# settings
settings.py
rq_settings.py
# Generated word lists
wordlist/*.txt

View File

@@ -58,6 +58,7 @@ def get_game_id():
def is_valid_dictionary_word(word: str) -> bool:
"""Verify if `word` is in the dictionary provided."""
# Either we: [ ] strip all the endlines during file load, or [x] use the endline to search here
return f'{word}\n' in dictionary
@@ -74,7 +75,7 @@ def what_game():
return {'game': get_game_id()}
@app.get('/api/guess')
@app.get('/api/guess/{word}')
def handle_guess(word: Union[str, None] = None):
"""Handle incoming guess."""
current_game_id = get_game_id()
@@ -96,8 +97,8 @@ def handle_guess(word: Union[str, None] = None):
return {'game': current_game_id, 'hint': hint}
@app.get("/api/answer/{item_id}")
@app.get('/api/answer/{item_id}')
def read_item(item_id: int, guess: Union[str, None] = None):
"""Get the word item."""
"""Get the word for the current game."""
word = words[item_id].strip()
return {"item_id": item_id, "guess": guess, 'word': word}
return {'item_id': item_id, 'guess': guess, 'word': word}

View File

@@ -1,10 +0,0 @@
var clip = new Clipboard('.copy');
clip.on("success", function(e) {
document.getElementById('copyresults').innerHTML = '<p style="font-size:var(--small);opacity:50%">Copied! Share your results with friends.</p>';
e.clearSelection();
});
clip.on("error", function() {
document.getElementById('copyresults').innerHTML = '<p style="font-size:var(--small);opacity:50%">Error. Please copy manually...</p>';
});

View File

@@ -1,23 +0,0 @@
/* Original from alphaguess.com */
function go() {
window.timerID = window.setInterval(timer, 0);
}
function timer(){
var nextgame = document.getElementById('nextgame');
var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1, 0, 0, 0);
var diff = Math.floor((midnight - now)/1000);
var hoursRemain = Math.floor(diff/(60*60));
var minutesRemain = Math.floor((diff-hoursRemain*60*60)/60);
var secondsRemain = Math.floor(diff%60);
nextgame.innerHTML = '<span class="nextgame">'+addZero(hoursRemain)+':'+addZero(minutesRemain)+':'+addZero(secondsRemain)+' over</span>';
}
function addZero(num){
if(num <=9) return '0'+num;
else return num;
}
go();

View File

@@ -2,3 +2,11 @@ body {
background-color: #333;
color: #FFF;
}
button {
background-color: #FF9800;
color: #333;
border: 0;
padding: .2rem;
}

View File

@@ -0,0 +1,104 @@
/* API calls **/
async function doGuess(guessWord) {
Alpine.store('alfagok').loading = true;
Alpine.store('alfagok').guessError = null;
if (guessWord === '') {
console.log('Nothing filled in');
Alpine.store('alfagok').guessError = 'Vul een woord in';
return;
}
Alpine.store('alfagok').nrGuesses++;
if (Alpine.store('alfagok').startTime === '') {
console.log('Setting startTime to now');
}
let response = await fetch('/api/guess/' + guessWord);
let result = await response.json();
console.log(result);
Alpine.store('alfagok').loading = false;
if (result.error) {
console.log('Error occurred during guess');
if (result.error === 'Word not in dictionary') {
Alpine.store('alfagok').guessError = 'Woord komt niet in de woordenlijst voor';
}
return;
}
if (result.hint && result.hint === 'after') {
console.log('na');
Alpine.store('alfagok').guessesBefore.push(guessWord);
}
if (result.hint && result.hint === 'before') {
console.log('voor');
Alpine.store('alfagok').guessesAfter.push(guessWord);
}
if (result.hint && result.hint === 'it') {
console.log('gevonden');
Alpine.store('alfagok').winTime = 'yay';
}
}
/* Time formatting **/
function getFormattedTime(milliseconds) {
if (!Number.isInteger(milliseconds)) {
return '';
}
let seconds = Math.round((milliseconds) / 1000);
const hours = Math.floor(seconds / 3600);
seconds %= 3600;
const minutes = Math.floor(seconds / 60);
seconds %= 60;
const formattedTime = [];
if (hours) {
formattedTime.push(`${hours}h`);
}
if (minutes) {
formattedTime.push(`${minutes}m`);
}
if (seconds) {
formattedTime.push(`${seconds}s`);
}
return formattedTime.join(' ') || '0s';
}
/* Clipboard stuff **/
var clip = new Clipboard('.copy');
clip.on("success", function(e) {
document.getElementById('copyresults').innerHTML = '<p style="font-size:var(--small);opacity:50%">Gekopieerd! Deel je resultaat.</p>';
e.clearSelection();
});
clip.on("error", function() {
document.getElementById('copyresults').innerHTML = '<p style="font-size:var(--small);opacity:50%">Fout. Graag handmatig kopi&euml;ren...</p>';
});
/* Game timer, original from alphaguess.com **/
function go() {
window.timerID = window.setInterval(timer, 0);
}
function timer(){
var nextgame = document.getElementById('nextgame');
var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1, 0, 0, 0);
var diff = Math.floor((midnight - now)/1000);
var hoursRemain = Math.floor(diff/(60*60));
var minutesRemain = Math.floor((diff-hoursRemain*60*60)/60);
var secondsRemain = Math.floor(diff%60);
nextgame.innerHTML = '<span class="nextgame">'+addZero(hoursRemain)+':'+addZero(minutesRemain)+':'+addZero(secondsRemain)+' over</span>';
}
function addZero(num){
if(num <=9) return '0'+num;
else return num;
}
go();

View File

@@ -5,98 +5,127 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/game.css">
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('alfagok', {
gameID: 0,
loading: false,
winTime: null,
startTime: null,
nrGuesses: 0,
guessesBefore: [],
guessesAfter: [],
guessValue: '',
guessError: '',
async getGameID() {
this.loading = true;
console.log('Loading gameID...');
let response = await fetch('/api/game');
let result = await response.json();
console.log(result);
this.loading = false;
if (result.game) {
return this.gameID = result.game;
}
}
}),
Alpine.store('darkMode', {
init() {
this.on = window.matchMedia('(prefers-color-scheme: dark)').matches
},
on: false,
toggle() {
this.on = ! this.on
}
})
})
</script>
<div
id="container"
x-data="{
search: '',
items: ['foo', 'bar', 'baz'],
winTime: null,
startTime: null,
nrGuesses: 0,
guessesBefore: ['blah'],
guessesAfter: [],
guessValue: '',
gameID: 0,
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}"
x-data=""
>
<a href="/" x-cloak class="title">alfagok</a> <span class="puzzleno">puzzle #[[ gameID ]]<span id="nextgame"></span></span>
<div x-cloak x-if="guessesBefore.length || guessesAfter.length"><br></div>
<a href="/" x-cloak class="title">alfagok</a> <span class="puzzleno">puzzle #<span x-text="$store.alfagok.gameID"></span><span id="nextgame"></span></span>
<div x-cloak x-show="$store.alfagok.guessesBefore.length || $store.alfagok.guessesAfter.length"><br></div>
<div x-cloak class="instructions" x-else>
<p>Guess the word of the day. Each guess reveals where the word sits alphabetically.</p>
<p>Raad het woord van de dag. Elke gok geeft een hint over waar het woord zich in het alfabet bevindt.</p>
</div>
<center>
<ul>
<template x-for="item in guessesBefore" :key="item">
<template x-for="item in $store.alfagok.guessesBefore" :key="item">
<li x-text="item"></li>
</template>
</ul>
<input type="text" x-model="guessValue">
<p x-cloak>Je huidige gok is: <span x-text="guessValue"></span></p>
<input type="button" value="Doe een gok">
<input type="text" x-model="$store.alfagok.guessValue" @keyup.enter="doGuess($store.alfagok.guessValue)">
{# <p x-cloak>Je huidige gok is: <span x-text="$store.alfagok.guessValue"></span></p>#}
<button @click="doGuess($store.alfagok.guessValue)">Doe een gok</button>
<p x-show="$store.alfagok.guessError" x-text="$store.alfagok.guessError"></p>
<ul>
<template x-for="item in guessesAfter" :key="item">
<template x-for="item in $store.alfagok.guessesAfter" :key="item">
<li x-text="item"></li>
</template>
</ul>
<div>
<div v-if="winTime" class="win">
<div x-show="$store.alfagok.winTime" class="win">
<h3><b>Je hebt hem! 🎉</b></h3>
<p>Het woord van vandaag was <b x-text="guessValue"></b>.</p>
<p>Het woord van vandaag was <b x-text="$store.alfagok.guessValue"></b>.</p>
<div id="stats">
<div id="results">
<p><b x-data="{ message: '🧩 Puzzle #' + gameID }" x-text="message"></b></p>
<p x-data="{ message: '🤔 '+ nrGuesses + ' gokken' }" x-text="message"></p>
<p x-data="{ message: '⏱️ ' + getFormattedTime(winTime - startTime) '" x-text="message"></p>
<p><b x-data="{ message: '🧩 Puzzle #' + $store.alfagok.gameID }" x-text="message"></b></p>
<p x-data="{ message: '🤔 '+ $store.alfagok.nrGuesses + ' gokken' }" x-text="message"></p>
<p x-data="{ message: '⏱️ ' + getFormattedTime($store.alfagok.winTime - $store.alfagok.startTime) }" x-text="message"></p>
<p>🔗 <span style="color:var(--blue)">alfagok.diginaut.net</span></p>
</div>
</div>
<div id="copyresults"></div>
<button class="copy" data-clipboard-target="#results">
Tik om te kopi&euml;ren te delen ❤️
</button>
<div id="copyresults"></div>
<button class="copy" data-clipboard-target="#results">
Tik om te kopi&euml;ren en te delen ❤️
</button>
</div>
</div>
</center>
<input x-model="search" placeholder="Search...">
<ul>
<template x-for="item in filteredItems" :key="item">
<li x-text="item"></li>
</template>
</ul>
</div>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<button x-data @click="$store.darkMode.toggle()">Toggle Dark Mode</button>
<div x-data :class="$store.darkMode.on && 'bg-black'">...</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.12/clipboard.min.js" rel=preload></script>
<script src="/static/copy.js"></script>
<script src="/static/countdown.js"></script>
<script src="/static/game.js"></script>
<script>
document.addEventListener('alpine:initialized', () => {
//Alpine.store('alfagok').gameID = getGameID();
Alpine.store('alfagok').getGameID();
})
</script>
</body>
</html>