War Card Game

Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.

References:

 Bicycle card company: War game site
 Wikipedia: War (card game)
Related tasks:

 Playing cards
 Card shuffles
 Deal cards for FreeCell
 Poker hand_analyser
 Go Fish


with javascript_semantics
sequence deck = shuffle(tagset(52)),
         hand1 = deck[1..26],
         hand2 = deck[27..52],
         pending = {}
 
function pop1()
    integer res
    {res, hand1} = {hand1[1],hand1[2..$]}
    return res
end function

function pop2()
    integer res
    {res, hand2} = {hand2[1],hand2[2..$]}
    return res
end function

function show(integer c)
    integer r = remainder(c-1,13)+1,
            s = floor((c-1)/13)+1
    printf(1,"%s    ",{"23456789TJQKA"[r]&"SHDC"[s]})
    return r
end function
 
while true do
    if length(hand1)=0 then
        if length(hand2)=0 then
            printf(1,"Game ends as a tie.\n")
            exit
        end if
        printf(1,"Player 2 wins the game.\n")
        exit
    elsif length(hand2)=0 then
        printf(1,"Player 1 wins the game.\n")
        exit
    end if
    integer c1 = pop1(),
            c2 = pop2(),
            r1 = show(c1),
            r2 = show(c2)
    if r1>r2 then
        printf(1,"Player 1 takes the cards.\n")
        hand1 &= shuffle(c1&c2&pending)
        pending = {}
    elsif r1<r2 then
        printf(1,"Player 2 takes the cards.\n")
        hand2 &= shuffle(c1&c2&pending)
        pending = {}
    else -- r1==r2
        printf(1,"Tie!\n")
        if length(hand1)!=0 and length(hand2)!=0 then
            pending &= shuffle(c1&c2&pop1()&pop2())
            printf(1,"??    ??    Cards are face down.\n")
        end if
    end if
end while
