I am trying to code the google dino game replica. I want to make the blocks or codes to be random heights. How to i do that?
Here is the code I am using:
HTML:
<!DOCTYPE html>
<html lang="en" onclick="jump()">
<head>
<meta charset="UTF-8">
<title>Jump Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game">
<div id="character"></div>
<div id="block"></div>
</div>
<p>Score: <span id="scoreSpan"></span></p>
</body>
<script src="script.js"></script>
</html>
_____________________________________________________________________________
CSS:
*{
padding: 0;
margin: 0;
overflow-x: hidden;
}
.game{
width: 500px;
height: 200px;
border: 1px solid black;
margin: auto;
}
#character{
width: 20px;
height: 50px;
background-color: red;
position:relative;
top: 150px;
}
.animate{
animation: jump 0.1s linear;
}
@keyframes jump{
0%{top: 150px;}
30%{top: 100px;}
70%{top: 100px;}
100%{top: 150px;}
}
#block{
background-color: blue;
width: 20px;
height: 20px;
position: relative;
top: 130px;
left: 500px;
animation: block 3s infinite linear;
}
@keyframes block{
0%{left: 500px}
100%{left: -20px}
}
p{
text-align: center;
}
_____________________________________________________________________________
JAVASCRIPT:
var character = document.getElementById("character");
var block = document.getElementById("block");
var counter=0;
function jump(){
if(character.classList == "animate"){return}
character.classList.add("animate");
setTimeout(function(){
character.classList.remove("animate");
},300);
}
var checkDead = setInterval(function() {
let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
let blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue("left"));
if(blockLeft<20 && blockLeft>-20 && characterTop>=130){
block.style.animation = "none";
alert("Game Over. score: "+Math.floor(counter/100));
counter=0;
block.style.animation = "block 1s infinite linear";
}else{
counter++;
document.getElementById("scoreSpan").innerHTML = Math.floor(counter/100);
}
}, 10);
var defaultMax = Math.exp(6) / 12;
function buffer(min=0.1, max=defaultMax, mult=1) {
return Math.min(max, Math.max(min,
min / 2 + Math.exp(Math.random() * 6) * Math.random() * mult / 12
))+"em";
}
function randomize() {
var block = document.getElementsByClassName("block");
for (var p = 0; p < block.length; p++) {
block[p].style.margin = buffer(0.1, defaultMax, 0.5) + " "
+ buffer(0.25) + " "
+ buffer(0.25, defaultMax, 0.5) + " "
+ buffer();
block[p].style.width = buffer(8);
block[p].style.height = buffer(5);
}
}
What I have tried:
I have tired using these tutorials but could not get them to work:
-
Randomizing in JavaScript - YouTube[
^]
-
Let's Create Random Emojis Project Using JavaScript #HuXnWebDev - YouTube[
^]