Compare commits

...

3 Commits

2 changed files with 178 additions and 109 deletions

View File

@ -45,21 +45,21 @@
</div>
</div>
<div class="row mt-3">
<div class="col-sm border text-center p-2" id="col1">
<div class="col-sm border text-center p-2" id="currCpuCol">
<span class="h2" id="currentCpuTitle"></span>
<br>
<span class="h3">cpu score:</span>
<span class="h3" id="currentCpuScore" style="color: blue;"></span>
</div>
<div class="col-sm border text-center p-2" id="col2">
<div class="col-sm border text-center p-2" id="nextCpuCol">
<span class="h2" id="nextCpuTitle"></span>
<br>
<span class="h3">cpu score:</span>
<span class="h3 counter-count" id="nextCpuScore" style="color: blue;">?</span>
<br>
<button class="btn btn-lg bg-info m-3" onclick="btnHigherClick()" id="btnHigher">Higher</button>
<button class="btn btn-lg bg-info m-3" id="btnHigher">Higher</button>
<br>
<button class="btn btn-lg bg-info mb-3" onclick="btnLowerClick()" id="btnLower">Lower</button>
<button class="btn btn-lg bg-info mb-3" id="btnLower">Lower</button>
</div>
</div>
</div>
@ -69,10 +69,8 @@
</div> -->
<script type="module">
import {main, btnHigherClick, btnLowerClick} from "./game.js"
window.btnHigherClick = btnHigherClick
window.btnLowerClick = btnLowerClick
<script defer type="module">
import { main } from "./game.js"
main()
</script>
</body>

233
game.js
View File

