Make me a simple chess engine in haskell thats text based.
- User
Make me a simple chess engine in haskell thats text based.
- Assistant
Make me a simple chess engine in haskell thats text based.
Certainly! Below is a simple text-based chess engine written in Haskell. This program allows two players to play a basic game of chess in the terminal. Please note that this is a simplified version:
This example serves as a starting point for a text-based chess game in Haskell.
-- Simple Text-Based Chess in Haskell
import Data.Char (toLower, ord)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
type Position = (Int, Int)
data PieceType = King | Queen | Rook | Bishop | Knight | Pawn deriving (Eq, Show)
data Color = White | Black deriving (Eq, Show)
data Piece = Piece {
pType :: PieceType,
pColor :: Color
} deriving (Eq, Show)
type Board = [[Maybe Piece]]
-- Initialize the board with the standard chess starting positions
initialBoard :: Board
initialBoard =
[ [ Just (Piece Rook White), Just (Piece Knight White), Just (Piece Bishop White), Just (Piece Queen White)
, Just (Piece King White), Just (Piece Bishop White), Just (Piece Knight White), Just (Piece Rook White) ]
, replicate 8 (Just (Piece Pawn White))
] ++ replicate 4 (replicate 8 Nothing) ++
[ replicate 8 (Just (Piece Pawn Black))
, [ Just (Piece Rook Black), Just (Piece Knight Black), Just (Piece Bishop Black), Just (Piece Queen Black)
, Just (Piece King Black), Just (Piece Bishop Black), Just (Piece Knight Black), Just (Piece Rook Black) ]
]
-- Display the board in the terminal
showBoard :: Board -> String
showBoard b = unlines $ [ topLabel ] ++ boardRows ++ [ topLabel ]
where
topLabel = " a b c d e f g h"
boardRows = [ showRank r row | (r, row) <- zip [8,7..1] b ]
showRank r row = show r ++ " " ++ intercalate " " (map showCell row)
showCell Nothing = "."
showCell (Just (Piece pt col)) = pieceChar pt col
pieceChar pt col = case col of
White -> case pt of
King -> "K"
Queen -> "Q"
Rook -> "R"
Bishop -> "B"
Knight -> "N"
Pawn -> "P"
Black -> case pt of
King -> "k"
Queen -> "q"
Rook -> "r"
Bishop -> "b"
Knight -> "n"
Pawn -> "p"
-- Parse user input into a move
parseMove :: String -> Maybe (Position, Position)
parseMove [fromFile, fromRank, toFile, toRank] = do
from <- parsePos (fromFile, fromRank)
to <- parsePos (toFile, toRank)
return (from, to)
where
parsePos (file, rank)
| file `elem` ['a'..'h'] && rank `elem` ['1'..'8'] =
Just (8 - digitToInt rank, ord (toLower file) - ord 'a')
| otherwise = Nothing
digitToInt c = ord c - ord '0'
parseMove _ = Nothing
-- Check if a move is valid (simplified)
isValidMove :: Board -> Color -> Position -> Position -> Bool
isValidMove board player from to =
pieceAt board from /= Nothing && pColor (fromJust (pieceAt board from)) == player
-- Get the piece at a given position
pieceAt :: Board -> Position -> Maybe Piece
pieceAt board (r, c) = board !! r !! c
-- Move a piece on the board
movePiece :: Board -> Position -> Position -> Board
movePiece board from@(fr, fc) to@(tr, tc) =
let piece = pieceAt board from
emptyRow = replicate 8 Nothing
updateRow r row
| r == fr = updateCell fc Nothing row
| r == tr = updateCell tc piece row
| otherwise = row
updateCell c val row = take c row ++ [val] ++ drop (c + 1) row
in zipWith updateRow [0..7] board
-- Switch to the opposite player
nextPlayer :: Color -> Color
nextPlayer White = Black
nextPlayer Black = White
-- The game loop
gameLoop :: Board -> Color -> IO ()
gameLoop board player = do
putStrLn $ showBoard board
putStrLn $ show player ++ "'s turn. Enter your move (e.g., e2e4):"
input <- getLine
case parseMove input of
Just (from, to) ->
if isValidMove board player from to
then do
let newBoard = movePiece board from to
gameLoop newBoard (nextPlayer player)
else do
putStrLn "Invalid move. Try again."
gameLoop board player
Nothing -> do
putStrLn "Invalid input format. Use format like e2e4."
gameLoop board player
main :: IO ()
main = do
putStrLn "Welcome to Simple Haskell Chess!"
gameLoop initialBoard White
To run this program:
Save the code in a file named Chess.hs.
Compile the program using GHC (the Glasgow Haskell Compiler):
ghc Chess.hs -o chess
Run the executable:
./chess
Move Validation: The isValidMove function is very basic and only checks that a piece exists at the source position and belongs to the current player. It doesn't check whether the move is legal according to chess rules.
Game Logic: The program doesn't detect check, checkmate, or stalemate. Players must play honorably or extend the code to include these rules.
Extending the Code: To make this into a functional chess engine, consider:
Data Types:
PieceType: Represents the type of chess pieces.Color: Represents the player's color (White or Black).Piece: Combines PieceType and Color.Board: A 2D list representing the chessboard, where each cell may contain a Piece or be Nothing.Functions:
initialBoard: Sets up the starting positions of the pieces.showBoard: Converts the board into a human-readable string.parseMove: Converts the user's input string into from/to positions.isValidMove: Checks if a move is valid (currently very basic).movePiece: Updates the board with the player's move.nextPlayer: Switches turns between players.gameLoop: The main loop that runs the game.Welcome to Simple Haskell Chess!
a b c d e f g h
8 R N B Q K B N R
7 P P P P P P P P
6 . . . . . . . .
5 . . . . . . . .
4 . . . . . . . .
3 . . . . . . . .
2 p p p p p p p p
1 r n b q k b n r
a b c d e f g h
White's turn. Enter your move (e.g., e2e4):
Players take turns entering moves in algebraic notation (e.g., e2e4), and the board updates accordingly.
Remember, this is a foundational example to illustrate how you might build a text-based chess game in Haskell. Developing a full chess engine involves handling many complex rules and conditions, which you can add incrementally to this base code.
Not yet included in a published release.