Cannot read property of undefined caused by variables - javascript

I have a 2d array called 'map.curCellMap' storing 1's and 0's. I am using the function 'cells.getNeighbourCount' (below) to reference cells in this map.
Within the context of the 'cells.update' function (below) this is returning an undefined error. In firefox it reads 'TypeError: map.curCellMap[nextY] is undefined'. However, if I call 'cells.getNeighbourCount' with hardcoded values it does work.
What gives?
var cells = {
getNeighbourCount: function(x, y) {
/*
/* [y][x]
/* Start a top and move clockwise
*/
var neighbours = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1]],
count = 0;
for(i = 0; i < neighbours.length; i++) {
var curNeighbour = neighbours[i];
//Skip this iteration if neighbour is out of bounds
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS)) {
continue;
}
var nextY = y+curNeighbour[0],
nextX = x+curNeighbour[1];
if(map.curCellMap[nextY][nextX] == 1) {
count++;
}
}
return count;
},
update: function() {
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var numNeighbours = this.getNeighbourCount(x, y),
newCellState;
if(numNeighbours >= 2 && numNeighbours <= 3) {
newCellState = 1;
} else {
newCellState = 0;
}
map.nextCellMap[y][x] = newCellState;
}
}
map.curCellMap = map.nextCellMap;
}
}
var map = {
curCellMap: null,
nextCellMap: null,
//Map functions
init: function() {
this.curCellMap = this.generateRandomMap(0.05);
this.nextCellMap = this.curCellMap;
},
generateRandomMap: function(density) {
/*
/* Generates a random cell map
/* density = 0.00 -> No live cells, density = 1.00 -> All cells live
*/
var map = helpers.create2DArray(ROWS, COLS);
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var rand = helpers.getRandomNum(0, 1);
map[y][x] = (rand <= density) ? 1 : 0;
}
}
return map;
}
}

