I'm trying to write a function for a card game which will allow players to exchange a card in their hand for a card in their opponents'. I'm just starting out, so I know I'm running into a problem with accessing the arrays when I do it - my program currently gets hung up on the first step, and won't recognize the input "player1" as a match for the object player1 in the players array. Is there an easy way to do that? Do I need to add a "name" key or something similar to my player object, and have the prompt ask for that?
function player(coins, active) {
this.coins = coins;
this.active = active;
this.hand = ["Bakery", "Wheat Field"]
}
var player1 = new player(0, true);
var player2 = new player(0, false);
var activePlayer = player1;
var allPlayers = [player1, player2];
function cardSwap() {
var targetPlayer = prompt("Which player do you want to exchange with?");
for (i = 0; i < allPlayers.length; i++) {
if (allPlayers[i] === targetPlayer) {
targetPlayer = allPlayers[i];
} else {
console.log ("That player doesn't exist!");
cardSwap();
}
}
console.log(targetPlayer["hand"]);
var targetCard = prompt("Which of their cards do you want?");
console.log(activePlayer["hand"]);
var giveCard = prompt("Which of your cards will you give in exchange?");
for (i = 0; i < targetPlayer["hand"].length; i++) {
if (targetPlayer["hand"][i] === targetCard) {
delete targetPlayer["hand"][i];
targetPlayer["hand"].push(giveCard);
break;
} else {
console.log(targetPlayer + " doesn't have that card!");
break;
}
}
for (i = 0; i < activePlayer["hand"].length; i++) {
if (activePlayer["hand"][i] === giveCard) {
delete activePlayer["hand"][i];
activePlayer["hand"].push(targetCard);
break;
} else {
console.log("You don't have that card!");
break;
}
}
};
cardSwap();
console.log(allPlayers);