gpt4 book ai didi

haskell - 如何通过检查是否满足获胜条件来退出 Haskell 中的 IO?

转载 作者:行者123 更新时间:2023-12-02 00:41:01 26 4
gpt4 key购买 nike

我正在尝试在 Haskell 中实现连接四的游戏。此时它基本上可以正常工作,但我很难将游戏已经结束的事实传递给 IO 递归函数。目前,代码将声明我有“函数游戏循环中的非详尽模式”,并且我不知道在实现胜利状态时如何正确退出。

这里是一些代码片段:

data Action = Move Piece State Col   -- do Piece in State
| Start -- returns starting state
data Result = EndOfGame Int -- end of game
| ContinueGame State
deriving (Eq, Show)

type Game = Action -> Result


connectfour :: Game
connectfour Start = ContinueGame ([],[],[],[],[],[],[])
connectfour (Move move state col)
| win move (addPiece move state col) col = EndOfGame move -- player of Piece value move wins
| isTie (addPiece move state col) = EndOfGame 0 -- no moves, tie
| otherwise = ContinueGame (addPiece move state col)


gameLoop (ContinueGame state) player = do
let turn = if player == 1 then 2 else 1
-- Removed code for forum, just prepping values to feed into printboard and printing dialog
putStrLn "Please select a column to enter your piece"
input <- getLine
gameLoop (connectfour (Move turn state (read input :: Int))) turn

TDLR; 我试图返回一个字符串,说明哪个玩家在退出时获胜,但我不知道如何编写一个在游戏循环中检查此情况的条件。

最佳答案

您只需在 gameLoop 中添加 EndOfGame 的情况即可:

gameLoop :: Result -> Int -> IO ()
gameLoop (EndOfGame move) _ = putStrLn ("Game over! Player " ++ show move ++ " won")
gameLoop (ContinueGame state) player = do
{- omitted -}
gameLoop (connectfour (Move turn state (read input :: Int))) turn

“函数 gameloop 中的非详尽模式”警告告诉您 gameLoop 缺少一个案例 - EndOfGame 案例。


另一方面,您可能需要考虑制作一个播放器 ADT:

data Player = One | Two deriving (Show)

otherPlayer :: Player -> Player
otherPlayer One = Two
otherPlayer Two = One

关于haskell - 如何通过检查是否满足获胜条件来退出 Haskell 中的 IO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com