The problem was
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS)) {
Needed to read
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS-1) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS-1)) {
OOPS!

Related

TypeError in JavaScript when setting the Y position

When running this code I currently getting the error "TypeError: Invalid value for y-coordinate. Make sure you are passing finite numbers to setPosition(x, y)." all of my functions do work are are declared properly. When I use a println and print out letYPos it prints out "NaN" but when I call the function again it prints out the correct value. Does anyone know how I can fix this or if there even is a way to fix this?
var count = 0;
var letYPos = 0;
var y = 3;
function testing()
{
var letXPos = 25;
letYPos += 75;
if (count == 6)
{
println("You have ran out of guesses, the correct anwser was: " + secretWord);
return;
}
var input = readLine("Enter your word: ");
if (input == null)
{
println("You have to enter a word! ");
return;
}
if (input.length != 5)
{
println("That is not a five letter word, please try again.");
return;
}
var x = 3;
for (var i = 0; i < input.length; i++)
{
if (input.includes(secretWord.charAt(i)))
{
var index = input.indexOf(secretWord.charAt(i));
}
if (index == 0) { yellow(3, y ) }
if (index == 1) { yellow(83, y ) }
if (index == 2) { yellow(163, y) }
if (index == 3) { yellow(243, y) }
if (index == 4) { yellow(323, y) } index = null;
}
for (var i = 0; i < input.length; i++)
{
if (input.charAt(i) == secretWord.charAt(i))
{
green(x, y);
}
x += 80;
}
y += 80;
for (var i = 0; i < input.length; i++)
{
for (var a = 0; a <= 5; a++)
{
var txt = new Text(input.charAt(a), font);
txt.setPosition(letXPos, letYPos);
add(txt);
letXPos += 80;
}
}
if (input == secretWord)
{
println("That's Correct, Congratulations!");
return;
}
count++;
setTimeout(testing, 100);
}

How can I make this collision detection possible?

I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.
function BoxSplash()
{
this.sample = [];
var test = false;
this.col = color(129)
this.changeColour = function()
{
this.col = color(random(0,255),random(0,128),random(0,255))
}
this.intersect = function(other)
{
for(var i = 0; i < numberss; i++)
{ var currentBox = this.sample[i]
var d = dist(currentBox.x,currentBox.y,other.x,other.y)
if(d < currentBox.width + other.width)
{
return true;
}
else
{
return false
}
}
noLoop()
}
this.draw = function()
{
stroke(255)
line(0,windowHeight/2,windowWidth,windowHeight/2)
stroke(0)
for(var i = 0; i < numberss; i++)
{
var box = {
x:random(0,windowWidth - 50),
y:random(windowHeight/2 ,windowHeight - 50),
width:50,
height:50,
speedX:random(1,5),
speedY:random(1,5)
}
this.sample.push(box)
}
//use numberss variable to work with gui
for(var i = 0; i < numberss; i++)
{
fill(this.col)
rect(this.sample[i].x,this.sample[i].y,50,50)
}
this.move()
}
this.move = function()
{
for(var i = 0; i < numberss; i++)
{
var shape = this.sample[i]
shape.x += shape.speedX
shape.y += shape.speedY
if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
{
shape.speedX = -shape.speedX
}
if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
{
shape.speedY = -shape.speedY;
}
for(var j = 0; j < numberss; j++)
{
var others = this.sample[j]
var d = dist(shape.x,shape.y,others.x,others.y)
if( i != j && d < shape.width + others.width)
{
test = true;
}
else
{
test = false
}
if(test)
{
this.col = color(255,0,0)
}
}
}
}
}
You should visit this link and transform their circles into your boxes.
1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d
2nd:
if (d < object1.h + object2.h) {
// Enter your code here
}

Trying to do Luhns Algorithm in Javascript but my programming keeps looping indefinitely

As the title says I am trying to write luhns algorithm in Javascript and have it print out a valid card number and what type of card it is whether that be American Express, Mastercard, or Visa.
When ran all it does is continuously loop the alert box. What I want it to print is this is a valid card type and what brand of card it is in the Alert Box.
function checkCreditCard() {
var ccnum = document.getElementById("cardnum").value;
var cardArray = [cardnum]
var temp = ccnum;
var checkerArray;
if (cardType(ccnum) === "AmericanExpress") {
checkerArray = [15];
for (x = 0; x < 15; x++) {
checkerArray[x] = ccnum % 10;
ccnum = ccnum / 10;
}
} else {
checkerArray = [16];
for (x = 0; x < 16; x++) {
checkerArray[x] = ccnum % 10;
ccnum = ccnum / 10;
if (ccnum == 0) {
checkerArray[15] = -1;
checkerArray[14] = -1;
checkerArray[13] = -1;
}
}
}
var summing;
for (x = 1; x < checkerArray.length; x = x + 2) {
if (checkerArray[x] < 0) {
return;
}
checkerArray[x] = checkerArray[x] * 2;
if (checkerArray[x] >= 10) {
summing = summing + checkerArray[x] % 10 + checkerArray[x] / 10
} else {
summing = summing + checkerArray[x];
}
}
for (x = 0; x < checkerArray.length; x = x + 2) {
if (checkerArray[x] < 0) {
return;
}
summing = summing + checkerArray[x];
if (summing == 20) {
alert("This Card is Legit")
} else {
alert("This Card is Invalid")
}
}
function cardType(ccnum) {
var x = {
Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
Mastercard: /^5[1-5][0-9]{14}$/,
AmericanExpress: /^3[47][0-9]{13}$/,
}
for (var l in x) {
if (x[l].test(ccnum)) {
return l;
}
}
return null;
}
}
<input type="text" id="cardnum" onkeyup="checkCreditCard()" />
<span id="valid">Enter a Number and Press Enter</span>
Let's use let
Also let's move the alert OUTSIDE the loop
function cardType(ccnum) {
var x = {
Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
Mastercard: /^5[1-5][0-9]{14}$/,
AmericanExpress: /^3[47][0-9]{13}$/,
}
for (var l in x) {
if (x[l].test(ccnum)) {
return l;
}
}
return null;
}
document.getElementById("cardForm").addEventListener("submit", function(e) {
e.preventDefault();
var ccnum = document.getElementById("cardnum").value;
if (ccnum.length < 16) return
var cardArray = [cardnum]
var temp = ccnum;
var checkerArray;
if (cardType(ccnum) === "AmericanExpress") {
checkerArray = [15];
for (let x = 0; x < 15; x++) {
checkerArray[x] = ccnum % 10;
ccnum /= 10;
}
} else {
checkerArray = [16];
for (let x = 0; x < 16; x++) {
checkerArray[x] = ccnum % 10;
ccnum /= 10;
if (ccnum == 0) {
checkerArray[15] = -1;
checkerArray[14] = -1;
checkerArray[13] = -1;
}
}
}
var summing;
for (let x = 1; x < checkerArray.length; x = x + 2) {
checkerArray[x] *= 2;
if (checkerArray[x] >= 10) {
summing += checkerArray[x] % 10 + checkerArray[x] / 10
} else {
summing += checkerArray[x];
}
}
for (let x = 0; x < checkerArray.length; x = x + 2) {
summing += checkerArray[x];
}
if (summing == 20) {
alert("This Card is Legit")
} else {
alert("This Card is Invalid")
}
})
<form id="cardForm">
<input type="tel" id="cardnum" maxlength="16" />
<span id="valid">Enter a Number and Press Enter</span>
</form>

Despite using an array for keydown (or keyup) functions my code still refuses to let me move while jumping

My code is as follows:
var map = [];
document.body.onkeydown = document.body.onkeyup = function(e){
e = e || event; // to deal with IE
map[e.key] = e.type == 'keydown';
console.log(map)
if (map["ArrowLeft"]) {move("left")}
if (map["ArrowRight"]) {move("right")}
if (map["Spacebar"] || map[" "]) {jump()};
However if i hold down the right arrow key and then press space the character jumps without changing the x pos.
My jumping code is:
async function jump() {
var jh = j;
var i;
for (i = jh * 2; i > -Math.abs(jh) * 2 - 0.5; i -= 0.5) {
rem_rect(70, py, 30, 30)
py -= i
rect(70, py, 30, 30)
await sleep(15)
}
}
My moving code is:
async function move(d) {
var i;
for (i = 0; i < p.length; i++) {
if (d === "right") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] -= ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
else if (d === "left") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] += ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
}
}

