storing high score with javascript - javascript

I have practiced one question and this is about checking time to click the shape that comes up. I want to save the the high score and compare with the next one coming up. It is just how to store the high score . It would be great help if somebody give the way to do it. Thank you in advance
<!doctype html>
<html>
<head>
<title> Javasript </title>
<style type="text/css">
#shape {
width: 200px;
height: 200px;
display:none;
position : relative;
}
</style>
</head>
<body>
<h1>Test your reaction </h1>
<p>Click on the boxes as soon as possible and win it </p>
<p>Your time taken <span id="timeTaken"></span></p>
<div id="shape"></div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400 ;
var left = Math.random() * 400 ;
var width = (Math.random() * 200) + 100 ;
if (Math.random()> 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0%"; }
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.width = width + 'px';
document.getElementById("shape").style.top = top + 'px';
document.getElementById("shape").style.left = left + 'px';
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.display = 'block';
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, Math.random() * 2000 );
}
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = 'none';
var end = new Date().getTime();
var timeTaken = (end - start)/1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
}
</script>
</body>
</html>

Related

Please i need help: Trying to have my animation move from initial coordinates to new inputted coordinates using JavaScript

I have Layout with a machine, i intend to have this machine (purple animation) move from point A to point B based on input cordinate x and cordinate Y. I followed some online tutorials but still not been able to get it. The animation currently moves manually with arrow keys but i intend to have it move automatically. The aim is to have the animation move at a slow frame pace to the inserted coordinates. Any help will be appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Farm Harvest </title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="grid"></div>
<input type="number" id = 'cords1' placeholder="X-Cordinates">
<input type="number" id = 'cords2' placeholder="Y-Cordinates">
<button id = "mybtn" onclick="myCords();">Get Value</button>
<script src="app.js"></script>
</body>
</html>
CSS:
.grid {
position: absolute;
width: 560px;
height: 300px;
border: solid 1px black;
margin-top: 100px;
}
.user {
position: absolute;
width: 30px;
height: 20px;
background-color: blueviolet;
}
.block {
position: absolute;
width: 100px;
height: 20px;
background-color: blue;
}
JS:
const grid = document.querySelector('.grid')
const value1 = document.getElementById('cord1')
const value2 = document.getElementById('cord2')
const blockWidth = 100
const blockHeight = 20
const boardWidth = 560
const boardHeight = 300
var mouseX, mouseY;
var stepWidthFactor = 200;
const userStart = [10, 270]
let currentPosition = userStarnst userStart1 = [10, 270]
let currentPosition1 = userStart1
const user1 = [10, 270]
let currentPosition2 = user1
//my block
class Block {
constructor(xAxis, yAxis) {
this.bottomLeft = [xAxis, yAxis]
this.bottomRight = [xAxis + blockWidth, yAxis]
this.topRight = [xAxis + blockWidth, yAxis + blockHeight]
this.topLeft = [xAxis, yAxis + blockHeight]
}
}
class moveblock{
constructor(xAxis,yAxis){
this.xAxis = inputval0;
this.yAxis = inputval1;
let currentPosition3 = user2;
}
}
//all my blocks
const blocks = [
new Block(120, 210),
new Block(230, 210),
new Block(340, 210),
new Block(120, 140),
new Block(230, 140),
new Block(340, 140),
new Block(120, 70),
new Block(230, 70),
new Block(340, 70),
]
//draw my blocks
function addBlocks() {
for (let i = 0; i < blocks.length; i++) {
const block = document.createElement('div')
block.classList.add('block')
block.style.left = blocks[i].bottomLeft[0] + 'px'
block.style.bottom = blocks[i].bottomLeft[1] + 'px'
grid.appendChild(block)
console.log(blocks[i].bottomLeft)
}
}
addBlocks()
//add user
const user = document.createElement('div')
user.classList.add('user')
grid.appendChild(user)
drawUser()
//move user
function moveUser(e) {
switch (e.key) {
case 'ArrowLeft':
if (currentPosition[0] > 0) {
currentPosition[0] -= 10
console.log(currentPosition[0] > 0)
drawUser()
}
break
case 'ArrowRight':
if (currentPosition[0] < (boardWidth - blockWidth)) {
currentPosition[0] += 10
console.log(currentPosition[0])
drawUser()
}
break
case 'ArrowDown':
if (currentPosition1[0] < (boardHeight - blockHeight)) {
currentPosition1[0] += 10
console.log(currentPosition1[0]>0)
drawUser()
}
break
case 'ArrowUp':
if (currentPosition1[0] > 0) {
currentPosition1[0] -= 10
console.log(currentPosition1[0])
drawUser()
}
break
}
}
document.addEventListener('keydown', moveUser)
//draw User
function drawUser() {
user.style.top = currentPosition1 [0] + 'px'
user.style.left = currentPosition[0] + 'px'
user.style.bottom = currentPosition[0] + 'px'
user.style.right = currentPosition[0] + 'px'
}
function myCords(){
const user2 = [inputval0,inputval1]
let currentPosition3 = user2;
var inputval0 = document.getElementById('cords1').value;
var inputval1 = document.getElementById('cords2').value;
if(inputval0 < boardHeight && inputval1 < boardWidth && inputval0 != 0 && inputval1 != 0){
alert("good cords " + "X: "+ inputval0 + " " +"Y: " +inputval1)
}
else{
alert("wrong cordinates")
}
}document.addEventListener('onclick',myCords)
function drawnewUser(){
user.style.left = currentPosition + 'px';
user.style.top = currentPosition + 'px'
user.style.bottom = currentPosition + 'px'
user.style.right = currentPosition + 'px'
}

