TicTacToe

From HaskellWiki
Revision as of 03:08, 27 January 2007 by Chessguy (talk | contribs)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


Diary of a Tic-tac-toe program

module TicTacToe
where

data Board = String

place :: String -> Int -> Char -> String
place [] _ _ = []
place (x:xs) 1 c = c : xs
place (x:xs) n c = x : (place xs (n-1) c)

firstFree :: String -> Int
firstFree (x:xs) | x == ' ' = 1
                 | otherwise = 1 + (firstFree xs)
main = do
  putStrLn "Enter your move:"
  move1 <- getLine
  let move1Num = read move1
  let board1 = place "         " move1Num 'X'
  let board2 = place board1 (firstFree board1) 'O'
  putStrLn ("New board:" ++ board2)

  putStrLn "Enter your move:"
  move2 <- getLine
  let move2Num = read move2
  let board3 = place board2 move2Num 'X'
  let board4 = place board3 (firstFree board3) 'O'
  putStrLn ("New board:" ++ board4)

  putStrLn "Enter your move:"
  move3 <- getLine
  let move3Num = read move3
  let board5 = place board4 move3Num 'X'
  let board6 = place board5 (firstFree board5) 'O'
  putStrLn ("New board:" ++ board6)

  putStrLn "Enter your move:"
  move4 <- getLine
  let move4Num = read move4
  let board7 = place board6 move4Num 'X'
  let board8 = place board7 (firstFree board7) 'O'
  putStrLn ("New board:" ++ board8)

  putStrLn "Enter your move:"
  move5 <- getLine
  let move5Num = read move5
  let board9 = place board8 move5Num 'X'

  putStrLn ("Final board:" ++ board9)


Hideous, isn't it? Why, thank you! That is, in fact, the point. I want to start with an absolutely hideous piece of code, and add features, re-factoring as I go. It seems to me like there's actually a lot you can do with tic-tac-toe, and so I hope this will turn into something instructive, both for me and for anyone who wants to follow along, and/or contribute.

Feature ideas (in no particular order):

  • output a real board
  • game-end condition check
  • curses-based interface
  • tic-tac-toe variants
  • computer can be x or o
  • two-player mode
  • tournament mode
  • web interface
  • lazy alpha-beta player
  • random square player
  • brute-force player
  • computer vs. computer mode
  • genetically-evolved players