求助:Haskell井字棋函数实现遇瓶颈,盼技术指导
Haskell 井字棋函数实现指导
- 棋盘基础复用:你已经实现的全空格3x3棋盘(
[[Char]]类型),可以直接作为后续功能的初始状态,比如定义为emptyBoard :: [[Char]]; emptyBoard = replicate 3 (replicate 3 ' ')。 - 安全落子函数:先实现一个能处理非法操作的落子逻辑,确保只有空格位置可被替换:
用makeMove :: [[Char]] -> (Int, Int) -> Char -> Maybe [[Char]] makeMove board (row, col) player | row < 0 || row > 2 || col < 0 || col > 2 = Nothing -- 拦截越界位置 | board !! row !! col /= ' ' = Nothing -- 拦截已占用位置 | otherwise = Just $ updateRow row (updateCol col player) board where updateCol c p row' = take c row' ++ [p] ++ drop (c+1) row' updateRow r f rows = take r rows ++ [f (rows !! r)] ++ drop (r+1) rowsMaybe类型区分有效/无效落子,符合Haskell的类型安全设计。 - 胜负判断逻辑:遍历所有行、列、对角线,检查是否存在连续三个相同的非空格标记:
import Data.List (transpose) checkWinner :: [[Char]] -> Maybe Char checkWinner board = checkLines (board ++ transpose board ++ diagonals) where diagonals = [[board !! 0 !! 0, board !! 1 !! 1, board !! 2 !! 2], [board !! 0 !! 2, board !! 1 !! 1, board !! 2 !! 0]] checkLines [] = Nothing checkLines (line:rest) = case line of [x, x', x''] | x == x' && x' == x'' && x /= ' ' -> Just x _ -> checkLines rest - 平局判断逻辑:当棋盘无空格且无胜者时判定为平局:
isDraw :: [[Char]] -> Bool isDraw board = all (all (/= ' ')) board && checkWinner board == Nothing
如果任务包含其他特定函数要求(比如游戏循环、AI落子等),可以补充具体需求细节后再针对性调整。
内容的提问来源于stack exchange,提问作者sebdev
相关产品推荐
相关产品推荐