@ -1,110 +1,181 @@
import { CountUp } from "https://cdnjs.cloudflare.com/ajax/libs/countup.js/2.6.0/countUp.min.js";
var cpuList;
var currentCpu;
var nextCpu;
class Ui {
#model;
// current user score
var score;
var highscore;
#scoreEl;
#highscoreEl;
function setHighscore(score) {
const currHighscore = localStorage.getItem("highscore_cpu")
if (currHighscore < score) {
localStorage.setItem("highscore_cpu", score)
highscore = score
}
#currCpuTitleEl;
#currCpuScoreEl;
#nextCpuTitleEl;
#nextCpuScoreEl;
#nextCpuStyle;
#btnHigher;
#btnLower;
constructor() {
this.#model = new Model();
}
export async function main() {
await fetch('./data.json')
.then((response) => response.json())
.then((json) => cpuList = json);
async init() {
await this.#model.init();
currentCpu = getRandomCpu();
nextCpu = getRandomCpu();
score = 0;
highscore = localStorage.getItem("highscore_cpu") ?? 0
updateLayout();
this.#scoreEl = document.getElementById("score");
this.#highscoreEl = document.getElementById("highscore");
this.#currCpuTitleEl = document.getElementById("currentCpuTitle");
this.#currCpuScoreEl = document.getElementById("currentCpuScore");
this.#nextCpuTitleEl = document.getElementById("nextCpuTitle");
this.#nextCpuScoreEl = document.getElementById("nextCpuScore");
this.#nextCpuStyle = document.getElementById("nextCpuCol").style;
this.#btnHigher = document.getElementById("btnHigher");
this.#btnLower = document.getElementById("btnLower");
this.#btnHigher.onclick = () => this.handleHigherPress();
this.#btnLower.onclick = () => this.handleLowerPress();
this.updateUiFromModel();
}
function getRandomCpu() {
let randomIndex = getRandomInt(0, cpuList.length)
return {
name: cpuList[randomIndex]["name"].split('@')[0],
score: cpuList[randomIndex]["cpuScore"]
}
async handleHigherPress() {
let result = this.#model.postAnswer('higher');
await this.animateTransition(result);
}
export function btnLowerClick() {
nextCpu.score < currentCpu.score ? showResult(true) : showResult(false);
async handleLowerPress() {
let result = this.#model.postAnswer('lower');
await this.animateTransition(result);
}
export function btnHigherClick() {
nextCpu.score > currentCpu.score ? showResult(true) : showResult(false);
updateUiFromModel() {
this.#scoreEl.innerText = this.#model.score;
this.#highscoreEl.innerText = this.#model.highscore;
this.#currCpuTitleEl.innerText = this.#model.currentCpu.name;
this.#currCpuScoreEl.innerText = new Intl.NumberFormat().format(this.#model.currentCpu.score);
this.#nextCpuTitleEl.innerText = this.#model.nextCpu.name;
}
function showResult(isCorrect) {
document.getElementById("btnHigher").setAttribute("disabled", "");
document.getElementById("btnLower").setAttribute("disabled", "");
async animateTransition(wasCorrect) {
this.updateUiFromModel();
this.#btnHigher.setAttribute("disabled", "");
this.#btnLower.setAttribute("disabled", "");
this.#nextCpuStyle.backgroundColor = wasCorrect ? "lightgreen" : "#FF4444";
document.getElementById("col2").style.backgroundColor = isCorrect ? "lightgreen" : "#FF4444";
if (!isCorrect) {
setHighscore(score)
}
score = isCorrect ? score + 1 : 0;
document.getElementById("score").innerText = score;
countUp();
}
// updates view based on the cpu objects
function updateLayout() {
document.getElementById("highscore").innerText = highscore;
document.getElementById("currentCpuTitle").innerText = currentCpu.name;
// add "." to large numbers
document.getElementById("currentCpuScore").innerText = new Intl.NumberFormat().format(currentCpu.score)
document.getElementById("nextCpuTitle").innerText = nextCpu.name;
document.getElementById("nextCpuScore").innerText = "?";
document.getElementById("col2").style.backgroundColor = "";
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function countUp() {
const options = {
startVal: nextCpu.score / 2,
startVal: this.#model.nextCpu.score / 2,
separator: '.',
decimal: ',',
duration: 2
};
let counter = new CountUp('nextCpuScore', nextCpu.score, options);
if (!counter.error) {
counter.start();
const counter = new CountUp(this.#nextCpuScoreEl, this.#model.nextCpu.score, options);
await new Promise(resolve => counter.start(resolve));
await this.#delay(500);
this.#model.nextRound();
this.updateUiFromModel();
this.#nextCpuStyle.backgroundColor = '';
this.#nextCpuScoreEl.innerText = '?';
this.#btnHigher.removeAttribute("disabled");
this.#btnLower.removeAttribute("disabled");
}
#delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
}
class Model {
#cpuList;
#currentCpu;
#nextCpu;
#tookGuessOnCurrent;
#score;
#highscore;
async init() {
const fetchResult = await fetch("./data.json");
this.#cpuList = await fetchResult.json();
this.#currentCpu = this.#getRandomCpu();
this.#nextCpu = this.#getRandomCpu();
this.#score = 0;
this.#highscore = localStorage.getItem("highscore_cpu") ?? 0;
this.#tookGuessOnCurrent = false;
}
get highscore() {
return this.#highscore;
}
get score() {
return this.#score;
}
get currentCpu() {
return this.#currentCpu;
}
get nextCpu() {
return this.#nextCpu;
}
get hasGuessed() {
return this.#tookGuessOnCurrent;
}
// Can be 'higher' or 'lower'
postAnswer(answer) {
if (this.#tookGuessOnCurrent) return false;
this.#tookGuessOnCurrent = true;
let answerWasCorrect = false;
if (answer === 'higher') {
answerWasCorrect = this.nextCpu.score > this.#currentCpu.score;
} else if (answer === 'lower') {
answerWasCorrect = this.nextCpu.score < this.#currentCpu.score;
}
if (answerWasCorrect) {
this.#score += 1;
return true;
} else {
counter.error(demo.error);
this.#updateHighscore(this.score)
this.#score = 0;
return false;
}
}
await delay(2500)
nextRound();
document.getElementById("btnHigher").removeAttribute("disabled");
document.getElementById("btnLower").removeAttribute("disabled");
nextRound() {
this.#currentCpu = this.#nextCpu;
this.#nextCpu = this.#getRandomCpu();
this.#tookGuessOnCurrent = false;
}
function nextRound() {
currentCpu = nextCpu;
nextCpu = getRandomCpu();
updateLayout();
#getRandomCpu() {
const item = this.#cpuList[Math.floor(Math.random() * this.#cpuList.length)];
return {
name: item["name"].split('@')[0],
score: item["cpuScore"]
};
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
#updateHighscore(newScore) {
if (newScore > this.#highscore) {
localStorage.setItem("highscore_cpu", newScore);
this.#highscore = newScore;
}
}
}
export async function main() {
const ui = new Ui();
await ui.init()
}