作为Haskell的初学者,我编写了一个tic tac toe游戏。在游戏的第一个版本中,我用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
函数?
答案 0 :(得分:4)
data Tile = EmptyTile | X | O deriving Eq
tileWins :: Board -> Tile -> Bool
tileWins b t =
any (\row -> all (\col -> b!(row,col) == t) [1..3]) [1..3] ||
any (\col -> all (\row -> b!(row,col) == t) [1..3]) [1..3] ||
all (\rc -> b!(rc,rc) == t) [1..3] ||
all (\rc -> b!(rc,4-rc) == t) [1..3]
说明:要使t
赢得以下其中一项,必须申请
row
,以便在所有col
umn位置找到t
col
umn,以便在所有row
位置找到t
t
s t
s 答案 1 :(得分:0)
如果你想做与元组相同的事情,你会这样做:
<div id='cssmenu' class="align-center">
<ul>
<li><a href='#'>Home</a>
</li>
<li class='active has-sub'><a href='#'>Products</a>
<ul>
<li class='has-sub'><a href='#'>Product 1</a>
<ul>
<li><a href='#'>Sub Product</a>
</li>
<li><a href='#'>Sub Product</a>
</li>
</ul>
</li>
<li class='has-sub'><a href='#'>Product 2</a>
<ul>
<li><a href='#'>Sub Product</a>
</li>
<li><a href='#'>Sub Product</a>
</li>
</ul>
</li>
</ul>
</li>
<li><a href='#'>About</a>
</li>
<li><a href='#'>Contact</a>
</li>
</ul>
</div>
您可以使用获胜指数列表列表来保存几行,然后处理。
另外,正如@chi所说(我的猜测),if ((b ! 0 ! 0) == t
&& (b ! 0 ! 1) == t
&& (b ! 0 ! 2) == t)
|| ((b ! 1 ! 0) == t
&& (b ! 1 ! 1) == t
...
,tileWins
和p1wins
应该返回p2wins
。