Connect Four Overview
Basic Types
Some years we have left the choice of representation to be up to the writer. This description is one possible representation:
type Player = Int -- really only two choices
type Posn = (Int, Int) -- coordinates
type Piece = (Player, Posn)
type Board = [Piece]
Functions to write
This is a minimum set of functions to write:
-
draw_board :: Board -> String
Create a String representation of the board.
-
make_move :: Board -> Int -> Player -> Board
Using the number for the column, give a new Board with a piece added. Assumes that the move is legal.
-
is_legal_move :: Board -> Int -> Bool
True if playing in the given column is legal. Used to prevent people from playing in full columns or off the board (e.g., column -5). The computer uses this information to decide whether the next move should be by the same player (attempted move was illegal) or the opponent.
-
is_won :: Board -> Bool
True when either player has four in a row on the board.
Advanced functions
When you are done with the minimum set of functions, consider writing functions that will allow the computer to choose moves, making better and better choices as you work your way down the list.
-
any_legal
gives the first legal move it finds. -
win_or_any_move
is an improvement overany_legal
that makes a winning move if there is one. -
win_or_get_three
is an improvement overwin_or_random_move
that plays to get three in a row if it cannot get four in a row. -
best_move
picks a move that will lead to a win if one exists and avoids moves that lead to losing.
The last function is the most interesting, but will require doing some outside reading on the minimax algorithm, perhaps looking at an implementation for Connect Four.
Design process
Make a plan before you start writing code! I recommend the top-down design that we discussed last year.
Please have each step of the design process visible for each function. It will speed your work and made it easier to understand!
- Purpose for the function
- Signature for the function
- Example(s) showing how the function will work.
- Write the function.
- Testing: put the examples for the function called
work
into a function calledtest_work
.
Technical details
-
Question: How do you print on more than one line?
Answer: Put “\n” in your string. For example: “One line\nSecond line”.
Example:
drawBoard xs = "__XX\n_OOO"
main = do putStrLn $ drawBoard [[0,0,1,1],[0,2,2,2]]
-
Question: What is the difference between ‘X’ and “X”?
Answer: ‘x’ is a character (Char), and “X” is a String, which is a list of characters.
-
Question: How do you define a type shortcut?
Answer: see examples at the top of the page.
-
Question: How do you define a struct?
Answer: it will be easier if you do not do this, but Chapter 8 in LYaH has all of the information you need.