Files
scheme-for-kids/kot-kit.scm

73 lines
2.2 KiB
Scheme
Raw Normal View History

2013-12-11 19:01:18 +04:00
(import (rnrs io ports (6))) ;; Guile
2014-04-18 10:40:19 +04:00
;;(require rnrs/io/ports-6) ;; Racket
2013-12-11 19:01:18 +04:00
2013-12-12 19:17:38 +04:00
(setlocale LC_ALL "") ;; Guile
2013-12-11 19:01:18 +04:00
(define (println . params)
2013-12-12 19:17:38 +04:00
(for-each (lambda (x) (display x)) params)
(newline))
2013-12-11 19:01:18 +04:00
2014-04-18 10:40:19 +04:00
;; Helper
2013-12-12 19:17:38 +04:00
(define (answer . params)
(for-each (lambda (x) (display x)) params)
(flush-output-port (current-output-port))
(get-line (current-input-port)))
2013-12-11 19:01:18 +04:00
(define (yes? . params)
2013-12-12 19:17:38 +04:00
(let ((ans (apply answer (append params '("? ")))))
2013-12-11 19:01:18 +04:00
(if (= (string-length ans) 0)
2014-04-18 10:40:19 +04:00
#f
(or
(char-ci=? (string-ref ans 0) #\y)
(char-ci=? (string-ref ans 0) #\д)))))
2013-12-11 19:01:18 +04:00
;; Copy tree
(define (copy-pet-tree pet-tree)
(if (null? pet-tree)
2014-04-18 10:40:19 +04:00
'()
(list (car pet-tree)
(cadr pet-tree)
(copy-pet-tree (caddr pet-tree))
(copy-pet-tree (cadddr pet-tree)))))
2013-12-11 19:01:18 +04:00
;; Main function
(define (game-round pet-tree top-pet-name)
(let walk-pet-tree ((pet-tree pet-tree)
(y-pet (list top-pet-name)))
(if (null? pet-tree)
2014-04-18 10:40:19 +04:00
(if (yes? "Это " (car y-pet))
(begin
(println "Ура, я угадал!")
'())
(let* ((name (answer "Сдаюсь! Кто это? "))
(feature (answer "Чем " name " отличается от " (car y-pet) "? ")))
(list name feature '() '()))) ;; return new pet
(append
(list (car pet-tree)
(cadr pet-tree))
(if (yes? (cadr pet-tree))
(list (walk-pet-tree (caddr pet-tree) pet-tree)
(copy-pet-tree (cadddr pet-tree)))
(list (copy-pet-tree (caddr pet-tree))
(walk-pet-tree (cadddr pet-tree) y-pet)))))))
2013-12-11 19:01:18 +04:00
(define TREE-FILE-NAME "data.sexp")
;; Main LOOP
(let loop ((pet-tree
2014-04-18 10:40:19 +04:00
(if (file-exists? TREE-FILE-NAME)
(call-with-input-file TREE-FILE-NAME read)
'())))
2013-12-11 19:01:18 +04:00
(let ((tree (game-round pet-tree "Кот")))
2013-12-12 19:17:38 +04:00
(newline)
2013-12-11 19:01:18 +04:00
(if (yes? "Играем еще")
2014-04-18 10:40:19 +04:00
(loop tree)
(begin
;; Racket
;; (if (file-exists? TREE-FILE-NAME) (delete-file TREE-FILE-NAME) #f)
2013-12-11 19:01:18 +04:00
2014-04-18 10:40:19 +04:00
(call-with-output-file TREE-FILE-NAME (lambda (p) (write tree p)))
))))
2013-12-11 19:01:18 +04:00
2014-04-18 10:40:19 +04:00
;; vim: set ts=2 sts=2 sw=2 expandtab: