Game in JavaScript problem with alert coming up too fast when clicking - javascript

I got a game where you are supposed to catch the burglar.
The problem I have is that the alertbox "Too bad, the burglar got away with your money!" comes too fast when one click the startthegame-button.
How do I do to get the alertbox to alert only after that the game has started and 10 seconds have passed?
I want the game to run only one time. So after the game has ended the person playing has to refresh the page to be able to start playing again.
Any help is much appreciated!
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title> BURGLAR-STOPPING </title>
<style>
#burglar {
position: absolute;
top: 150px;
left: 60px;
}
</style>
</head>
<body>
<h1>Get the burglar! </h1>
<h3> You have only 10 seconds before the burglar runs away with all your money! </h3>
<div id="burglar" onclick="stopIt();"> BURGLAR </div>
<input type="button" value="Start the game" onclick="startthegame();time();">
<script>
var x = 150;
var y = 300;
var course = "right";
var randomUp = Math.floor(Math.random() * 166);
var t = function startthegame() {
setInterval(moveMe, 0);
}
function stopIt() {
clearInterval(t);
alert("Yes, You got the burglar!");
}
function moveMe() {
if (course == "right") {
x = x + 2;
} else if (course == "left") {
x = x - 2;
} else if (course == "down") {
y = y + 1;
} else if (course == "up") {
y = y - 1;
}
document.getElementById("burglar").style.left = x + "px";
document.getElementById("burglar").style.top = y + "px";
if (x == 1050 && course == "right") {
course = "down";
} else if (y == 500 && course == "down") {
course = "left";
} else if (x == 150 && course == "left") {
course = "up";
} else if (y == randomUp && course == "up") {
course = "right";
}
}
function startthegame() {
setInterval(moveMe, 0);
}
function time() {
setTimeout(time, 10000);
alert("Too bad, the burglar got away with your money!");
}
</script>
</body></html>

Your code is creating a timeout to call itself and it then alerts the string. It is NOT making the alert at 10 sconds.
function time() {
setTimeout(time, 10000);
alert("Too bad, the burglar got away with your money!");
}
should be
var endTimer;
function time() {
endTimer = setTimeout(function () { alert("Too bad, the burglar got away with your money!"); }, 10000);
}
Now you are trying to cancel the timeout, but the t is a reference to the function, not the interval
var t = function startthegame() {
setInterval(moveMe, 0);
}
should be
var t;
function startthegame() {
t = setInterval(moveMe, 0);
}
And for some reason you defined startthegame twice.
so we have
var x = 150;
var y = 300;
var course = "right";
var randomUp = Math.floor(Math.random() * 166);
var hasRun = false;
var moveTimer;
function startthegame() {
if (hasRun) return;
hasRun = true;
moveTimer = setInterval(moveMe, 1);
}
function stopTimers () {
if (moveTimer) clearInterval(moveTimer);
if (endTimer) clearTimeout(endTimer);
}
function stopIt() {
stopTimers();
alert("Yes, You got the burglar!");
}
function moveMe() {
if (course == "right") {
x = x + 2;
} else if (course == "left") {
x = x - 2;
} else if (course == "down") {
y = y + 1;
} else if (course == "up") {
y = y - 1;
}
document.getElementById("burglar").style.left = x + "px";
document.getElementById("burglar").style.top = y + "px";
if (x == 1050 && course == "right") {
course = "down";
} else if (y == 500 && course == "down") {
course = "left";
} else if (x == 150 && course == "left") {
course = "up";
} else if (y == randomUp && course == "up") {
course = "right";
}
}
var endTimer
function time() {
endTimer = setTimeout(function() {
alert("Too bad, the burglar got away with your money!");
stopTimers();
}, 10000);
}
<html lang="sv">
<head>
<meta charset="utf-8">
<title> BURGLAR-STOPPING </title>
<style>
#burglar {
position: absolute;
top: 150px;
left: 60px;
}
</style>
</head>
<body>
<h1>Get the burglar! </h1>
<h3> You have only 10 seconds before the burglar runs away with all your money! </h3>
<div id="burglar" onclick="stopIt();"> BURGLAR </div>
<input type="button" value="Start the game" onclick="startthegame();time();">
</body>
</html>

Related

Background Error fault when applying condition

