[Find your Hat] Bug when placing the hat

Hello everyone,

I am currently back on Node.js and the challenge “Find your Hat”.

Working on the update of the field, I tried to place the hat on a random location. But for some reason, I can’t place it outside of the first row (so [O]).

The exact error is :

newField[2][0] = hat;
                      ^

TypeError: Cannot set properties of undefined (setting '0')

Here is my whole code:

const prompt = require('prompt-sync')({sigint: true});

const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';


const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  });

const createRandomNumber = () =>{
    return Math.floor(Math.random() * 8);
}
const createField = () => {
    

    let newField = [];
   
   for(i = 0; i <= 15; i ++) {
       let newArray = [];
       for (j = 0; j <=10; j++) {
           let randomNumber = createRandomNumber();
           
            
            if (randomNumber %2 == 0 ) {
               newArray.push(fieldCharacter);
               
               randomNumber = createRandomNumber();
               
            }
            else if (randomNumber %3 == 0) {
              newArray.push(hole);
              
              randomNumber = createRandomNumber();
               
            }
            else {
              newArray.push(fieldCharacter);
               
              randomNumber = createRandomNumber();
            }
           
          
       }
       newArray.push("\n");
       newField.push(newArray);
       newField[0][0] = pathCharacter;
       let hatX = Math.floor(Math.random() * 15);
       let hatY = Math.floor(Math.random() * 10);
       newField[2][0] = hat;
   }
   
 
return newField;
  
};

class Field {
  constructor (field, y, x) {
    this.field =  createField()
    this.print
    this.y = 0
    this.x = 0
    this.playGame

    
}
print() {
    let result = this.field.join("").replaceAll(",", "");
 
 console.log(result);
    
}
playGame(input) {
 if (input == 'r') {
 //in construction
 }
 
}



};

const myField = new Field();

myField.print();

const input = prompt("Which way ? r, l, u, d");
console.log(`You chose ${input}`);
myField.playGame(input);

Is there a problem with my field in general ? Thank you very much !

newField[2][0]

is undefined.

If newField[2] is defined, it would also have to be something that’s indexable like an array.

Thanks for your answer !

I checked again and found the error: I put the code placing the hat inside the loop to create the field, which means it tried to place the hat inside an array which was not (yet) defined.

Moved it outside and nod works perfectly :slight_smile: