检查列表中的元素是否高于或低于1

时间:2015-02-01 15:35:55

标签: common-lisp

我正在制作一个模拟扑克游戏的LISP程序。

目前我订购了给定的'手通过这个:

(defconstant order #(2 3 4 5 6 7 8 9 10 J Q K A))

(defun sort< (el1 el2)
  (< (position el1 order)
     (position el2 order)))

我通过&#39;手&#39;一个开始计算它是什么手的函数。

(defun poker (hand)
  (defparameter sortedhand (sort hand 'sort< :key 'first))
  (if (and (equal (second(first sortedhand))(second(second sortedhand)))
           (equal (second(first sortedhand))(second(third sortedhand)))
           (equal (second(first sortedhand))(second(fourth sortedhand)))
           (equal (second(first sortedhand))(second(fifth sortedhand))))
      (print 't)
       (print 'f))
        (print sortedhand))

(我在这里检查他们是否属于同一套装)

手的格式为:

(poker '((3 H)(2 H)(J H)(8 H)(5 H)))

其中3是数字,H是诉讼(心)。

对于像Straight这样的计算手,我必须检查这些牌是否是连续值。

(poker '(8 H)(Q H)(9 H)(10 H)(J H))

例如是Straight Flush。

有没有办法干净利落地做到这一点? 有什么办法可以用我不变的命令来实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

我会把它分成“直”和“齐声”谓词。

(defun straightp (hand)
  (let ((sorted-hand (mapcar #'first (sort (copy-tree hand) #'card<))))
    (every (lambda (card0 card1)
             (= 1 (card-diff card1 card0)))
           sorted-hand
           (rest sorted-hand))))

(defun flushp (hand)
  (apply #'suite= hand))

(defun straight-flush-p (hand)
  (and (straightp hand)
       (flushp hand)))

Card<card-diffsuite=具有相当明显的含义:

(defconstant +card-values+
  #(2 3 4 5 6 7 8 9 10 J Q K A))

(defun card-value (card)
  (position (first card) +card-values+))

(defun card-diff (card0 card1)
  (- (card-value card0) (card-value card1)))

(defun card< (&rest cards)
  (apply #'< (mapcar #'card-value cards)))

(defun suite= (&rest cards)
  (if (endp (rest cards))
      t
      (let ((card-suites (mapcar #'second cards)))
        (every #'eql card-suites (rest card-suites)))))

(未测试)。