So if x = Number value background changes fine, my question is when x has no value. How can I have a background-color of #ffffff. Currently, code is defaulting to #db0000.
JS:
var grid_value = document.getElementById("Vone").innerHTML;
var x = grid_value;
if (x >= 0 && x < 15) {
document.getElementById("GridA").style.backgroundColor = "#db0000";
} else if (x >= 15 && x < 25) {
document.getElementById("GridA").style.backgroundColor = "#f0ad4e";
} else if (x >= 25) {
document.getElementById("GridA").style.backgroundColor = "#5cb85c";
} else if (x = "Pick" ) {
document.getElementById("GridA").style.backgroundColor = "#0085eb";
} else if (x = "" ) {
document.getElementById("GridA").style.backgroundColor = "#ffffff";
}
Here you haven't given any conditions if x doesn't have a value, so the default condition is x=0.
You should try else if (!x).
else if (!x) {
document.getElementById("GridA").style.backgroundColor = "#ffffff";
}
Hope this helps you out.
const gA = document.getElementById("GridA");
document.getElementById("Vone").addEventListener("blur", function(event){
gA.classList = "";
var x = this.value;
if (x === "") {
gA.classList.add("white");
} else if (x === "Pick") {
gA.classList.add("color1");
} else if (x >= 0 && x < 15) {
gA.classList.add("color2");
} else if (x >= 15 && x < 25) {
gA.classList.add("color3");
} else if (x >= 25) {
gA.classList.add("color4");
}
});
#GridA { height:100px; border:1px solid grey; margin-top:5px; }
.color1 { background-color:#dbf000; }
.color2 { background-color:#f0ad4e; }
.color3 { background-color:#5cb85c; }
.color4 { background-color:#0085eb; }
.white { background-color:#ffffff; }
<input id="Vone">
<div id="GridA"></div>

Why do I get the Error: "Cannot read property 'style' of null" on line 216 because of something also on lines 190, 200, 213?

* I can't figure out why I get the following error on my console: "Cannot read property 'style' of null" on line 216(near the bottom, I have put a comment) because of something also on lines 190, 200, 213? I think the problem is about the laser variable... Please help. I would really appreciate if someone could help me as soon as possible.*
'''
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>test</title>
<div>
<h1 style="text-align:center; color:purple;" id="pixelator">
<big>
<i>
<b>
Pixelator
</b>
</i>
</big>
</h1>
<button type="button" id="button1" onclick="Instructions()">Instructions for game</button>
<button type="button" id="button2" onclick="YouTube()">YouTube</button>
<h3 id="Instructions1">
Use the keys WASD to controll player one(blue), Q to
shoot left and E to shoot right. Use the arrow keys to controll player two(),
1 on the numberpad to shoot left and two to shoot right.
</h3>
<button type="button" id="Close" onclick="close1()">Close</button>
</div>
<img src="C:/Users/Tania/Documents/Website/Screenshots/Nice.jpg" alt="Image not found" id="Pic">
</head>
<body style="background-color:green">
<style>
button {
background-color: #4169E1;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 30%;
height: 45px;
}
#hero {
background:#ff0000;
width:20px;
height:50px;
position:absolute;
}
#player {
background:#ff0000;
width:20px;
height:50px;
position:absolute;
}
#Pic {
width: 150px;
}
#laser {
width: 30;
height: 3;
background:#ff0000
position:absolute;
}
</style>
<div id="player"></div>
<div id="hero"></div>
<div id="laser"></div>
<script type="text/javascript">
function YouTube(){
window.open("https://www.youtube.com/channel/UCe9MhUIA6wwwchVBzypCBnA");
}
document.getElementById("Instructions1").style.display = "none";
document.getElementById("Close").style.display = "none";
function Instructions() {
document.getElementById("Instructions1").style.display = "block";
document.getElementById("Close").style.display = "block";
}
function close1() {
document.getElementById("Instructions1").style.display = "none";
document.getElementById("Close").style.display = "none";
}
var LEFT_KEY = 65;
var UP_KEY = 87;
var RIGHT_KEY = 68;
var DOWN_KEY = 83;
var LEFT_ARROW = 37;
var RIGHT_ARROW = 39;
var SPACE_KEY = 32;
var DOWN_ARROW = 40;
var UP_ARROW = 38;
var Q_KEY = 81;
var E_KEY = 69;
var HERO_MOVEMENT = 10;
var lastLoopRun = 0;
var controller = new Object();
var player = new Object();
player.element = 'player'
player.x = 650;
player.y =460;
var hero = new Object();
hero.element = 'hero';
hero.x = 250;
hero.y = 460;
var laser = new Object();
laser.x = 0;
laser.y = -120;
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 1910) {
sprite.x = 1910 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 940) {
sprite.y = 940 - sprite.h;
}
}
function createSprite(element, x, y, w, h) {
var result=new Object();
result.element=element;
result.x=x;
result.y=y;
result.w=w;
result.h=h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
if (keyCode == LEFT_ARROW) {
controller.leftarrow = isPressed;
}
if (keyCode == RIGHT_ARROW) {
controller.rightarrow = isPressed;
}
if (keyCode == UP_ARROW) {
controller.rightarrow = isPressed
}
if (keyCode == DOWN_ARROW) {
controller.downarrow = isPressed
}
if (keyCode == Q_KEY) {
controller.qkey = isPressed
}
if (keyCode == E_KEY) {
controller.ekey = isPressed
}
}
function handleControls() {
if (controller.down) {
hero.y += HERO_MOVEMENT
}
if (controller.up) {
hero.y -= HERO_MOVEMENT
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.qkey && laser.x <= -120) {
laser.x=hero.x-20;
laser.y=hero.y+15;
}
if (controller.ekey && laser.x <= -120) {
laser.x=hero.x+20;
laser.y=hero.y+10;
}
ensureBounds(hero);
}
function showSprites() {
setPosition(hero);
setPosition(laser);
setPosition(player)
}
function updatePositions() {
laser.x-= 90
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
showSprites();
lastLoopRun = new Date().getTime();
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
loop();
function setPosition(sprite) {
var e = document.getElementById(sprite.element)
//***LINE 216-*** e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
createSprite('laser', 0, -120, 2, 50)
</script>
</body>
</html>
'''
Your laser object doesn't have the laser.element property set, if you add laser.element='laser'; after the laster.x and laser.y inicializations (line 104) this error should be fixed

JavaScript function not being called from button

I am trying to code the infamous FizzBuzz program in multiple languages and I am stumped on JavaScript. I am trying to call the function from a button but it doesn't work, and even when I try to call the function normally the same happens. I've tried multiple different methods of outputting and it made no difference so hopefully someone can show me what im doing wrong. Here's the code:
<!DOCTYPE html>
<html>
<body>
<div class="center">
<h1>This is FizzBuzz</h1>
<button onclick="fizzBuzz()">Run FizzBuzz</button>
<p id="hi">Hi there</p>
</div>
<style>
.center {
text-align: center;
font-family:Arial;
}
</style>
<script> //JavaScript
var idd = document.getElementById("hi");
function fizzBuzz(){
idd.innerHTML = "hi";
for (x = 0; x = 15; x++) {
idd.innerHTML = x;
if (x % 3 == 0 && x % 5 == 0){
idd.innerHTML = "FizzBuzz";
} else if((x % 3)= 0){
idd.innerHTML = "Fizz";
} else if((x % 5) = 0){
idd.innerHTML = "Buzz";
} else {
idd.innerHTML = x;
}
}
}
fizzBuzz();
</script>
</body>
</html>
x = 15 will never evaluate to false, meaning the loop will go on forever. Try changing it to x < 15.
function fizzBuzz(){
idd.innerHTML = "hi";
for (x = 0; x < 15; x++) {
idd.innerHTML = x;
if (x % 3 == 0 && x % 5 == 0){
idd.innerHTML = "FizzBuzz";
} else if((x % 3) == 0){
idd.innerHTML = "Fizz";
} else if((x % 5) == 0){
idd.innerHTML = "Buzz";
} else {
idd.innerHTML = x;
}
}
}
You will also need to use == instead of = for comparisons for it to work, as in (x % 3) == 0.
<!DOCTYPE html>
<html>
<body>
<div class="center">
<h1>This is FizzBuzz</h1>
<button onclick="fizzBuzz()">Run FizzBuzz</button>
<p id="hi">Hi there</p>
</div>
<style>
.center {
text-align: center;
font-family:Arial;
}
</style>
<script> //JavaScript
var idd = document.getElementById("hi");
function fizzBuzz(){
idd.innerHTML = "hi";
for (x = 0; x < 15; x++) {
idd.innerHTML = x;
if (x % 3 == 0 && x % 5 == 0){
idd.innerHTML = "FizzBuzz";
} else if((x % 3)== 0){<!--here '=='-->
idd.innerHTML = "Fizz";
} else if((x % 5) == 0){<!--here '=='-->
idd.innerHTML = "Buzz";
} else {
idd.innerHTML = x;
}
}
}
fizzBuzz();
</script>
</body>
</html>

JavaScript/HTML Canvas: mouse detection for looped row of buttons

I'm building a simple drum machine that uses canvas for the GUI. I have a row of buttons drawn with a for loop that toggle on/off when clicked.
Here's a sample on JSFiddle
While it works, I'm a bit embarrassed by my buttonToggleDetection function. It's the only solution I could think of to check which button the mouse is over. I'm wondering if anyone can suggest a better way to do this?
var buttonToggleDetection = function(posx, posy, x) {
if (posx < canvas.width/2 && posy > x && posy < x*2) {
if (posx > x*1 && posx < x*2) {
if (pattern[0] === 0) {
pattern[0] = 1;
} else {
pattern[0] = 0;
}
}
else if (posx > x*2 && posx < x*3) {
if (pattern[1] === 0) {
pattern[1] = 1;
} else {
pattern[1] = 0;
}
}
else if (posx > x*3 && posx < x*4) {
if (pattern[2] === 0) {
pattern[2] = 1;
} else {
pattern[2] = 0;
}
}
else if (posx > x*4 && posx < x*5) {
if (pattern[3] === 0) {
pattern[3] = 1;
} else {
pattern[3] = 0;
}
}
else if (posx > x*5 && posx < x*6) {
if (pattern[4] === 0) {
pattern[4] = 1;
} else {
pattern[4] = 0;
}
}
else if (posx > x*6 && posx < x*7) {
if (pattern[5] === 0) {
pattern[5] = 1;
} else {
pattern[5] = 0;
}
}
else if (posx > x*7 && posx < x*8) {
if (pattern[6] === 0) {
pattern[6] = 1;
} else {
pattern[6] = 0;
}
}
else if (posx > x*8 && posx < x*9) {
if (pattern[7] === 0) {
pattern[7] = 1;
} else {
pattern[7] = 0;
}
}
}
if (posx > canvas.width/2 && posy > x && posy < x*2) {
if (posx > x*9 && posx < x*10) {
if (pattern[8] === 0) {
pattern[8] = 1;
} else {
pattern[8] = 0;
}
}
else if (posx > x*10 && posx < x*11) {
if (pattern[9] === 0) {
pattern[9] = 1;
} else {
pattern[9] = 0;
}
}
else if (posx > x*11 && posx < x*12) {
if (pattern[10] === 0) {
pattern[10] = 1;
} else {
pattern[10] = 0;
}
}
else if (posx > x*12 && posx < x*13) {
if (pattern[11] === 0) {
pattern[11] = 1;
} else {
pattern[11] = 0;
}
}
else if (posx > x*13 && posx < x*14) {
if (pattern[12] === 0) {
pattern[12] = 1;
} else {
pattern[12] = 0;
}
}
else if (posx > x*14 && posx < x*15) {
if (pattern[13] === 0) {
pattern[13] = 1;
} else {
pattern[13] = 0;
}
}
else if (posx > x*15 && posx < x*16) {
if (pattern[14] === 0) {
pattern[14] = 1;
} else {
pattern[14] = 0;
}
}
else if (posx > x*16 && posx < x*17) {
if (pattern[15] === 0) {
pattern[15] = 1;
} else {
pattern[15] = 0;
}
}
}
return;
}
Your way of bounds checking the buttons seems fine...but your loop could be tightened up a bit by defining your buttons in an array and then looping through that array.
Here's one way to draw and toggle buttons in html canvas:
Define each of your button's x,y,width,height & pressed-state
var buttons=[];
buttons.push({x:20,y:20,width:50,height:35,text:'One',isPressed:false});
buttons.push({x:80,y:20,width:50,height:35,text:'Two',isPressed:true});
buttons.push({x:140,y:20,width:50,height:35,text:'Three',isPressed:false});
Test if the mouse is over any button:
for(var i=0;i<buttons.length;i++){
var b=buttons[i];
if(mx>b.x && mx<b.x+b.width && my>b.y && my<=b.y+b.height){
b.isPressed=(!b.isPressed);
}
}
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.font='14px verdana';
var buttons=[];
buttons.push({x:20,y:20,width:50,height:35,text:'One',isPressed:false});
buttons.push({x:80,y:20,width:50,height:35,text:'Two',isPressed:true});
buttons.push({x:140,y:20,width:50,height:35,text:'Three',isPressed:false});
draw();
function draw(){
var label;
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<buttons.length;i++){
var b=buttons[i];
if(b.isPressed){
ctx.shadowBlur=0;
ctx.shadowOffsetX=0;
ctx.shadowOffsetY=0;
ctx.shadowColor=null;
ctx.fillStyle='powderblue';
label='ON';
}else{
ctx.shadowBlur=2;
ctx.shadowOffsetX=2;
ctx.shadowOffsetY=2;
ctx.shadowColor='black';
ctx.fillStyle='paleturquoise';
label='OFF';
}
ctx.strokeRect(b.x,b.y,b.width,b.height);
ctx.fillRect(b.x,b.y,b.width,b.height);
ctx.shadowBlur=0;
ctx.shadowOffsetX=0;
ctx.shadowOffsetY=0;
ctx.shadowColor=null;
ctx.fillStyle='black';
ctx.fillText(label,b.x+b.width/2,b.y+b.height/2);
ctx.fillStyle='gray';
ctx.fillText(label,b.x+b.width/2+1,b.y+b.height/2+1);
}
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
//
for(var i=0;i<buttons.length;i++){
var b=buttons[i];
if(mx>b.x && mx<b.x+b.width && my>b.y && my<=b.y+b.height){
b.isPressed=(!b.isPressed);
}
}
draw();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click the buttons</h4>
<canvas id="canvas" width=300 height=300></canvas>
I would recommend using svg instead of canvas. The content of an SVG node is very similar to that of a canvas node, but each shape is built out of XML markup or dynamically created elements, much like document.body's contents. This gives you a few big advantages:
You can apply classes to individual shapes, and use css to apply
colors/styles.
You can take advantage of css's :hover pseudo-style
to apply color to hovered elements.
Most importantly: You can bind events to each shape!
The code below is available to fiddle with at http://jsfiddle.net/3zevLyur/1/
Here's the html:
<svg id="drumMachine"/>
<div id="debugText"/>
Here's the javascript to build the pads and bind events:
var svg = document.getElementById("drumMachine");
var activePad = null;
var debugText = document.getElementById("debugText");
for (var x = 0; x < 16; x++) {
createNewPad(x);
}
function createNewPad(padNumber) {
var r = document.createElementNS("http://www.w3.org/2000/svg", "rect")
r.setAttribute("width", "40");
r.setAttribute("height", "40");
r.setAttribute("x", padNumber * 50);
r.setAttribute("data-pad-number", x);
r.onmouseenter = mouseOver;
r.onmouseleave = mouseOut;
svg.appendChild(r);
}
function mouseOver() {
activePad = this;
debugText.innerHTML = this.getAttribute("data-pad-number");
}
function mouseOut() {
activePad = null;
debugText.innerHTML = "";
}

Loop doesn't change content within div

This loop is supposed to increment the variable x every 15 seconds and depending upon what value x is the appropriate content is shown, the problem is that x doesn't increment.
var x = 1;
function slider() {
if (x > 4) {
x = 1;
}
if (x == 1) {
document.writeln("<div id='picture_slider_info'><h3>Example one</h3></div>");
} else if(x == 2) {
document.writeln("<div id='picture_slider_info'><h3>Example two</h3></div>");
} else if (x == 3) {
document.writeln("<div id='picture_slider_info'><h3>Example three</h3></div>");
} else {
document.writeln("<div id='picture_slider_info'><h3>Example four</h3></div>");
}
x++
}
setInterval(slider(), 15000);
You are not incrementing the variable x.
Change your code to:
var x = 1;
function slider() {
x++; // x incremented.
if (x > 4) {
x = 1;
}
if (x == 1) {
document.writeln("<div id='picture_slider_info'><h3>Example one</h3></div>");
} else if(x == 2) {
document.writeln("<div id='picture_slider_info'><h3>Example two</h3></div>");
} else if (x == 3) {
document.writeln("<div id='picture_slider_info'><h3>Example three</h3></div>");
} else {
document.writeln("<div id='picture_slider_info'><h3>Example four</h3></div>");
}
}
setInterval(slider(), 15000);
You shouldn't be calling slider(), instead, pass the function as argument to setInterval:
setInterval(slider, 1500).
You are currently passing the return result of slider() which is undefined to setInterval.
Nikola Dimitroff is right.
I'm giving this as an answer to give you the code.
<html>
<head>
<script type="text/javascript">
var x = 1;
function slider() {
console.log(x);
if (x > 4) { x = 1; }
if (x == 1) { console.log("One"); }
else if(x == 2) { console.log("Two"); }
else if (x == 3) { console.log("Three"); }
else { console.log("More"); }
x++
}
setInterval(slider, 1000);
</script>
</head>
<body>
</body>
</html>

Categories

Resources