History repeats [Desiderius #14]

Two weeks ago I talked about the playing logic and the improvements kot_2010 made, but there is a bit more info I want to share. Let’s talk a little bit more about how I designed the playing history. History is a list of lists, where each inner list is a trick. Visually:

//An empty game:
[
[]
]
//One card played:
[
[aceOfSpades]
]
//Three cards played:
[
[aceOfHearts, queenofClubs, aceOfSpades]
]
//Five cards played:
[
[kingofPain*] ,
[eigthOfSpades, aceOfHearts, queenofClubs, aceOfSpades]
]

Two notes: I put played cards at the beginning of the list. F# makes it easy to inspect the head (with h :: t) and I am guessing I more often want to look at the most recently played card than the earliest one.

Also, of course I could also just throw the whole thing in one flat list and take ((mod 4) Length history) from the top to get the most recent trick. Somehow that felt unnatural to me as there is such a string grouping going on, but I might change my mind.

So, here is the thing! If you pay close attention to my playing logic code, you might wonder why there is not a special case for when thisTrick has 4 cards, because in that case, we do not have to follow suit, and may also play a fresh card (the highest, for example) This is because I have done quite a smart thing in adding cards to the history:

   let rec addToHistory (history: List<List>)(card: Desi.Card) = 
      match history with

      | h :: t when List.length h = 0 -> //if this trick is empty we add a card
         [card] :: t

      | h :: t when List.length h = 3 -> //add the last card and start a new one*
         [] :: (card :: h) :: t

      | h :: t -> //in all other cases, get the trick and add to it
          (card :: h) :: t

      //* this is used to make the play logic simpler, we can now always get the
      //head of history and thus obtain the latest trick 

So, 4 cards played looks like this:

//Four cards played:
 [
 [] ,
 [eigthOfSpades, aceOfHearts, queenofClubs, aceOfSpades]
 ]
rather than like this:
 //Four cards played:
 [
 [eigthOfSpades, aceOfHearts, queenofClubs, aceOfSpades]
 ]

Okay it makes the adding logic harder, but that is write once, and then benefit for ever of easily getting the latest trick.

*that’s no real card in bridge, I just have a thing for Sting 😀