function play2(deck1, history1, deck2, history2) {
if (history1.has(hand(deck1)) || history2.has(hand(deck2))) {
return { winner: 1, deck: deck1, score: calcScore(deck1) };
}
if (deck1.isEmpty()) {
return { winner: 2, deck: deck2, score: calcScore(deck2) };
}
if (deck2.isEmpty()) {
return { winner: 1, deck: deck1, score: calcScore(deck1) };
}
history1.add(hand(deck1));
history2.add(hand(deck2));
const [c1, c2] = [deck1.shift(), deck2.shift()];
if (deck1.toArray().length < c1 || deck2.toArray().length < c2) {
if (c1 > c2) {
deck1.push(c1);
deck1.push(c2);
} else {
deck2.push(c2);
deck2.push(c1);
}
return play2(deck1, history1, deck2, history2);
}
const subGame = play2(
new Denque(deck1.toArray().slice(0, c1)),
new Set(),
new Denque(deck2.toArray().slice(0, c2)),
new Set()
);
if (subGame.winner === 1) {
deck1.push(c1);
deck1.push(c2);
} else {
deck2.push(c2);
deck2.push(c1);
}
return play2(deck1, history1, deck2, history2);
}