I'm trying to code an algorithm that tests to see if a game is possible to be won, given a randomly shuffled deck. I came up with a super simplified solitaire-esque game with like 15 cards, because I'm just messing around and I don't want to try a game with too many options until I've figured out a way to do it. My goal is to test every possible combination of moves, so I wrote a function that returns an array of possible moves when given the state of the board. What I need help with is calling that function every time I change the board. Right now my code calling the function looks like this:
let moves = possibleMoves(piles);
if (moves.length >= 1){
for (let move of moves) {
let nB = piles.slice(0);
nB[move.from].pop();
nB[move.to].push({card: move.card, x: move.to, y: nB[move.to].length});
let m0s = possibleMoves(nB);
if (m0s.length >= 1) {
for (let m0 of m0s){
let nB0 = nB.slice(0);
nB0[m0.from].pop();
nB0[m0.to].push({card: m0.card, x: m0.to, y: nB0[m0.to].length})
}
}
}
}
But obviously I can't just nest that loop infinitely until there are no possible moves (note, I still haven't written code for when there are no possible moves but I'll get to it). The reason I can't just do a while loop is because I want to check every possible move after every possible move, without actually changing the board. Is there a better way to do this?
A recursive function maybe what you are looking for
function recursive(piles){
let moves = possibleMoves(piles);
if (moves.length >= 1){
for (let move of moves) {
let nB = piles.slice(0);
nB[move.from].pop();
nB[move.to].push({card: move.card, x: move.to, y: nB[move.to].length});
recursive(nB)
}
}else{
return;
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.