The number that is assigned to the rows begins at 0 and increases one per row. You must assign a variable to the row in order to log it to the console:
After a row is assigned a variable, you can access a single element inside it. Using a similar notation we can pull out one element from one array:
console.log(`firstshipisboard[1][2]`)// using the second brackets is how you access the columns in the row you identify// "firstRow1" is accesing the first element in the first array
Matrix Iteration
Each elements in the matrix is an array, so we have to iterate over each row using a loop:
for(leti=0,i<board.length;i++){// a single rowletrow=board[i];// loop over each elementfor(let=j,j<row.length;j++){letcolumn=row[j];if(column==="s"){console.log(`Shipislocatedat${row}rowand${column}column`);}}// i used "i" and "j" to assign coordinates when the ship is located
Turns
To create turns i will create a loop that iterates 10 times
for(leti=0;i<10;i++){}
Randomizing
Randon Index, in order to choose a random square we can use the Math.random function:
for(leti=0;i<10;i++){}functiongetRandomNum(){returnMath.floor(Math.random()*board.length);// using "board.length creates the max number the generator can use}// Math.random will return a random number between 0 and 1 so we use" * 5 " to make it a whole number we can useconsole.log(getRandomNum());console.log(getRandomNum());console.log(getRandomNum());console.log(getRandomNum());
Selecting a Random Square
Using the same Math.random function, i will create code that displays a certain square's coordinates:
Top comments (0)