Skip to content

Instantly share code, notes, and snippets.

@cindywu
Last active May 5, 2020 03:18
Show Gist options
  • Save cindywu/247cc2e6716a60ce86bc194ec52a135f to your computer and use it in GitHub Desktop.
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)
(cond
((null? win-combos)#f)
((equal? '(x x x) (returncombostate (car win-combos) board)) #t)
((equal? '(o o o) (returncombostate (car win-combos) board)) #t)
(else
(won (cdr win-combos) board))))
(define (returncombostate combo board)
(cond
((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)
0)
((pair? board)
(+ 1 (length (cdr board))))
(else
(error "invalid argument to length")))))
(define (display-board board)
(display "|")
(display (car board))
(display "|")
(display (cadr board))
(display "|")
(display (caddr board))
(display "|")
(newline)
(if (< 0 (length (cdddr board)))
(display-board (cdddr board))
(newline)))
(define (turn board)
(display-board board)
(newline)
(display "make your move:")
(define index (read))
(play (subst (currentplayer board) index board)))
(define (currentplayer board)
(cond
((= (remainder (empty-spaces board) 2) 1)
'x)
((= (remainder (empty-spaces board) 2) 0)
'o)))
(define winner
(lambda (board)
(cond
((eq? (currentplayer board) 'x)'o)
((eq? (currentplayer board) 'o)'x))))
(define full?
(lambda (board)
(= 0 (empty-spaces board))))
(define empty-spaces
(lambda (board)
(cond
((null? board)
0)
((number? (car board))
(+ 1 (empty-spaces (cdr board))))
(else
(+ 0 (empty-spaces (cdr board)))))))
(define subst
(lambda (currentplayer index board)
(cond
((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)
(cond
((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