【发布时间】:2015-05-01 16:54:09
【问题描述】:
作为一名 Haskell 初学者,我编写了一个井字游戏。在游戏的第一个版本中,我使用 9 个元组来表示游戏板。我以前是这样检查中奖条件的;
checkWinner :: Board -> Maybe Player
checkWinner (X,X,X,_,_,_,_,_,_) = Just Player1
checkWinner (_,_,_,X,X,X,_,_,_) = Just Player1
... same thing continues
现在我正在尝试更改我的代码以改用数组,但我不知道如何检查获胜条件。 haskell 中缺少循环使我很难为此制定算法。
这是我当前的代码;
import Data.Array
data Tile = EmptyTile | X | O
data Player = Player1 | Player2
showTile :: Tile -> String
showTile EmptyTile = " "
showTile X = "X"
showTile O = "O"
type Board = Array (Int,Int) Tile
emptyBoard :: Board
emptyBoard = array ((1,1),(3,3)) [((x,y), EmptyTile) | x <- [1,2,3], y <- [1,2,3]]
put :: Board -> Tile -> Int -> Int -> Maybe Board
put b t x y = case b!(x,y) of
EmptyTile -> Just (b // [((x,y), t)])
_ -> Nothing
p1wins, p2wins :: Board -> Bool
p1wins b = tileWins b X
p2wins b = tileWins b O
-- will be called with a board and either x or o
-- and it will tell whether that tile wins
tileWins :: Board -> Tile -> Bool
tileWins b t =
如何在haskell中实现tileWins函数?
【问题讨论】:
-
tileWins究竟应该做什么?它的类型是什么? -
@chi 我已经更新了问题。
标签: arrays haskell tic-tac-toe