Skip to content

Instantly share code, notes, and snippets.

@cindywu
Created May 8, 2020 12:34
Show Gist options
  • Save cindywu/03c05e8f03122971668083a9b84409cf to your computer and use it in GitHub Desktop.
Save cindywu/03c05e8f03122971668083a9b84409cf to your computer and use it in GitHub Desktop.
computer player 'o picks 2
(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 (humanturn board)
(display-board board)
(newline)
(display "make your move:")
(define index (read))
(play2 (subst (currentplayer board) index board)))
(define (computerturn board)
(display-board board) ; '(x 2 3 4 5 6 7 8 9)
(play (subst 'o 2 board)) ;' (x o 3 4 5 6 7 8 9)
)
(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 (humanturn board)))))
(define (play2 board)
(if (eq? (currentplayer board) 'x)
(humanturn board)
(computerturn board)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment