Skip to content

Instantly share code, notes, and snippets.

@MintayRibkins
Created May 9, 2024 09:51
Show Gist options
  • Save MintayRibkins/22fedf71f5087d3fcefdede8653ee404 to your computer and use it in GitHub Desktop.
Save MintayRibkins/22fedf71f5087d3fcefdede8653ee404 to your computer and use it in GitHub Desktop.
js game
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Trova il tesoro!</title>
</head>
<body>
<h1 id="heading">Trova il tesoro!</h1>
<img id="map" width=400 height=400 src="img.png" alt="">
<p id="distance"></p>
<script>
// Ottenere un numero casuale da 0 a dimensione-1
const getRandomNumber = function (size) {
return Math.floor(Math.random() * size);
};
// Calcolare la distanza dal clicco (evento) al tesoro (target)
const getDistance = function (event, target) {
var diffX = event.offsetX - target.x;
var diffY = event.offsetY - target.y;
return Math.sqrt((diffX * diffX) + (diffY * diffY));
};
// Ottenere una stringa di suggerimento di distanza
const getDistanceHint = function (distance) {
if (distance < 10) {
return "Ti brucerai!";
} else if (distance < 20) {
return "Molto caldo";
} else if (distance < 40) {
return "Caldo";
} else if (distance < 80) {
return "Caldo";
} else if (distance < 160) {
return "Freddo";
} else if (distance < 320) {
return "Molto freddo";
} else {
return "Congelerai!";
}
};
// Creare variabili
const width = 400;
const height = 400;
let clicks = 0;
// Posizione casuale del tesoro
const target = {
x: getRandomNumber(width),
y: getRandomNumber(height)
};
// Aggiungere un gestore di clic all'elemento img
document.querySelector("#map").addEventListener('click', function (event) {
console.log('click')
clicks++;
// Ottenere la distanza dal punto di clic al tesoro
var distance = getDistance(event, target);
// Trasformare la distanza in un suggerimento
var distanceHint = getDistanceHint(distance);
// Scrivere nel elemento #distance il nuovo suggerimento
var distanceElement = document.getElementById("distance");
// Imposta il testo del elemento sulla stringa distanceHint
distanceElement.textContent = distanceHint;
// Se il clic è stato abbastanza vicino, congratulazioni per la vittoria
if (distance < 8) {
alert("Tesoro trovato! Clicchi fatti: " + clicks);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment