;; The cards ;; (define (deal) (+ 1 (random 10))) ;; The hands ;; (define (make-hand up-card total) (cons up-card total)) (define (up-card-hand hand) (car hand)) (define (total-hand hand) (cdr hand)) (define (add-card-hand hand new-card) (cons (up-card-hand hand) (+ new-card (total-hand hand)))) ;; Play hand loop ;; (define (play strategy my-hand opponent-up-card) (cond ((> (total-hand my-hand) 21) my-hand) ; I lose... give up ((strategy my-hand opponent-up-card) ; hit? (play strategy (add-card-hand my-hand (deal)) opponent-up-card)) (else my-hand))) ; stay ;; The Engine ;; (define (twenty-one player-1-strategy player-2-strategy) (let* ((new-hand-player-2 (deal)) (player-2-initial-hand (make-hand new-hand-player-2 new-hand-player-2))) (let* ((new-hand-player-1 (deal)) (player-1-hand (play player-1-strategy (make-hand new-hand-player-1 new-hand-player-1) (up-card-hand player-2-initial-hand)))) (if (> (total-hand player-1-hand) 21) 2 (let ((player-2-hand (play player-2-strategy player-2-initial-hand (up-card-hand player-1-hand)))) (cond ((> (total-hand player-2-hand) 21) 1) ((> (total-hand player-1-hand) (total-hand player-2-hand)) 1) (else 2)))))))