Files
quickdraw-game/quickdraw-game.html
T

761 lines
27 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: sans-serif;
}
:root {
--bg: #161616;
}
html {
height: 100vh;
width: 100vw;
background-color: var(--bg);
font-size: 24px;
overflow-x: hidden;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
width: 100vw;
}
#frame {
width: 60%;
height: 75%;
/** border: 1px solid white; */
}
#center {
height: 50px;
width: 50px;
background-color: var(--bg);
border: 5px solid red;
border-radius: 50%;
position: absolute;
border-radius: 50%;
}
.target {
height: 50px;
width: 50px;
background-color: red;
position: absolute;
border-radius: 50%;
}
.target:active {
background-color: orange;
}
.hidden {
display: none;
opacity: 0;
}
.fade {
transition: opacity 1s;
}
.title {
font-weight: bold;
font-size: 2rem;
}
#title-container {
justify-self: center;
justify-content: center;
display: flex;
flex-direction: row;
width: 100%;
gap: 2rem;
}
#text-box {
display: flex;
flex-direction: column;
align-content: end;
justify-content: space-evenly;
gap: 1rem;
text-align: center;
color: red;
width: 100%;
min-height: 2rem;
line-height: 1rem;
margin-top: 2rem;
}
@media screen and (max-width: 750px) {
html {
font-size: 32px;
}
#text-box {
flex-direction: column;
align-items: center;
}
.text { font-size: .5rem; }
.title { font-size: 2rem; }
}
</style>
</head>
<body>
<div id="frame">
<!-- where the targets + bullseye are drawn -->
</div>
<!-- where we place text + buttons -->
<div id="text-box">
<!-- intro related -->
<div id="title-container">
<span id="title1" class="hidden title">QUICK</span>
<span id="title2" class="hidden title">DRAW</span>
</div>
<!-- gamemode menu buttons-->
<div id="game-modes" class="hidden fade">
<button id="normal" onclick="handleNormalMode()">normal</button>
<button id="countdown" onclick="handleCountdownMode()">countdown</button>
<!-- <button id="infinite">infinite</button> -->
</div>
<!-- pre-round text -->
<span id="game-text" class="hidden fade"></span>
<!-- post game buttons -->
<div id="game-over-buttons" class="hidden fade">
<button id="play-again" onclick="handlePlayAgain()">play again</button>
<button id="reset-game" onclick="handleReset()">back to main menu</button>
</div>
<!-- countdown text -->
<span id="ready" class="hidden title">READY?</span>
<span id="countdown3" class="hidden title">3</span>
<span id="countdown2" class="hidden title">2</span>
<span id="countdown1" class="hidden title">1</span>
<span id="draw" class="hidden title">DRAW!</span>
</div>
<script>
// SCREEN / SETUP VARIABLES
let gameBorderWidth = 1;
let targetWidth = 50;
let targetHeight = 50;
let pageHeight;
let pageWidth;
let frameElement;
let frameRect;
let frameHeight;
let frameWidth;
let center;
let ratio;
let xFrameAdjustment;
let yFrameAdjustment;
// UX HELPERS
let drawingCircle = false;
let needsResizeAdjustment = false;
// GAME STATE VARIABLES
let gamemode = ""; // can be: "normal", "countdown", "infinite"
let countingDown = false;
let hovering = false;
let hoverCount = 0; // number of times the cursor has hovered over bullseye. used to cleanly handle round starting / cancelling
let gameIsOver = false;
// GAMEPLAY VARIABLES
let targetsClicked = 0;
// "NORMAL" MODE ONLY VARIABLES
let currentRound = 0;
let totalTime = 0.0;
let roundSeconds = 0.0;
let roundTimeStart = 0;
let roundTimeEnd = 0;
let bestNormalTime = 0;
// "COUNTDOWN" MODE ONLY VARIABLES
let countdownTime = 0;
let bestCountdownScore = 0;
// menu / text elements
let titleContainer = document.getElementById("title-container");
let title1 = document.getElementById("title1");
let title2 = document.getElementById("title2");
let gameModes = document.getElementById("game-modes");
let gameText = document.getElementById("game-text");
let gameOverButtons = document.getElementById("game-over-buttons");
let ready = document.getElementById("ready");
let one = document.getElementById("countdown1");
let two = document.getElementById("countdown2");
let three = document.getElementById("countdown3");
let draw = document.getElementById("draw");
// setup initialization
window.addEventListener("load", initGame);
async function initGame() {
// determine screen parameters + listen for changes
setParameters();
window.addEventListener("resize", handlePageResize);
center = generateTarget(xFrameAdjustment, yFrameAdjustment);
center.id = "center";
document.body.insertAdjacentElement("afterbegin", center);
await drawTargetsInCircle(2);
if (needsResizeAdjustment) {
// auto-reset screen if page was resized during animation
handlePageResize();
}
await fadeMainMenuIn();
if (localStorage.getItem("bestNormalTime") != null) {
bestNormalTime = Number.parseFloat(localStorage.getItem("bestNormalTime"));
}
if (localStorage.getItem("bestCountdownScore") != null) {
bestCountdownScore = Number.parseInt(localStorage.getItem("bestCountdownScore"));
}
}
// helper function to determine screen-size + ratios for rendering targets
function setParameters(event) {
pageHeight = window.innerHeight;
pageWidth = window.innerWidth;
frameElement = document.getElementById("frame");
frameRect = frameElement.getBoundingClientRect();
frameHeight = frameElement.offsetHeight;
frameWidth = frameElement.offsetWidth;
// ratio = (frameHeight - (gameBorderWidth*2)) / (frameWidth - (gameBorderWidth*2));
ratio = frameHeight / frameWidth;
// adjustments to find center of frame in absolute coords (for origin of target cirlce)
xFrameAdjustment = ((frameWidth / 2) + frameRect.left) - (targetWidth / 2);
yFrameAdjustment = ((frameHeight / 2) + frameRect.top) - (targetWidth / 2);
// init logs:
console.log('page: ' + pageWidth + ' x ' + pageHeight);
console.log('frame: ' + frameWidth + ' x ' + frameHeight);
}
async function handlePlayAgain(e) {
gameIsOver = false;
// hide game over buttons
gameOverButtons.style.display = "none";
gameOverButtons.style.opacity = "0";
// remove game text from DOM flow
gameText.style.display = "none";
gameText.style.opacity = "0";
if (gamemode == "normal") {
handleNormalMode(e);
}
else if (gamemode == "countdown") {
handleCountdownMode(e);
}
else {
alert("cannot play again, gamemode does not exit?");
}
}
async function handleNormalMode(e) {
gamemode = "normal";
console.log("game mode: " + gamemode);
// setup mode parameters
currentRound = 1;
totalTime = 0;
await fadeMainMenuOut();
// set game instruction text + fade it in
gameText.innerText = "hover on middle circle to start the countdown,\nthen click the targets as fast as possible!";
gameText.style.opacity = "0";
gameText.style.display = "inline";
await sleep(500);
gameText.style.opacity = "100";
// enable player to start first round
center.addEventListener("mouseover", handleHoverStart);
center.addEventListener("mouseleave", handleHoverEnd);
}
async function handleCountdownMode(e) {
gamemode = "countdown";
console.log("game mode: " + gamemode);
await fadeMainMenuOut();
// set game instruction text + fade it in
gameText.innerText = "hover on middle circle to start the countdown,\nthen click as many targets as possible!";
gameText.style.opacity = "0";
gameText.style.display = "inline";
await sleep(500);
gameText.style.opacity = "100";
// enable player to start game
center.addEventListener("mouseover", handleHoverStart);
center.addEventListener("mouseleave", handleHoverEnd);
}
async function handleReset(e) {
gameIsOver = false;
gamemode = "";
currentRound = 0;
// hide buttons
gameOverButtons.style.display = "none";
gameOverButtons.style.opacity = "0";
// remove game text from DOM flow
gameText.style.display = "none";
gameText.style.opacity = "0";
// reintroduce main menu elements into DOM flow
await sleep(800);
await drawTargetsInCircle(2);
await fadeMainMenuIn();
}
async function handleHoverStart(e) {
hovering = true;
hoverCount++;
console.log('hover count: ' + hoverCount);
console.log('current round: ' + currentRound);
// remove all targets
frameElement.replaceChildren();
gameText.style.display = "none";
if (gamemode == "normal") {
await startNormalRound(currentRound);
}
else if (gamemode == "countdown") {
await startCountdownMode();
}
// if (infinityMode)
}
async function startCountdownMode() {
// if user cancels hover countdown, don't start round
if (!await normalModeRoundCountdown(hoverCount)) {
console.log("player canceled coundown");
return;
}
// setup mode parameters
targetsClicked = 0;
tempTargetsClicked = 0;
countdownTime = 15.0;
// clear screen + render countdown / score
center.remove();
gameText.innerText = countdownTime.toFixed(3) + "s\ntargets clicked: " + targetsClicked;
gameText.style.display = "inline";
gameText.style.opacity = "100";
// begin actual game loop!
randomTargetGenerator(1);
while (countdownTime > 0.0) {
gameText.innerText = countdownTime.toFixed(3) + "s\ntargets clicked: " + targetsClicked;
// auto-reset screen if page was resized during animation
if (needsResizeAdjustment) {
handlePageResize();
}
// generate new target if last one was clicked
if (targetsClicked != tempTargetsClicked) {
randomTargetGenerator(1);
tempTargetsClicked++;
}
countdownTime = countdownTime - .01;
await sleep(10);
}
gameIsOver = true;
// ensure no targets are still on screen after timer ends
frameElement.replaceChildren();
// show end of round text. if high score, alert player and save
if (targetsClicked > bestCountdownScore || bestCountdownScore == 0) {
if (bestCountdownScore == 0) {
alert("NEW HIGHEST SCORE!!! congratulations cowboy.");
}
else {
alert("NEW HIGHEST SCORE!!! previous best: " + bestCountdownScore + " targets. congratulations cowboy.");
}
bestCountdownScore = targetsClicked;
localStorage.setItem("bestCountdownScore", bestCountdownScore);
}
gameText.innerText = "TARGETS CLICKED: " + targetsClicked +
"\nHIGH SCORE: " + bestCountdownScore +
"\nhover on circle to go back to main menu..";
// bring bullseye back to screen
center = generateTarget(xFrameAdjustment, yFrameAdjustment);
center.id = "center";
document.body.insertAdjacentElement("afterbegin", center);
gameOverButtons.style.display = "flex";
gameOverButtons.style.opacity = "100";
}
async function startNormalRound(roundNumber) {
if (roundNumber > 3) {
handleReset({});
return;
}
// if user cancels hover countdown, don't start round
if (!await normalModeRoundCountdown(hoverCount)) {
console.log("player canceled coundown");
return;
}
let numTargets = 0;
if (roundNumber == 1) {
numTargets = 1;
}
else if (roundNumber == 2) {
numTargets = 3;
}
else if (roundNumber == 3) {
numTargets = 5;
}
// effectively begin the round
console.log("starting round " + roundNumber);
center.remove();
targetsClicked = 0;
roundTimeStart = Date.now();
randomTargetGenerator(numTargets);
while (targetsClicked < numTargets) {
await sleep(10);
if (targetsClicked == numTargets) break;
}
roundTimeEnd = Date.now();
roundSeconds = (roundTimeEnd - roundTimeStart) / 1000;
totalTime += roundSeconds;
currentRound++;
// bring bullseye back to screen
center = generateTarget(xFrameAdjustment, yFrameAdjustment);
center.id = "center";
document.body.insertAdjacentElement("afterbegin", center);
// ensure "DRAW" isn't still lingering on screen after round
draw.style.display = "none";
draw.style.opacity = "0";
if (roundNumber == 3) {
// GAME OVER STUFF
gameIsOver = true;
if (totalTime < bestNormalTime || bestNormalTime == 0) {
if (bestNormalTime == 0) {
alert("NEW FASTEST TIME!!! congratulations cowboy.");
}
else {
alert("NEW FASTEST TIME!!! previous best: " + bestNormalTime.toFixed(3) + "s. congratulations cowboy.");
}
bestNormalTime = totalTime;
localStorage.setItem("bestNormalTime", bestNormalTime);
}
gameText.innerText = "ROUND: " + roundSeconds.toFixed(3) +
"s\nTOTAL: " + totalTime.toFixed(3) +
"s\nBEST SCORE: " + bestNormalTime.toFixed(3);
gameOverButtons.style.display = "flex";
gameOverButtons.style.opacity = "100";
}
else {
console.log("ROUND: " + roundSeconds.toFixed(3) + "s\nTOTAL: " + totalTime.toFixed(3) + "\nhover on circle to start round " + currentRound);
gameText.innerText = "ROUND: " + roundSeconds.toFixed(3) + "s\nTOTAL: " + totalTime.toFixed(3) + "s\nhover on circle to start round " + currentRound;
center.addEventListener("mouseover", handleHoverStart);
center.addEventListener("mouseleave", handleHoverEnd);
}
gameText.style.display = "inline";
gameText.style.opacity = "100";
return;
}
/**
* HELPER TO KICK-OFF "NORMAL MODE" ROUNDS
*/
async function normalModeRoundCountdown(hoverNumber) {
gameText.style.display = "none";
countingDown = true;
// this if-check prevents countdown from continuing if user removes / reapplies hover while we're sleeping
if (!hovering || hoverNumber != hoverCount) return false;
ready.style.display = "inline";
ready.style.opacity = "100";
await sleep(1000);
if (!hovering || hoverNumber != hoverCount) return false;
ready.style.display = "none";
ready.style.opacity = "0";
if (!hovering || hoverNumber != hoverCount) return false;
one.style.opacity = "0";
two.style.opacity = "0";
three.style.opacity = "0";
if (!hovering || hoverNumber != hoverCount) return false;
one.style.display = "inline";
two.style.display = "inline";
three.style.display = "inline";
if (!hovering || hoverNumber != hoverCount) return false;
three.style.opacity = "100";
await sleep(500);
if (!hovering || hoverNumber != hoverCount) return false;
two.style.opacity = "100";
await sleep(500);
if (!hovering || hoverNumber != hoverCount) return false;
one.style.opacity = "100";
await sleep(500);
if (!hovering || hoverNumber != hoverCount) return false;
one.style.display = "none";
two.style.display = "none";
three.style.display = "none";
one.style.opacity = "0";
two.style.opacity = "0";
three.style.opacity = "0";
draw.style.display = "inline";
draw.style.opacity = "100";
countingDown = false;
// keep "DRAW" on screen for first second of the round
setTimeout(() => {draw.style.display = "none"; draw.style.opacity = "0"; }, 1000);
return true;
}
function handleHoverEnd(e) {
hovering = false;
if (countingDown) {
ready.style.display = "none";
one.style.display = "none";
two.style.display = "none";
three.style.display = "none";
draw.style.display = "none";
ready.style.opacity = "0";
one.style.opacity = "0";
two.style.opacity = "0";
three.style.opacity = "0";
draw.style.opacity = "0";
if (gamemode == "normal") {
if (currentRound <= 1) {
drawTargetsInCircle(0);
gameText.innerText = "hover on middle circle to start the countdown,\nthen click the targets as fast as possible!";
}
else {
gameText.innerText = "ROUND: " + roundSeconds.toFixed(3) + "s\nTOTAL: " + totalTime.toFixed(3) + "s\nhover on circle to start round " + currentRound;
}
}
else if (gamemode == "countdown") {
drawTargetsInCircle(0);
gameText.innerText = "hover on middle circle to start the countdown,\nthen click as many targets as possible!";
}
gameText.style.display = "inline";
countingDown = false;
}
}
function handleTargetClick(e) {
targetsClicked++;
e.target.remove();
}
function handlePageResize(event) {
// take note if page was resized during animation or mid-countdown round to auto-reset at earliest convenience
if (!needsResizeAdjustment && (drawingCircle || countdownTime > 0)) {
needsResizeAdjustment = true; return;
}
/**
* if no game has started yet, re-draw circle
*
* no matter what, if targets on screen, do not reset, do not redraw middle circle, but do flag for reset
*
* if adding eventListener, need to redraw center circle!
*
* if we are playing normal mode:
* -- if round 1, redraw cirlce and addEventListener for hover
* -- if round 2/3, only addEventListener for hover
* -- if round 4, only addEvenListener for reset
*
* if we are playing countdown mode:
* -- if countdownTimer == 0,
* ----- need a way to know if this is before or after the game!
* ----- if before game, redraw cirlce and addEventListener for hover
* ----- if after game, only addEventListener for reset
* -- if countdownTimer > 0, flag for reset upon next target clicked, no event listeners
**/
frameElement.replaceChildren();
setParameters();
center.remove();
center = generateTarget(xFrameAdjustment, yFrameAdjustment);
center.id = "center";
document.body.insertAdjacentElement("afterbegin", center);
if (gamemode == "") {
drawTargetsInCircle(0);
}
else if (gamemode != "") {
center.addEventListener("mouseover", handleHoverStart);
center.addEventListener("mouseleave", handleHoverEnd);
}
console.log('page: ' + pageWidth + ' x ' + pageHeight);
console.log('frame: ' + frameWidth + ' x ' + frameHeight);
needsResizeAdjustment = false;
}
async function drawTargetsInCircle(drawDurationSeconds) {
drawingCircle = true;
let r, x, y;
let radians;
let target;
for (let i = 0; i < 360; i = i + 2) {
r = (frameWidth / 2) - (targetWidth / 2) - (gameBorderWidth * 2);
radians = degreesToRadians(i);
x = (r * 1 * Math.cos(radians)) + xFrameAdjustment;
y = (r * ratio * Math.sin(radians)) + yFrameAdjustment;
target = generateTarget(x, y);
document.getElementById("frame").insertAdjacentElement("afterbegin", target);
if (drawDurationSeconds) {
target.classList.add("fade");
await sleep((drawDurationSeconds * 1000) / 180);
}
}
drawingCircle = false;
}
// helpers for rendering main menu stuff
async function fadeMainMenuIn() {
title1.classList.remove("fade");
title2.classList.remove("fade");
// add main menu elements to DOM flow
titleContainer.style.display = "flex";
title1.style.display = "inline";
title2.style.display = "inline";
gameModes.style.display = "inline";
// make title elements actually visible
title1.style.opacity = "100";
await sleep(500);
title2.style.opacity = "100";
await sleep(1500);
// add fade class for when elements are removed
title1.classList.add("fade");
title2.classList.add("fade");
// fade in gamemodes
await sleep(500);
gameModes.style.opacity = "100";
}
async function fadeMainMenuOut() {
let targets = document.getElementsByClassName("target");
for (let i = 0; i < targets.length; i++) {
console.log(targets[i]);
targets[i].style.opacity = 0;
};
title1.style.opacity = "0";
title2.style.opacity = "0";
gameModes.style.opacity = "0";
await sleep(500);
titleContainer.style.display = "none";
gameModes.style.display = "none";
title1.style.display = "none";
title2.style.display = "none";
}
function degreesToRadians(degrees) {
return degrees * (Math.PI / 180)
}
// function to place a target somewhere random on the circle
function randomTargetGenerator(numTargets) {
let radians, radius
let x, y;
let target;
for (let i = 0; i < numTargets; i++){
radians = degreesToRadians(getRandomInt(0, 360));
radius = (frameWidth / 2) - (targetWidth / 2) - (gameBorderWidth * 2);
x = (radius * 1 * Math.cos(radians)) + xFrameAdjustment;
y = (radius * ratio * Math.sin(radians)) + yFrameAdjustment;
target = generateTarget(x, y);
target.classList.add("target");
target.addEventListener("click", handleTargetClick);
document.getElementById("frame").insertAdjacentElement("afterbegin", target);
}
}
function generateTarget(x, y) {
const target = document.createElement("div");
target.classList.add("target");
target.style.top = y +'px';
target.style.left = x + 'px';
// console.log(target);
return target;
}
function getRandomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // The maximum is exclusive and the minimum is inclusive
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
</script>
</body>
</html>