It has a system to go through an array checking if any of the allowed words have been entered:
<!-- norte, sur, este, oeste -->
I assign the value to accionActual
using a input.value.
, leaving something like this:
accionActual="norte";
function recorrerArray(accionJugador) {
for (let i = 0; i < accionesPermitidas.length; i++) {
if (accionJugador.indexOf(accionesPermitidas[i]) !== -1) {
accionActual = accionesPermitidas[i];
informacionJuegoMensaje = "El jugador ha decidido: "+accionActual;
elegirMapa();
break;
} else {
elegirMapa();
}
}
}
Then, based on which word was written, an action will be done with a switch.
function elegirMapa() {
switch (accionActual) {
case "norte":
posicionJugador -= 3;
actualizarInformacion();
actualizarPosicionJugador();
break;
case "este":
posicionJugador -= 1;
actualizarInformacion();
actualizarPosicionJugador();
actualizarImagenesMapa();
break;
case "sur":
posicionJugador += 3;
actualizarInformacion();
actualizarPosicionJugador();
actualizarImagenesMapa();
break;
case "oeste":
posicionJugador += 1;
actualizarInformacion();
actualizarPosicionJugador();
actualizarImagenesMapa();
break;
default:
informacionJuegoMensaje = "No conozco esa accion";
actualizarInformacion();
break;
}
}
The problem: if I write "west" or "east", the action of "east" will be executed.
How can I make it validate "west" as well, without "east" being taken as it were? ?
NOTE: I know that the program will look for the word specifically, and if I enter something like "I want to go north", it will find "north". That is, the first word that is formed will be the one that it finds, because if "west" is formed first, it does not recognize it?
It turns out that in this case, the order of the factors does alter the product.
Since the array is searched in order, and the first word that appears is "east", then the instruction
accionJugador.indexOf(accionesPermitidas[i]) !== -1
will always find the word "east", even when what is written is "west" because it does a sequential search, not by words , of the four letters positionally... in fact, what is happening is that one writes "west"... and that already contains "east".It seems to me that a simpler way, and one that would get rid of the problem, is to use regular expressions to extract the address of the text obtained through the input.
Example:
The regular expression is used
/norte|sur|este|oeste/
to declare the valid addresses, then it is usedmatch
to check if the string includes one of those words, if it does, it returns an array including the word, otherwise it returnsnull
.