Workshop › Klondike Solitaire › Step 21 of 40
tryMove(from, index, to) moves the card at index and every card on top of it from one pile to another, if the
rules allow it: to a foundation only one card that canFound, to a column a card that canStack, never onto the stock or
the waste.
```js
// Move cards from index onwards of pile `from` to pile `to`, if the rules allow it.
function tryMove(from, index, to) {
const cards = piles[from].slice(index)
if (from === to || !cards.length) return false
const allowed = to[0] === 'f' ? cards.length === 1 && canFound(cards[0], piles[to]) : to[0] === 't' && canStack(cards[0], piles[to])
if (!allowed) return false
piles[to].push(...piles[from].splice(index))
return true
}
```slice(index) copies the cards from index to the end without changing the pile; we only look at them.allowed: to a foundation, one card that canFound; otherwise it must be a column and canStack. The stock and the
waste fail both.splice(index) cuts those cards off the source; push(...cards) adds them one by one to the target (... spreads the
array into separate items).Above the hit comment line (// Which card, ...), write tryMove with its comment and leave an empty line after it.
Skills: Arrays and objects, Game states
← Rule 2: building a foundation Turn over the uncovered card →