Compare commits

...

7 Commits

8 changed files with 177 additions and 86 deletions

2
.gitignore vendored
View File

@ -1,2 +1,2 @@
src/countries.js countries.js
*.swp *.swp

View File

@ -1,12 +1,16 @@
all: countries.js all: countries.js
countries: countries/countries.json: .SUBMODULES
git submodule init
git submodule update
countries.js: countries countries.js: countries/countries.json .PHONY
python3 scripts/generate_countries_list.py countries/countries.json > countries.js python3 scripts/generate_countries_list.py countries/countries.json > countries.js
clean: clean:
rm -rf countries.js rm -rf countries.js
rm -rf countries rm -rf countries
.SUBMODULES:
git submodule init
git submodule update
.PHONY:

95
game.js
View File

@ -10,33 +10,48 @@ const answerDHTML = document.getElementById("answer_d");
const bodyHTML = document.getElementsByTagName("body")[0] const bodyHTML = document.getElementsByTagName("body")[0]
const incorrectAnswersTable = document.getElementById('incorrectAnswersTable'); const incorrectAnswersTable = document.getElementById('incorrectAnswersTable');
const correctAnswersTable = document.getElementById('correctAnswersTable'); const correctAnswersTable = document.getElementById('correctAnswersTable');
const guessCheckboxHTML = document.getElementById('guessCheckbox');
const previousQuestionAnswer = document.getElementById('previousQuestionAnswer'); const previousQuestionAnswer = document.getElementById('previousQuestionAnswer');
const previousQuestionText = document.getElementById('previousQuestionText'); const previousQuestionText = document.getElementById('previousQuestionText');
const regionListHTML = document.getElementById("regionList");
const resultsHTML = document.getElementById("results"); const resultsHTML = document.getElementById("results");
const scoreHTML = document.getElementById("score"); const scoreHTML = document.getElementById("score");
const settingsHTML = document.getElementById("settings"); const settingsHTML = document.getElementById("settings");
const selectorHTML = document.getElementById("region_selector");
const selectorResultsHTML = document.getElementById("selector_results");
const questionHTML = document.getElementById("question"); const questionHTML = document.getElementById("question");
const timeHTML = document.getElementById("time"); const timeHTML = document.getElementById("time");
var gameTimeStartTime = 0; var gameTimeStartTime = 0;
var gameTimeIntervalId = 0; var gameTimeIntervalId = 0;
var selectedRegion = null;
const guessCountry = () => guessCheckboxHTML.checked;
function updateTime() { const updateTime = () => {
const secondsPassed = ((new Date().getTime() - gameTimeStartTime.getTime())/1000) const secondsPassed = ((new Date().getTime() - gameTimeStartTime.getTime())/1000)
.toFixed(3); .toFixed(3);
timeHTML.innerHTML = secondsPassed; timeHTML.innerHTML = secondsPassed;
} }
const capitals_list = Object.values(countries).map(country => country.capital); const getMasterQuestionList = () => {
const regionList = [...new Set(Object.values(countries).map(country => country.region))] if(guessCountry()) return capitals
.concat([...new Set(Object.values(countries).map(country => country.subregion))]) return countries;
}
const getQuestionHTML = (state) => {
if(guessCountry())
return `what country is <span id="questionCapital">${state.question}</span> the capital of?`
return `what is the capital of <span id="questionCountry">${state.question}</span>?`
}
const answer_list = () => Object.values(getMasterQuestionList()).map(item => item.answer);
const regionList = () => [...new Set(Object.values(getMasterQuestionList()).map(item => item.region))]
.concat([...new Set(Object.values(getMasterQuestionList()).map(item => item.subregion))])
.concat([ALL_REGIONS]) .concat([ALL_REGIONS])
.sort(); .sort();
const date = new Date(); const date = new Date();
var questionList, selectorMatches, state; var questionList, state;
var resultsChart = new Chart( var resultsChart = new Chart(
document.getElementById('resultsChart'), document.getElementById('resultsChart'),
@ -64,12 +79,8 @@ var resultsChart = new Chart(
// set up game // set up game
function init() { function init() {
// generate question list // generate question list
var regex; questionList = Object.keys(getMasterQuestionList())
if (selectorHTML.value == "" || selectorHTML.value == ALL_REGIONS) regex = new RegExp(".*"); .filter(c => getMasterQuestionList()[c].region == selectedRegion || getMasterQuestionList()[c].subregion == selectedRegion)
else regex = new RegExp(selectorHTML.value, "gi");
questionList = Object.keys(countries)
.filter(c => countries[c].region.match(regex) || countries[c].subregion.match(regex))
.sort(() => Math.random()-0.5); .sort(() => Math.random()-0.5);
// set up state variable // set up state variable
@ -87,7 +98,7 @@ function init() {
answersHTML.style.display = ""; answersHTML.style.display = "";
settingsHTML.style.display = "none"; settingsHTML.style.display = "none";
questionHTML.onclick = deinit; questionHTML.onclick = deinit;
incorrectAnswersTable.innerHTML = "<tr> <th> country </th> <th> capital </th> <th> your answer </th> </tr>"; incorrectAnswersTable.innerHTML = "<tr> <th> question </th> <th> answer </th> <th> your answer </th> </tr>";
correctAnswersTable.innerHTML = "<tr> <th> country </th> <th> capital </th> </tr>"; correctAnswersTable.innerHTML = "<tr> <th> country </th> <th> capital </th> </tr>";
// start game // start game
@ -105,13 +116,12 @@ function deinit() {
answersHTML.style.display = "none"; answersHTML.style.display = "none";
resultsHTML.style.display = "none"; resultsHTML.style.display = "none";
settingsHTML.style.display = ""; settingsHTML.style.display = "";
questionHTML.innerHTML = "tap here or press enter to start"; questionHTML.innerHTML = "capitals_quiz - select a region to start!";
scoreHTML.innerHTML = "score"; scoreHTML.innerHTML = "score";
questionHTML.onclick = init; questionHTML.onclick = init;
timeHTML.innerHTML = "time"; timeHTML.innerHTML = "time";
questionList = null; questionList = null;
selectorMatches = []
state = { state = {
"score": 0, "score": 0,
"maxScore": 0, "maxScore": 0,
@ -131,12 +141,12 @@ function updateState() {
var newQuestion = questionList.pop(); var newQuestion = questionList.pop();
var options = [] var options = []
while (options.length < 4) { while (options.length < 4) {
var c = capitals_list[Math.floor(Math.random()*capitals_list.length)]; var c = answer_list()[Math.floor(Math.random()*answer_list().length)];
if (c !== countries[newQuestion].capital && !options.includes(c)){ if (c !== getMasterQuestionList()[newQuestion].answer && !options.includes(c)){
options.push(c); options.push(c);
} }
} }
options[Math.floor(Math.random()*4)] = countries[newQuestion].capital; options[Math.floor(Math.random()*4)] = getMasterQuestionList()[newQuestion].answer;
if (state.question) state.previousQuestion = { if (state.question) state.previousQuestion = {
"question": state.question, "question": state.question,
@ -145,7 +155,7 @@ function updateState() {
}; };
state.question = newQuestion; state.question = newQuestion;
state.options = options; state.options = options;
state.answer = countries[newQuestion].capital; state.answer = getMasterQuestionList()[newQuestion].answer;
} }
@ -160,7 +170,7 @@ function updateScreen(){
answerBHTML.getElementsByClassName("text")[0].innerHTML = state.options[1]; answerBHTML.getElementsByClassName("text")[0].innerHTML = state.options[1];
answerCHTML.getElementsByClassName("text")[0].innerHTML = state.options[2]; answerCHTML.getElementsByClassName("text")[0].innerHTML = state.options[2];
answerDHTML.getElementsByClassName("text")[0].innerHTML = state.options[3]; answerDHTML.getElementsByClassName("text")[0].innerHTML = state.options[3];
questionHTML.innerHTML = `what is the capital of <span id="questionCountry">${state.question}</span>?`; questionHTML.innerHTML = getQuestionHTML(state)
if (state.previousQuestion ) { if (state.previousQuestion ) {
previousQuestionAnswer.innerHTML = state.previousQuestion.answer; previousQuestionAnswer.innerHTML = state.previousQuestion.answer;
previousQuestionText.style.display = ""; previousQuestionText.style.display = "";
@ -222,7 +232,7 @@ function processClick(answer) {
}); });
state.userAnswer = null; state.userAnswer = null;
// change background color based on if answer was correct // change background color based on if answer was correct for 500ms
bodyHTML.classList.add(isAnswerCorrect ? "correct" : "incorrect") bodyHTML.classList.add(isAnswerCorrect ? "correct" : "incorrect")
setTimeout(() => bodyHTML.classList = [], 500) setTimeout(() => bodyHTML.classList = [], 500)
@ -231,27 +241,11 @@ function processClick(answer) {
} }
function setSelectorMatches(value){ function setRegion(region) {
const regex = new RegExp(selectorHTML.value, "gi"); selectedRegion = region
selectorMatches = regionList
.filter(region => region.match(regex))
displaySelectorMatches();
} }
// set up event listeners
function displaySelectorMatches(){
selectorResultsHTML.innerHTML = selectorMatches
.map(region => {
return `<div class="selector_result" onclick="setSelectorValue('${region}'); init()"> ${region} </div>`
})
.sort()
.join("");
}
function setSelectorValue(value) {
selectorHTML.value = value;
}
answerAHTML.addEventListener("click", () => processClick(0)); answerAHTML.addEventListener("click", () => processClick(0));
answerBHTML.addEventListener("click", () => processClick(1)); answerBHTML.addEventListener("click", () => processClick(1));
@ -269,17 +263,12 @@ document.addEventListener("keyup", e => {
if (e.code == "Enter" && !state.startedGame) init(); if (e.code == "Enter" && !state.startedGame) init();
}); });
selectorHTML.addEventListener("change", setSelectorMatches); // start game
selectorHTML.addEventListener("keyup", e => {
var topResult = document.getElementsByClassName("selector_result")[0]
if (e.code == "Enter" && selectorHTML.value === "") { init(); return; }
if (e.code == "Enter" && selectorHTML.value === topResult.innerHTML.trim()) { init(); return; }
if (e.code == "Enter") selectorHTML.value = topResult.innerHTML.trim();
setSelectorMatches();
});
deinit(); deinit();
selectorHTML.focus(); regionListHTML.innerHTML = regionList()
setSelectorMatches(); .map(region => {
return `<div class="regionListItem" onclick="setRegion('${region}'); init()"> ${region} </div>`
})
.sort()
.join("");

View File

@ -4,6 +4,11 @@
--c-color: var(--green); --c-color: var(--green);
--d-color: var(--blue); --d-color: var(--blue);
--question-country-color: var(--teal); --question-country-color: var(--teal);
--question-capital-color: var(--blue);
}
input {
font-family: inherit
} }
.correct { .correct {
@ -105,26 +110,99 @@ span#questionCountry {
background-color: var(--question-country-color); background-color: var(--question-country-color);
} }
#region_selector { span#questionCapital {
width: 100%; background-color: var(--question-capital-color);
background: var(--dark-bg);
font-size: 1.5em;
padding: 1em;
border: none;
border-radius: 0.25em;
box-sizing: border-box;
} }
#settings { #settings {
width: 100% width: 100%
} }
#selector_results { #regionList {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: center; justify-content: center;
} }
#settings .selector_result { #settings .regionListItem {
margin: 1em; padding: 1em;
transition: 0.5s;
} }
#settings .regionListItem:hover {
background: #d9d9d9;
color: black;
}
/* toggle switches */
/* https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_switch */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--question-country-color);
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: var(--question-capital-color);
}
input:focus + .slider {
box-shadow: 0 0 1px var(--blue);
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
#questionTypeSelector {
display: flex;
width: 100%;
align-items: center;
justify-content: space-around;
margin-top: 3em;;
margin-bottom: 3em;;
}