How do I use a repeat function to reset everything and run everything over again?

I have a repeat function which runs on a button on-click event, however it's not working properly. Maybe because there are too many setIntervals running although I tried to clear them all. I also made sure to reset the variables used back to their initial values, however the moving circle keeps showing up faded when the shoot again button is pressed, so I'm assuming there's an issue with the setInterval, however, I don't know what it is.It's also not drawing the basketball again.
var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;
var ctx = canvas.getContext("2d");
var intervalId2;
var intervalId1;
//Initializing Variables
var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;
var resetVars = function() {
dt = 0.01;
var x = r + 1;
var y = 500 / 1.2;
var xc = 145;
var yc = 300;
var dxc = 95;
var dyc = 300;
var theta = 0;
};
//resetVars();
var reset = function() {
ctx.clearRect(0, 0, 800, 800);
drawHoop()
};
//Interval Id to eventually clear it to stop this to shoot
var intervalID = setInterval(moveCirc, 10000 * dt);
var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
var repeat = function() {
reset();
clearInterval(intervalID);
clearInterval(intervalId2);
clearInterval(intervalId1);
resetVars();
drawBasketball();
drawHoop();
moveCirc();
intervalID = setInterval(moveCirc, 10000 * dt);
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>
<body style="background-color:powderblue;">
<p id="count"></p>
<button id="again" onclick="repeat()"> Shoot Again </button>
</body>
This should make a stop button for a repeating function
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
Stop

JavaScript : animation for a div

I want to animate a div (say height 50 px and width 50 px) from left to right in the browser.
I can share my html css part here:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box{
width:100px;
height:100px;
position: absolute;
}
.blue{
background:#00f;
}
.position{
margin-top: 50px;
}
</style>
</head>
<body>
<div class="box blue position" id="move_box"> </div>
<script>
</script>
</body>
</html>
How can I animate the div from left to right according to the condition "moves 10 pixels right and 10 pixels down per second"?
Note: only in JavaScript.
My script:
<script>
var box = document.getElementById('move_box'),
boxPos = 0,
boxLastPos = 0,
boxVelocity = 0.01,
limit = 300,
lastFrameTimeMs = 0,
maxFPS = 60,
delta = 0,
timestep = 1000 / 60,
fps = 60,
framesThisSecond = 0,
lastFpsUpdate = 0,
running = false,
started = false,
frameID = 0;
function update(delta) {
boxLastPos = boxPos;
boxPos += boxVelocity * delta;
// Switch directions if we go too far
if (boxPos >= limit || boxPos <= 0) boxVelocity = -boxVelocity;
}
function draw(interp) {
box.style.left = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
box.style.top = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
console.log(box.style.top);
}
function panic() {
delta = 0;
}
function begin() {
}
function end(fps) {
/*box.style.backgroundColor = 'blue';*/
}
function stop() {
running = false;
started = false;
cancelAnimationFrame(frameID);
}
function start() {
if (!started) {
started = true;
frameID = requestAnimationFrame(function(timestamp) {
draw(1);
running = true;
lastFrameTimeMs = timestamp;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
frameID = requestAnimationFrame(mainLoop);
});
}
}
function mainLoop(timestamp) {
// Throttle the frame rate.
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
frameID = requestAnimationFrame(mainLoop);
return;
}
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
begin(timestamp, delta);
if (timestamp > lastFpsUpdate + 1000) {
fps = 0.25 * framesThisSecond + 0.75 * fps;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
}
framesThisSecond++;
var numUpdateSteps = 0;
while (delta >= timestep) {
update(timestep);
delta -= timestep;
if (++numUpdateSteps >= 240) {
panic();
break;
}
}
draw(delta / timestep);
end(fps);
frameID = requestAnimationFrame(mainLoop);
}
start();
</script>
Check that:
var i = 1;
var div = document.getElementById('move_box');
function myLoop() {
setTimeout(function() {
div.style.top = i * 10 + 'px'
div.style.left = i * 10 + 'px'
i++;
if (i < 5) {
myLoop();
}
}, 1000)
}
myLoop(); // start the loop
.box {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
}
.blue {
background: #00f;
}
.position {
margin-top: 50px;
}
<div class="box blue position" id="move_box"> </div>
JSFiddle

