Hi, everybody,
I need your help because I’m trying to create a rock, papers, cisors game with the help of the phone sensors and sending values not another but I want to display who won. I can’t return the value because of the function, it never returns any value at all I can’t tell who won. I’ll give you my code ( sorry it’s in French). Hopefully you can help me.
var msgEleve1 = {payload: msg.payload};
var msgEleve2 = {payload: msg.resultat2};
function comparer(choix1, choix2) {
if (choix1 === choix2) {
return 'Egalité !';
} else if (choix1 === 'pierre') {
if (choix2 === 'ciseaux') {
return 'pierre';
} else if (choix2 === 'feuille') {
return 'feuille';
}
} else if (choix1 === 'feuille') {
if (choix2 === 'pierre') {
return 'feuille';
} else if (choix2 === 'ciseaux') {
return 'ciseaux';
}
} else if (choix1 === 'ciseaux') {
if (choix2 === 'pierre') {
return 'pierre';
} else if (choix2 === 'feuille') {
return 'ciseaux';
}
}
}
var resultat=comparer(msgEleve1,msgEleve2);
if (resultat == 'égalité') {
msg.resultat='Egalité'
return msg;
} else if (resultat == msgEleve1) {
msg.resultat='Eleve 1 a gagné'
return msg;
} else {
msg.resultat='Eleve 2 a gagné'
return msg;
}
You need to be sure what is going into the function is what you expect.
For example, your function comparer has no final else and will likely be falling through.
Also in your code, msgEleve1 & msgEleve2 are objects with a .payload property - cant compare objects like this if (choix1 === choix2) { so instead, take the string & compare that instead.
try this - see if it highlights your issue...
var msgEleve1 = msg.payload || "";
var msgEleve2 = msg.resultat2 || "";
const validChoices = ["pierre","feuille","ciseaux"];
if(!validChoices.includes(msgEleve1)) {
node.warn(`msgEleve1 '${msgEleve1}' is not valid`)
return null;
}
if(!validChoices.includes(msgEleve1)) {
node.warn(`msgEleve2 '${msgEleve2}' is not valid`)
return null;
}
function comparer(choix1, choix2) {
if (choix1 === choix2) {
return 'Egalité !';
} else if (choix1 === 'pierre') {
if (choix2 === 'ciseaux') {
return 'pierre';
} else if (choix2 === 'feuille') {
return 'feuille';
}
} else if (choix1 === 'feuille') {
if (choix2 === 'pierre') {
return 'feuille';
} else if (choix2 === 'ciseaux') {
return 'ciseaux';
}
} else if (choix1 === 'ciseaux') {
if (choix2 === 'pierre') {
return 'pierre';
} else if (choix2 === 'feuille') {
return 'ciseaux';
}
}
}
var resultat = comparer(msgEleve1, msgEleve2);
if (!resultat) {
return null; //halt flow
}
if (resultat == 'égalité') {
msg.resultat = 'Egalité'
} else if (resultat == msgEleve1) {
msg.resultat = 'Eleve 1 a gagné'
} else {
msg.resultat = 'Eleve 2 a gagné'
}
return msg; //return msg to next node