Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 6 min read

Last card, Wild +4 and optional stacking: how I coded Colour Pile in JavaScript

Every few weeks someone asks if I can add UNO to mympgames, my free arcade of 60+ multiplayer browser games. I can't ship UNO itself. I can ship a shedding game in the same family as Crazy Eights: a 108-card deck, Skip,

Every few weeks someone asks if I can add UNO to mympgames, my free arcade of 60+ multiplayer browser games. I can't ship UNO itself. I can ship a shedding game in the same family as Crazy Eights: a 108-card deck, Skip, Reverse, +2, Wilds, and a "Last card!" call that people actually shout across the table.

That's Colour Pile. The rules live in one file, colour-pile.js, a little over 400 lines. The server uses it to judge every play, and the computer seats use the same functions. This post walks through the rules I ended up encoding, with real code, trimmed a little. Colour Pile is not affiliated with Mattel or UNO.

A 108-card deck in short codes

I didn't want a card object with color, rank and kind fields. A short string is enough, and it survives a JSON trip unchanged:

const COLOURS = ['R', 'Y', 'G', 'B'];
const isWild = (c) => c === 'W' || c === 'W4';
const colourOf = (c) => (isWild(c) ? null : c[0]);
const faceOf = (c) => (isWild(c) ? c : c.slice(1));
const drawValue = (c) => (c === 'W4' ? 4 : faceOf(c) === 'D' ? 2 : 0);

'R7' is a red 7, 'GS' a green Skip, 'BV' a blue Reverse, 'YD' a yellow +2. 'W' and 'W4' are the wilds. V stands for Reverse because R was already red; D is the +2 ("draw"). It's cryptic at first, and easy to test.

The deck is the familiar 108: one 0 and two each of 1รขโ‚ฌโ€œ9, Skip, Reverse and +2 in every colour, plus four Wilds and four Wild +4s. Each player starts with seven cards. The starter on the discard pile is never a wild รขโ‚ฌโ€ if one comes off the stock, it goes back under and we turn another.

What "fits" actually means

Almost every argument at the table is a question about this function:

function fits(st, c, hand) {
  if (st.pending) {
    if (c === 'W4') return true;
    return faceOf(c) === 'D' && faceOf(top(st)) === 'D';
  }
  if (c === 'W') return true;
  if (c === 'W4') return !hand.some((x) => colourOf(x) === st.colour);
  return colourOf(c) === st.colour || faceOf(c) === faceOf(top(st));
}

The last line is the everyday rule: match the current colour, or the face of the top card. A Wild always fits. A Wild +4 only fits when you hold no card of the current colour รขโ‚ฌโ€ a hard check, not a bluff. I left out the "challenge the +4" rule some tables use. It would have needed a second action, a timer, and a way to show a hand. The server already knows whether the +4 was legal, so there is nothing to challenge.

st.pending is the optional stacking rule, off by default. If someone has just played a +2 or +4 and stacking is on, you either play another draw card or take the lot. A +2 stacks on a +2, and a Wild +4 stacks on either. A +2 cannot answer a +4. Letting a +2 cancel into a +4 felt generous; making the next player find another +4, or take the cards, felt closer to how people actually play it.

The opening card can skip you before you've had a turn

After the deal, the person left of the dealer is first รขโ‚ฌโ€ unless the starter says otherwise:

if (f === 'S' || (f === 'V' && st.n === 2)) st.turn = nextSeat(st, st.turn);
else if (f === 'V') {
  st.dir = -1;
  st.turn = st.dealer;
} else if (f === 'D') {
  if (st.stacking) st.pending = 2;
  else {
    drawCards(st, st.turn, 2);
    st.turn = nextSeat(st, st.turn);
  }
}

A starting Skip moves the turn on. So does a starting Reverse when there are only two players, because with two people Reverse is treated as Skip for the whole game. With three or more, it flips the direction and the dealer plays first. A starting +2 either loads a pending stack or forces the first player to draw two and sit out. I used to ignore the starter's action. Friends who grew up with the other convention noticed immediately.

