79 lines
2.4 KiB
Scheme
79 lines
2.4 KiB
Scheme
(define-module (gib-gab-gob game)
|
|
#:use-module (goblins)
|
|
#:use-module (goblins vat)
|
|
#:use-module (goblins actor-lib methods)
|
|
#:use-module (goblins actor-lib sealers)
|
|
#:use-module (goblins actor-lib selfish-spawn)
|
|
#:use-module (ice-9 match)
|
|
#:use-module (srfi srfi-1)
|
|
#:use-module (ice-9 rdelim)
|
|
#:export (^ggg-controller))
|
|
|
|
;; Actual Tic Tac Toe game
|
|
(define ggg-size 3) ;; tic tac toe with more than 3x3 grid?
|
|
|
|
(define (^ggg-controller bcom initiator? peer)
|
|
(define mark (if initiator? 'x 'o))
|
|
(define peer-mark (if initiator? 'o 'x))
|
|
(define board (make-board))
|
|
(define my-turn? (not initiator?))
|
|
|
|
(methods
|
|
;; The peer is telling us about the turn it took.
|
|
[(peer-turn! x y)
|
|
(if (not my-turn?)
|
|
(begin
|
|
(board-choose! board peer-mark x y)
|
|
(set! my-turn? (not my-turn?))
|
|
(board-display board))
|
|
(error "It's my turn!"))]
|
|
;; TODO: This needs to go somewhere else so the peer can't move for us!
|
|
[(my-turn! x y)
|
|
(if my-turn?
|
|
(begin
|
|
(board-choose! board mark x y)
|
|
(set! my-turn? (not my-turn?))
|
|
(board-display board))
|
|
(error "It's not my turn."))]))
|
|
|
|
;; Board logic
|
|
|
|
(define (make-board)
|
|
(make-array #f ggg-size ggg-size))
|
|
|
|
(define (board-ref board x y)
|
|
(array-ref board y x))
|
|
|
|
(define (board-choose! board val x y)
|
|
(define ref (board-ref board x y))
|
|
(if ref
|
|
(error "That space is already occupied with:" ref)
|
|
(array-set! board val y x)))
|
|
|
|
(define (board-display board)
|
|
(define (print m) (or m " "))
|
|
;; this is .. probably messy?
|
|
(array-slice-for-each-in-order
|
|
1
|
|
(λ (x)
|
|
(map (λ (i) (format #t "[~a]" (print i)))
|
|
(array->list x))
|
|
(format #t "\n"))
|
|
board))
|
|
|
|
(define (board-winner? board mark)
|
|
;; e.g. '(0 1 2)
|
|
(define idxs (iota ggg-size))
|
|
;; true, if any item in list is non-false
|
|
(define (any? l) (and (any identity l) #t))
|
|
;; Iterate through iota calling fn and check if all are true
|
|
(define (iter-all? fn) (apply eq? mark (map fn idxs)))
|
|
;; Iterate through the rows and see if any are winners
|
|
(define (row-winner? b)
|
|
(any? (map (λ (y) (iter-all? (λ (x) (board-ref b x y)))) idxs)))
|
|
(or (row-winner? board)
|
|
(row-winner? (transpose-array board 1 0))
|
|
;; check the two diagonals
|
|
(iter-all? (λ (x) (board-ref board x x)))
|
|
(iter-all? (λ (x) (board-ref board x (- ggg-size x 1))))))
|