Not able to get the image elements in correct position

I want to achieve something like image shown below.
More specifically, I need to have smiley faces randomly distributed throughout a 500px area and have a border on the right-hand side of the area.
but with the following code I am not getting the desired result.
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute
}
div {
width: 500px;
height: 500px
}
#rightSide {
position: absolute;
left: 500px;
border-left: 1px solid black
}
</style>
</head>
<body onload="generateFaces()">
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
var numberOfFaces = 5;
var top_position = 400;
var left_position = 400;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function generateFaces() {
while (i < numberOfFaces) {
var this_img = document.createElement("img");
this_img.src = "#";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = top_position - 50;
left_position = left_position - 50;
i++;
}
}
</script>
</body>
</html>
The result I am getting for the above code snippet looks like
How will I make it proper?
In your while loop you subtract 50 from top and left every time, so you get even distances for each image.
Use Math.random() for random values. The function returns values between 0 and 1, so multiply with the container size to get random positions.
You just need to go with random funtion if you require random positions. For fix position you need to implement particular position checks.
top_position = Math.random()*400; left_position = Math.random()*400;
JS Fiddle - https://jsfiddle.net/manishghec/13k8caen/
If you want to use random positions:
top_position = Math.random()*400; left_position = Math.random()*400;
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
Here is the fiddle: https://jsfiddle.net/v222wgav/1/
This is how you generate random top_position locations and random left_position locations.
You should be able to modify the code below to suit your needs.
I've included a random function getRandom which is just a standard "get a random number within this range" function.
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
To use it, just provide a minimum number of pixels, and a maximum number of pixels in the range you need.
getRandom(0, 400);
var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
while(i < numberOfFaces)
{
var this_img = document.createElement("img");
this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = getRandom(0, 400);
left_position = getRandom(0, 400);
i++;
}
}
img {
position:absolute
}
div {
width:500px;height:500px
}
#rightSide {
position:absolute;
left: 0px;
top: 0px;
border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
I would do away with the #rightSide div all together like so:
var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
while(i < numberOfFaces)
{
var this_img = document.createElement("img");
this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = getRandom(0, 400);
left_position = getRandom(0, 400);
i++;
}
}
img {
position:absolute
}
div {
width:500px;height:500px
}
#leftSide {
border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">
<div id="leftSide"></div>
</body>
</html>
Happy Random Smilies!
Resources:
Image Credit: https://commons.wikimedia.org/wiki/File:718smiley.svg
How to use generate random numbers in a specific range

Progress Bar Keeps Repeating

How can the code below be modified such that when the progress bar is finished loading and it reaches the end, a seperate function (ie. test() )can be executed rather than just repeating and repeating like it is now.
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
w = 0;
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>
</head>
<body onload="var progress_run_id = setInterval(progress, 30);">
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>
Much thanks and appreciation for all your help.
Cheers,
Jay
Call this separate function instead of
w = 0;
line. Don't forget to clearInterval(progress_run_id) too.
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
var progress_run_id = null;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
clearInterval( progress_run_id );
w = 0;
} else {
w = parseInt(w) + 5 + 'px';
}
node.style.width = w;
}
function initialize(){
progress_run_id = setInterval(progress, 30);
}
window.onload = initialize();
</script>
</head>
<body>
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test(); // CHANGE THIS
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
That checks if the width is equal to the completed width. If it is, then clear the interval, and call your test function.
<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test();
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>

Categories