Why my JS path-finder algorythm isn't work when I change the matrix

I've to make a code that run a matrix to find the sorthest path to '9' (only walking above the ones, and avoiding the zeros)
In the example below The result correct (5 steps), but if I change the matrix elements positions, the result came wrong..
What can I do? I appreciate any help.
var matrix =
[[1,1,1,1],
[0,1,1,0],
[0,1,0,1],
[0,1,9,1],
[1,1,1,1]]
function runMatrix(matrix){
newPos = 0;
var resultr;
var resultc;
for( var i = 0, lenR = matrix.length; i < lenR; i++ ) {
for(var j = 0, lenC = matrix[i].length; j < lenC; j++){
if( matrix[i][j] == 9 ) {
resultr = i;
resultc = j;
break;
}
}
}
for( var i = 0; i < resultr; i++ ) {
var k = 0;
if(matrix[i+1][k] == 1){
if(matrix[i+1][k+1] == 9 || matrix[i+1][k-1] == 9){
newPos = newPos + 2;
}else{
newPos = newPos + 1;
}
}else{
for(k = 1; k < resultc; i++){
if(matrix[i][k] == 1 || matrix[i][k] == 9){
newPos = newPos + 1
if(matrix[i+1][k] == 1){
if(matrix[i+1][k+1] == 9 || matrix[i+1][k-1] == 9){
newPos = newPos + 2;
}else{
newPos = newPos + 1;
}
i++;
break;
}
}
}
}
}
console.log("Steps: "+newPos)
}
runMatrix(matrix)
update
this matrix doens't work, for example:
[[1,1,1,1],
[0,0,0,1],
[0,0,0,1],
[0,0,9,1],
[0,0,0,0]]
It returns 4

Categories