-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
100 lines (79 loc) · 2.45 KB
/
Copy pathgame.js
File metadata and controls
100 lines (79 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
let score, round, totalRounds = 20;
let currentSymbol, locked;
let startTime;
let times;
function init(){
document.getElementById("startBtn").onclick = startGame;
document.getElementById("restartBtn").onclick = startGame;
document.getElementById("leftHalf").onclick = () => choose('left');
document.getElementById("rightHalf").onclick = () => choose('right');
}
function showScreen(id){
document.querySelectorAll('.screen').forEach(s=>s.classList.remove('active'));
document.getElementById(id).classList.add('active');
}
function startGame(){
score=0; round=0; times=[];
document.getElementById("score").textContent=0;
document.getElementById("progressBar").style.width="0%";
showScreen("gameScreen");
nextRound();
}
function nextRound(){
if(round>=totalRounds){ endGame(); return; }
round++;
document.getElementById("roundText").textContent="Runda "+round+" av "+totalRounds;
document.getElementById("progressBar").style.width=(round/totalRounds*100)+"%";
currentSymbol = Math.random()>0.5 ? "●" : "■";
document.getElementById("symbol").textContent=currentSymbol;
startTime = performance.now();
locked=false;
}
function choose(side){
if(locked) return;
locked=true;
let reaction = performance.now() - startTime;
times.push(reaction);
let correct = (currentSymbol==="●" && side==="left") ||
(currentSymbol==="■" && side==="right");
let half = document.getElementById(side==="left"?"leftHalf":"rightHalf");
if(correct){
score++;
document.getElementById("score").textContent=score;
half.classList.add("correct");
}else{
half.classList.add("incorrect");
}
setTimeout(()=>{
half.classList.remove("correct","incorrect");
nextRound();
},180);
}
function formatTime(ms){
if(ms < 1000) return Math.round(ms) + " ms";
return (ms/1000).toFixed(1).replace('.',',') + " sek";
}
function endGame(){
showScreen("endScreen");
let avg = times.reduce((a,b)=>a+b,0)/times.length;
document.getElementById("resultTitle").textContent =
score===20 ? "💪 20 av 20" : "Resultat";
document.getElementById("finalScore").textContent =
score + " poäng";
document.getElementById("averageTime").textContent =
"Genomsnitt: " + formatTime(avg);
let best = localStorage.getItem("best20");
if(score===20){
if(!best || avg < best){
localStorage.setItem("best20", avg);
best = avg;
}
}
if(best){
document.getElementById("bestTime").textContent =
"Bästa (20/20): " + formatTime(best);
}else{
document.getElementById("bestTime").textContent = "";
}
}
document.addEventListener("DOMContentLoaded", init);