Skip to content

Instantly share code, notes, and snippets.

Last active May 5, 2020 03:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cindywu/247cc2e6716a60ce86bc194ec52a135f to your computer and use it in GitHub Desktop.
it barely works
(define board '(1 2 3 4 5 6 7 8 9))
(define win-combos '((1 2 3) (4 5 6) (7 8 9) (1 4 7) (2 5 8) (3 6 9) (1 5 9) (3 5 7)))
(define (won win-combos board)
((null? win-combos)#f)
((equal? '(x x x) (returncombostate (car win-combos) board)) #t)
((equal? '(o o o) (returncombostate (car win-combos) board)) #t)
(won (cdr win-combos) board))))
(define (returncombostate combo board)
((null? combo)'())
(else (cons (returnstate (car combo) board) (returncombostate (cdr combo) board)))))
(define returnstate
(lambda (index board)
(if (= 1 index)(car board)(returnstate (- index 1) (cdr board)))))
(define length
(lambda (board)
(cond ((null? board)
((pair? board)
(+ 1 (length (cdr board))))
(error "invalid argument to length")))))
(define (display-board board)
(display "|")
(display (car board))
(display "|")
(display (cadr board))
(display "|")
(display (caddr board))
(display "|")
(if (< 0 (length (cdddr board)))
(display-board (cdddr board))
(define (turn board)
(display-board board)
(display "make your move:")
(define index (read))
(play (subst (currentplayer board) index board)))
(define (currentplayer board)
((= (remainder (empty-spaces board) 2) 1)
((= (remainder (empty-spaces board) 2) 0)
(define winner
(lambda (board)
((eq? (currentplayer board) 'x)'o)
((eq? (currentplayer board) 'o)'x))))
(define full?
(lambda (board)
(= 0 (empty-spaces board))))
(define empty-spaces
(lambda (board)
((null? board)
((number? (car board))
(+ 1 (empty-spaces (cdr board))))
(+ 0 (empty-spaces (cdr board)))))))
(define subst
(lambda (currentplayer index board)
((null? board)'())
((eq? (car board) index)(cons currentplayer (subst currentplayer index (cdr board))))
(else (cons (car board) (subst currentplayer index (cdr board)))))))
(define play
(lambda (board)
((won win-combos board)(display-board board)(display (winner board))(display " is the champion"))
((full? board)(display-board board)(display "its a tie"))
(else (turn board)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment