JavaScript function not being called from button - javascript

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>

Related

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

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>

JS Alert when items collected?

I have created a maze game where the user must collect all the coins in the maze, however I am trying to make an alert appear once the user has collected all the coins, not in any particular order just in general. The alert is being very troublesome at the moment and not working correctly and I'm not sure where I am going wrong based off my research into the matter. I am new to JavaScript so apologies for any clear mistakes.
EDIT I GOT TOLD TO REPHRASE MY QUESTION MORE DIRECTLY - SO THIS ISN'T A DUPLICATE QUESTION. I ALSO HAVE A MAP DECLARDED BUT CANNOT UPLOAD AS IT'S TOO MUCH CODE.
Also, when I say not working correctly, it will appear at random counts as supposed to when the last reward has been collected.
var el = document.getElementById('game');
function drawWorld(){
el.innerHTML = '';
for(var y = 0; y < map.length ; y = y + 1) {
for(var x = 0; x < map[y].length ; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
} else if (map[y][x] === 4) {
el.innerHTML += "<div class='ship'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function restartGame(){
window.location.reload();
}
function winGame(){
if (!map[5].includes(2) && !map[2].includes(2) &&
!map[3].includes(2) && !map[2].includes(2) && !map[4].includes(2)
&& !map[2].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event){
if (event.keyCode === 37){
if ( map[character.y][character.x-1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38){
if ( map[character.y-1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39){
if ( map[character.y][character.x+1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40){
if ( map[character.y+1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}

Generating a random grid of connected paths

I am trying to generate a random grid of connected paths. The image below shows how far I've managed to get it:
The rules that the grid needs to adhere to are the following:
all the paths must connect to each other in some way but there can be dead ends
there can be no blocks that have no connections (i.e. can't be reached)
the blocks on the edge must have paths that point inward, not outward.
As you can see in my image, my code isn't quite right, but I can't find the error.
Here is a fiddle with the code: jsfiddle.net/thatOneGuy/jz5sfr00/1
But I think my mistake is in this function:
function linkAll() {
for (var x = 0; x < 9; x++) {
for (y = 0; y < 9; y++) {
//link up to each other
var count = 0;
if ((x > 0) && (y > 0)) {
if (hz[x - 1][y].right) {
hz[x][y].left = 1;
} else count++;
if (hz[x][y - 1].bottom) {
hz[x][y].top = 1;
} else count++;
}
if ((x < 9) && (y < 9)) {
if (hz[x + 1][y].left) {
hz[x][y].right = 1;
} else count++;
if (hz[x][y + 1].top) {
hz[x][y].bottom = 1;
} else count++;
}
if (count == 4) {
var newPath = getDirection(getRandomInt(0, 3));
if (newPath == 'top') {
hz[x][y - 1].bottom = 1
hz[x][y].top = 1;
} else if (newPath == 'left') {
hz[x - 1][y].right = 1;
hz[x][y].left = 1;
} else if (newPath == 'bottom') {
hz[x][y + 1].top = 1;
hz[x][y].bottom = 1;
} else if (newPath == 'right') {
hz[x + 1][y].left = 1;
hz[x][y].right = 1;
}
}
} //end for (y)
} //end for (x)
}
UPDATE:
I realised that I confused the x and y values of the array. They should have been swopped.
So I added a linkEdges() function so that the edge blocks all link together:
function linkEdges(){
for(var x = 0; x < 10; x++){
for(var y = 0; y < 10; y++){
if((x==0) && (y > 0) && (y < 9)){
if(hz[0][y-1].right){
//console.log(x + ' ' + y + ' y-1 = 1');
//console.log('Inside (y-1) ');
//console.log(hz[x][y]);
if (hz[0][y].left != null)
{
hz[0][y].left = 1;
}
}
}
if ((y==0) && (x > 0)){
if(hz[x-1][0].bottom){
if(hz[x][0].top != null)
hz[x][0].top = 1;
}
}
if ((y==9) && (x < 9) && (x > 0)){
if(hz[x+1][9].top){
if(hz[x][9].bottom != null)
hz[x][9].bottom = 1;
}
}
if ((x==9) && (y < 9)){
if(hz[9][y+1].left){
if(hz[9][y].right != null)
hz[9][y].right = 1;
}
}
} //end for(y)
}//end for(x)
}
I also updated the linkAll() function:
function linkAll(){
for(var x=0; x < 9; x++){
for(var y=0; y < 9; y++){
//link up to each other
var count = 0;
if((x > 0) && (y > 0)){
if(hz[x-1][y].bottom){
hz[x][y].top = 1;
}
else count++;
if(hz[x][y-1].right){
hz[x][y].left = 1;
}
else count++;
}
if((x < 9) && (y < 9)){
if(hz[x+1][y].top){
hz[x][y].bottom = 1;
}
else count++;
if(hz[x][y+1].left){
hz[x][y].right = 1;
}
else count++;
}
if(count == 4){
//console.log('x: ' + x + ' y: '+y);
var newPath = getDirection(getRandomInt(0, 3));
//console.log(newPath);
if(newPath == 'top'){
hz[x][y-1].right = 1
hz[x][y].left = 1;
}
else if(newPath == 'left'){
hz[x-1][y].bottom = 1;
hz[x][y].top = 1;
}
else if(newPath == 'bottom'){
hz[x][y+1].left = 1;
hz[x][y].right = 1;
}
else if(newPath == 'right'){
hz[x+1][y].top = 1;
hz[x][y].bottom = 1;
}
}
}//end for (y)
}//end for (x)
}
My grid now looks like this:
I just don't know how to connect those last few edges. I think it has something to do with my linkEdges() function.

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>

javascript array problem

i have written a snake program using javascript..
the problem is that the snake does not grow more than 2 blocks size....
<html>
<head>
<script type="text/javascript">
var matrix, body, dir, key, lastx, lasty, start, applex, appley, eat, hal;
function node(x, y) {
this.x = x;
this.y = y;
}
function draw() {
var str;
for (var i = 0; i < body.length; i++) {
matrix[body[i].x * 50 + body[i].y].bgColor = "black";
}
}
function halt() {
hal = 1 - hal;
if (hal == 0) automove();
}
function check_status() {
if (start == 1 && hal == 0) {
var ch;
if (eat == 1) {
do {
ch = 0;
applex = Math.round(49 * Math.random());
appley = Math.round(49 * Math.random());
for (var i = 0; i < body.length; i++)
if (body[i].x == applex && body[i].x == appley) ch = 1;
} while (ch == 1);
matrix[applex * 50 + appley].bgColor = "blue";
eat = 0;
}
lastx = body[body.length - 1].x;
lasty = body[body.length - 1].y;
for (var i = 1; i < body.length; i++) {
body[i].x = body[i - 1].x;
body[i].y = body[i - 1].y;
}
if (dir == 1)--body[0].x;
else if (dir == -1)++body[0].x;
else if (dir == 2)--body[0].y;
else if (dir == -2)++body[0].y;
if (body[0].x == -1 || body[0].x == 50 || body[0].y == 50 || body[0].y == -1) {
alert("GAME OVER!!");
start = 0;
}
for (var i = 1; i < body.length; i++) {
if (body[0].x == body[i].x && body[0].y == body[i].y) {
alert("GAME OVER!!");
start = 0;
i = 10000;
}
}
if (body[0].x == applex && appley == body[0].y) {
eat = 1;
body[body.length] = new node(lastx, lasty);
}
matrix[lastx * 50 + lasty].bgColor = "white";
draw();
}
}
function automove() {
if (start == 1 && hal == 0) {
if (key != -dir) dir = key;
check_status();
window.setTimeout("automove()", 200);
}
}
function init() {
start = 1;
var x = document.getElementById("mine");
var str = "<table id='tab' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
for (var i = 0; i < 50; i++) {
str += "<tr>";
for (var j = 0; j < 50; j++)
str += "<td></td>";
str += "</tr>";
}
str += "</table>";
x.innerHTML = str;
matrix = document.getElementsByTagName("td");
body = new Array();
body[0] = new node(0, 0);
draw();
dir = key = -1;
eat = 1;
v = 0;
hal = 0;
automove();
}
function keypress(e) {
if ((e.keyCode == 38) || ((e.which) && (e.which == 38))) //up
key = 1;
else if ((e.keyCode == 40) || ((e.which) && (e.which == 40))) //down
key = -1;
else if ((e.keyCode == 37) || ((e.which) && (e.which == 37))) //left
key = 2;
else if ((e.keyCode == 39) || ((e.which) && (e.which == 39))) //right
key = -2;
check_status();
}
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
<input type="button" onClick="halt()" value="pause">
<p id="mine"></p>
<br><h5 id="score"></h5>
</body>
</html>
The problem is here:
lastx=body[body.length-1].x;
lasty=body[body.length-1].y;
for(var i=1;i<body.length;i++)
{
body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
}
In that loop, body[1] is assigned to body[0], then body [2] is assigned to body[1] etc. This means that everything from index 1 to the end will be set equal to body[0], then body[0] is altered based on direction - so there are only two positions.
Look into the javascript unshift method.
You could replace that loop with:
body.unshift(body[0]);

Categories

Resources