I'm following an exercise's tutorial but I cannot understand the logic. The initial setup is a 3x3 board made of a 2D array. Each nested array will have 3 elements, and they will be objects with two properties: x and y, defining their position in the array. (x represent the index and y the position of each element in the nested array so it will be 0,1 or 2 since each nested array has 3 elements). we define an object we will be using: it will be named player and, for now, will have x and y properties set to the following values:
const player = {
x: 1,
y: 1
};
So now the object is placed in the middle of our 3x3 board with position {1,1}
Our next logical step is to start writing some code and to define a function that will allow us, whenever called, depending on the given command (go left or go right) to change the position of the player on the board. To be able to affect the player’s properties and its position, our function has to have access to the player object. Also, we have to set some condition in order not to allow our player to leave the board. And that's the condition I do not understand:
if (thePlayer.y >= 0 && thePlayer.y < 2) {
if (command === 'l') {
thePlayer.y--;
} else {
thePlayer.y++;
}
console.log(`Player has position: x=${thePlayer.x}, y=${thePlayer.y}`);
} else {
console.log("You can't place player outside of the board!");
}
}
Why the first 'if' statement says >=0 and not >0 ?
if the value of y was 0, the player would be on the left side of the board, and then still able to move left because equal to zero and then would go out of the board. What makes me totally blank is the following sentence:
Now, if our player’s property “y” is lower than 0, we’ll get a notification that the player left the board, and that is not allowed.
The exercise is right but I would like to understand!
Aucun commentaire:
Enregistrer un commentaire