Skip to content

Instantly share code, notes, and snippets.

@cindywu
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
Embed
What would you like to do?
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