JS Alert when items collected? - javascript

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)
}

Related

Character will not jump after touching in JS

I am programming collision detection in JS for a platformer. For some reason, when my character touches the ground on the top, it won't jump again. Here's my code:
if (isCollideY(platforms[i].getBoundingClientRect(), document.getElementById('spriteNotReal').getBoundingClientRect()) == true) {
if (falling == true && (jumping == false)) {
moveY = platforms[i].getBoundingClientRect().y + 3;
momentumY = 0;
onSolidGround = true;
}
}
if (event.code == 'KeyW' && (moveY <= 300)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}
else if (onSolidGround == false) {
if (momentumY < 0) {
falling = true;
}
else if (momentumY > 0) {
jumping = true;
}
else {
jumping = false;
}
moveX += momentumX / 3 + 1;
document.getElementById("spriteNotReal").src = "jumpmain.gif";
}
My problem was somewhat stupid. After checking the input code, I realized that the jump wasn't happening because it would only jump while on the "platform" I set up to test, not while it was actually on a platform. Here's the improved code:
if (event.code == 'KeyW' && (onSolidGround == true)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}

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.

Function won’t read value of global variable - JavaScript

I'm having trouble here. I have one variable that is supposed to have two states. I want to check to see if the state has changed, and even though it has, my function continues to say that it hasn't. Take a look:
<script type="text/javascript">
var i = 0;
//More unrelated code here
function Talk(url) {
just_done = 0;
//alert("Hey!");
buttons = document.getElementsByTagName("input");
iframe = document.getElementsByTagName("iframe");
//alert("Hey!");
if (url == "scheduler.html" && talk == 0 && just_done == 0) {
trc = parseInt(getCookie("trc"));
if (getCookie("trc") == "NaN") {
trc = 0;
}
if ((getCookie("trc")) == undefined) {
trc = 0;
}
//alert("It started.");
stop = 0;
buttons[0].value=" Stop Listening ";
iframe[0].src=url;
//alert("It should be removed");
talk = 1;
just_done = 1;
}
if (url == "scheduler.html" && talk == 1 && just_done == 0) {
//alert("It stopped.");
stop = 1;
full_time = getTimeSince() + klove;
document.cookie="klove=" + full_time;
buttons[0].value=" Listen Now ";
iframe[0].src="";
// //alert("It should be removed");
talk = 0;
just_done = 1;
//alert(full_time);
}
if (url == "http://emf.mp3.miisolutions.net:80/kl/klove_itunes" && music == 0 && just_done == 0) {
klove = parseInt(getCookie("klove"));
if ((getCookie("klove")) == "NaN") {
klove = 0;
//alert("K-Love seemed to be null.");
}
if ((getCookie("klove")) == undefined) {
klove = 0;
}
//alert("It started.");
stop = 0;
iframe[0].src=url;
// //alert("It should be removed");
music = 1;
just_done = 1;
}
if (url == "http://emf.mp3.miisolutions.net:80/kl/klove_itunes" && music == 1 && just_done == 0) {
//alert("It stopped.");
stop = 1;
full_time = getTimeSince() + klove;
document.cookie="klove=" + full_time;
iframe[0].src="";
// //alert("It should be removed");
music = 0;
just_done = 1;
//alert(full_time);
}
if (url == "http://tunein.streamguys1.com/cnn" && news == 0 && just_done == 0) {
cnn = parseInt(getCookie("cnn"));
if ((getCookie("cnn")) == "NaN") {
cnn = 0;
//alert("CNN seemed to be null.");
}
if ((getCookie("cnn")) == undefined) {
cnn = 0;
}
//alert("It started.");
stop = 0;
iframe[0].src=url;
// //alert("It should be removed");
news = 1;
just_done = 1;
}
if (url == "http://tunein.streamguys1.com/cnn" && news == 1 && just_done == 0) {
//alert("It stopped.");
stop = 1;
full_time = getTimeSince() + cnn;
document.cookie="cnn=" + full_time;
iframe[0].src="";
// //alert("It should be removed");
news = 0;
just_done = 1;
//alert(full_time);
}
}
stop = 0;
Time();
function Time() {
if (stop == 0) {
i = i + 1;
alert(i);
setTimeout(Time, 1000);
}
if (stop != 0) {
alert("I'm done. It's " + i);
}
}
</script>
<input width="10px" height="6px" id="button" type="button" onClick='Talk("scheduler.html")' value=" Listen Now "></input>
Strange that I have this issue, I’ve followed EVERYBODY’s instructions on this very site when they have similar issues, and yet this still won’t work.
EDIT: Let me add that the if statement that sets stop to 1 is within another function.
EDIT 2: Here is more code, so you can trigger my issue.

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

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