Implement some simple converters for custom types to/from integers

Given n in 0..51, certainly there exists r, s s.t.  `n = 13s + r`
where r in 0..12 and s in 0..3.  `r` is the rank, and `s` is the suit.

ranks are ordered Ace, 2, 3, ..., Queen, King and suits are ordered
Diamond, Club, Heart, Spade.

Therefore there is a 1-1 correspondence between 0..51 and any card in
the deck.

Jokers are a bit less straightforward; for now I'll define them as an
outlier which doesn't exist in the same bounds (which is why they're
the default return for suit in int->suit).  Likely I'll go for -1
representing a Joker.
This commit is contained in:
2025-02-14 17:01:12 +00:00
parent f4b43031ad
commit 76a7017246
2 changed files with 48 additions and 1 deletions

View File

@@ -35,3 +35,44 @@
(deftype cardset () `(and list (satisfies cardsetp)))
(fn int->suit (n) (-> (int-card) suit)
(case (floor n 13)
(0 :Diamonds)
(1 :Clubs)
(2 :Hearts)
(3 :Spades)
(t :Joker)))
(fn suit->int (item) (-> (suit) (integer 0 4))
(case item
(:Diamonds 0)
(:Clubs 1)
(:Hearts 2)
(:Spades 3)
(t 4)))
(fn int->rank (n) (-> (int-card) rank)
(case (mod n 13)
(0 :Ace)
(10 :Jack)
(11 :Queen)
(12 :King)
(t (+ n 1))))
(fn rank->int (rank) (-> (rank) (integer 0 12))
(case rank
(:Ace 0)
(:Jack 10)
(:Queen 11)
(:King 12)
(t (- rank 1))))
(fn int->card (num) (-> (int-card) card)
(cons (int->rank num)
(int->suit num)))
(fn card->int (card) (-> (card) int-card)
(destructuring-bind (rank . suit) card
(->> (suit->int suit)
(* 13)
(+ (rank->int rank)))))

View File

@@ -34,7 +34,13 @@
(defpackage cantedraw.model
(:use :cl :cantedraw.lib.macros :cantedraw.lib.functions)
(:export :int-card :rank :suit :card :cardset))
(:export
;; Types
:int-card :rank :suit :card :cardset
;; Converters
:int->suit :int->rank :int->card
:suit->int :rank->int :card->int
))
(defpackage cantedraw.main
(:use :cl :cantedraw.lib.macros :cantedraw.lib.functions)