Cleanup and proper win checking

This commit is contained in:
Vivianne 2023-07-03 01:09:56 -07:00
parent 3ce3051bef
commit da663511f7

View file

@ -20,18 +20,18 @@
(methods
;; The peer is telling us about the turn it took.
[(peer-turn! coords)
[(peer-turn! x y)
(if (not my-turn?)
(begin
(board-choose! board peer-mark coords)
(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! coords)
[(my-turn! x y)
(if my-turn?
(begin
(board-choose! board mark coords)
(board-choose! board mark x y)
(set! my-turn? (not my-turn?))
(board-display board))
(error "It's not my turn."))]))
@ -41,43 +41,38 @@
(define (make-board)
(make-array #f ggg-size ggg-size))
(define (board-ref board coords)
(match coords ((x y) (array-ref board y x))))
(define (board-ref board x y)
(array-ref board y x))
(define (board-choose! board val coords)
(match coords
((x y)
(define ref (board-ref board coords))
(if ref
(error "That space is already occupied with:" ref)
(array-set! board val 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
(lambda (x)
(map (lambda (i) (format #t "[~a]" (print i)))
(λ (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))
(define (row-winner? y)
(apply eq? mark (map (lambda (x) (board-ref board (list x y))) idxs)))
(define (col-winner? x)
(apply eq? mark (map (lambda (y) (board-ref board (list x y))) idxs)))
(define (diag-winner?)
(or
(apply eq? mark (map (lambda (x) (board-ref board (list x x))) idxs))
(apply eq? mark (map (lambda (x) (board-ref board (list x x))) idxs))))
(any (lambda (x) (eq? #t x))
(cons
(diag-winner?)
(append
(map row-winner? idxs)
(map col-winner? idxs)))))
;; 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))))))