4
gohookr.sh Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
cd `dirname $0`
git pull
make

View File

@ -12,32 +12,39 @@
<body> <body>
<div id=game> <div id=game>
<div id="toprow"> <div id="toprow">
<p onclick="init()" id="question">you need javascript enabled to play this</p> <p id="question">you need javascript enabled to play this</p>
<div id="gameinfo"> <div id="gameinfo">
<p id="time">time</p> <p id="time">time</p>
<p id="score">score</p> <p id="score">score</p>
</div> </div>
</div> </div>
<div style="display: none" id="settings"> <div style="display: none" id="settings">
<input placeholder="select a region (tap or type to filter)" id="region_selector" type="text"> <div id="regionList"></div>
<div id="selector_results"></div> <div id="questionTypeSelector" >
<p>guess capital</p>
<label class="switch">
<input id="guessCheckbox" type="checkbox">
<span class="slider round"></span>
</label>
<p>guess country</p>
</div>
</div> </div>
<div style="display: none" id="answers"> <div style="display: none" id="answers">
<div class="answer" id="answer_a"> <div class="answer" id="answer_a">
<p class="letter" id="a">a</p> <p class="letter" id="a">1</p>
<p class="text">answer a text</p> <p class="text">answer 1 text</p>
</div> </div>
<div class="answer" id="answer_b"> <div class="answer" id="answer_b">
<p class="letter" id="b">b</p> <p class="letter" id="b">2</p>
<p class="text">answer b text</p> <p class="text">answer 2 text</p>
</div> </div>
<div class="answer" id="answer_c"> <div class="answer" id="answer_c">
<p class="letter" id="c">c</p> <p class="letter" id="c">3</p>
<p class="text">this sample text is longer than the rest</p> <p class="text">this sample text is longer than the rest</p>
</div> </div>
<div class="answer" id="answer_d"> <div class="answer" id="answer_d">
<p class="letter" id="d">d</p> <p class="letter" id="d">4</p>
<p class="text">answer d text</p> <p class="text">answer 4 text</p>
</div> </div>
<p id="previousQuestionText" style="display: none"> answer to previous question: <span id="previousQuestionAnswer"> </span></p> <p id="previousQuestionText" style="display: none"> answer to previous question: <span id="previousQuestionAnswer"> </span></p>
</div> </div>
@ -54,7 +61,7 @@
</div> </div>
</div> </div>
<p> built with ❤ and adequate amounts of care by <a href="https://alra.uk">alv</a></p> <p> built with ❤ and adequate amounts of care by <a href="https://alra.uk">alv</a></p>
<script type="text/javascript" src="countries.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="countries.js"></script>
<script type="text/javascript" src="game.js"></script> <script type="text/javascript" src="game.js"></script>
</body> </body>

View File

@ -18,20 +18,30 @@ def main(args):
with open(args.file) as fp: with open(args.file) as fp:
countries = json.load(fp) countries = json.load(fp)
r = {} country_list = {}
capital_list = {}
for country in countries: for country in countries:
if len(country['capital']) < 1 or country['capital'][0] == "" or not country['independent']: if len(country['capital']) < 1 or country['capital'][0] == "" or not country['independent']:
continue continue
r[country['name']['common']] = { country_list[country['name']['common']] = {
'capital': country['capital'][0], 'answer': country['capital'][0],
'region': country['region'],
'subregion': country['subregion'],
'languages': country['languages']
}
capital_list[country['capital'][0]] = {
'answer': country['name']['common'],
'region': country['region'], 'region': country['region'],
'subregion': country['subregion'], 'subregion': country['subregion'],
'languages': country['languages'] 'languages': country['languages']
} }
print('countries = ', end='') print('countries = ', end='')
print(json.dumps(r)) print(json.dumps(country_list), end=';')
print('capitals = ', end='')
print(json.dumps(capital_list))
return 0 return 0

View File

@ -33,4 +33,3 @@ body {
padding: 2em; padding: 2em;
} }
} }