Direction is a seat offset, st.dir is 1 or -1, and nextSeat wraps with a double modulo so a negative direction doesn't produce a negative index:

function nextSeat(st, from, steps = 1) {
  return (((from + st.dir * steps) % st.n) + st.n) % st.n;
}

Skip is advance(st, 2). Reverse with two players is the same. With a bigger table it flips st.dir and advances once, so the new next player is the one who was sitting behind the person who just played.

Draw one, or take the stack

If you have no legal card, you draw one. If that card fits, it's the only one you're allowed to play; if it doesn't, you pass.

if (st.drawn && c !== st.drawn) {
  return { ok: false, error: 'You can only play the card you drew' };
}

When a draw stack is pending and you decline to add to it, "draw" means take the whole pending total, not one card. If the stock runs out, the discard is shuffled back under the top card. If even that is gone and everybody passes, the lowest hand wins the round.

"Last card!" is a window, not a checkbox

This was the part I rewrote most. If you go down to one card and forget to call, anyone can catch you until the next real move, and you draw two. If nobody catches you in time, the penalty still applies when that next move happens.

Playing from two cards down to one, without calling, marks you as exposed. You can call on your turn with two cards, before you play, or after you've been exposed, while the window is open:

if (a.type === 'call') {
  if (h.length === 1 && st.exposed === i) { /* clear the window */ }
  if (h.length === 2 && st.turn === i) { /* pre-call, then play */ }
}

A catch from any other seat draws two for the forgetful player. Every other real action รขโ‚ฌโ€ a play, a draw, a pass รขโ‚ฌโ€ goes through closeWindow first, which applies the same penalty automatically if the call never came. Computer seats wait 1.6 seconds when someone is exposed, so a human has a beat to hit Catch before the bot moves on.

The bots themselves call about 90% of the time when they have two cards. The other 10% they forget, on purpose. A computer that never misses "Last card!" is no fun to sit next to.

Scoring, then the next deal

Emptying your hand ends the round. You score the cards left in everyone else's hands: face value for number cards, 20 for Skip, Reverse and +2, 50 for either wild. First to the target wins รขโ‚ฌโ€ 100, 250 or 500, or a single-round game. In an online room the next deal starts after ten seconds, so a lagging player doesn't hold up the table.

How the bot chooses a card

The computer player is a weighted sort, not a search. It scores each legal card and plays the best:

const score = (c) => {
  let v = 0;
  if (isWild(c)) v -= 40;                 // keep Wilds for later
  if (drawValue(c) && !isWild(c)) v += nextCount <= 2 ? 30 : 5;
  if (faceOf(c) === 'S' || faceOf(c) === 'V') v += nextCount <= 2 ? 25 : 4;
  if (!isWild(c)) v += count(colourOf(c)) * 3 + cardPoints(c) / 10;
  if (c === 'W4' && nextCount <= 2) v += 50;
  return v;
};

It hoards wilds, dumps high-value cards when it can, and saves Skip, Reverse, +2 and Wild +4 for when the next player is about to go out. If it has to play a wild, it names the colour it holds most of. Against attentive humans it is a decent extra seat, not a terror.

What I'd change

I'd still like a challenge action for Wild +4 รขโ‚ฌโ€ some tables want the theatre, even though the legality is already server-side. Stacking is slightly asymmetric, which is why it's a toggle. The bot is greedy: it doesn't plan two turns ahead, and it will sometimes burn a Skip too early.

What I'd keep is the shape: one function that decides whether a card fits, one window for the last-card rule, and a server that will not accept a play the rules function would reject. Most of the bug reports since then have been about the animation of a reversed turn order, not a card that shouldn't have been allowed.

You can try Colour Pile at mympgames.com/play/colour-pile with friends or computer seats, and find the rest of the arcade at mympgames.com.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.