Skip to content

Instantly share code, notes, and snippets.

@omegatakuma
Created June 3, 2012 01:15
Show Gist options
  • Save omegatakuma/2860807 to your computer and use it in GitHub Desktop.
Save omegatakuma/2860807 to your computer and use it in GitHub Desktop.
三目並べ
#!/usr/local/bin/gosh
(use srfi-27)
(define *board* (make-vector 9 'empty))
(define (board-ref n)(vector-ref *board* n))
(define (board-set! n m)(vector-set! *board* n m))
(define (print-board)
(let ((lst '((maru . "◯") (batu . "×") (empty . "."))))
(dotimes (x 9)
(format #t "~A " (cdr (assq (vector-ref *board* x) lst)))
(if (or (= x 2) (= x 5) (= x 8))(newline)))))
(define (input)
(let loop ()
(display "input> ")(flush)
(let ((pos (read)))
(if (eq? (board-ref pos) 'empty)
(print *board*)
(begin
(display "Error")(newline)
(loop))))))
(define (computer)
(let loop ()
(let ((n (random-integer 9)))
(if (eq? (board-ref n) 'empty)
(board-set! n 'batu)
(loop))))
(define win-position '(
(0 1 2)
(3 4 5)
(6 7 8)
(0 3 6)
(1 4 7)
(2 5 6)
(0 4 5)
(2 4 6)))
(define (three? turn)
(map (lambda(x)
(map (lambda(y)
(if (eq? (board-ref y) turn) #t #f))x))win-position))
(define (game-end?)
(let loop ((m (three? 'maru))(b (three? 'batu)))
(cond
((null? m)
#t)
((= (count #t (car m)) 3)
(display "You win!!!")(flush)(exit))
((= (count #t (car b)) 3)
(display "You loss!!!")(flush)(exit))
((not(memq 'empty (vector->list *board*)))
(display "draw!!!!!")(flush)(exit))
(else (loop (cdr m) (cdr b))))))
(define (count key lst)
(let loop ((lst lst)(n 0))
(cond
((null? lst)n)
((eq? (car lst) key)(loop (cdr lst) (+ n 1)))
(else (loop (cdr lst) n)))))
(define (position key lst)
(let loop ((lst lst)(n 0))
(cond
((null? lst) #f)
((eq? key (car lst))n)
(else (loop (cdr lst) (+ n 1))))))
(define (start)
(print-board)
(let loop ()
(input)
(computer)
(print-board)
(game-end?)
(loop)))
(define (main args)
(start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment