【问题标题】:Check if a player wins in a tic tac toe game检查玩家是否在井字游戏中获胜
【发布时间】: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


【解决方案1】:
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,这样在所有column 位置我们都可以找到t
  • 必须存在一个column 以便在所有row 位置中找到t
  • 在主对角线上我们发现三个ts
  • 在另一个对角线上,我们发现了三个ts

【讨论】:

    【解决方案2】:

    如果你想做和元组一样的事情,你会这样做:

    if ((b ! 0 ! 0) == t
        && (b ! 0 ! 1) == t
        && (b ! 0 ! 2) == t)
       || ((b ! 1 ! 0) == t
        && (b ! 1 ! 1) == t
        ...
    

    您可以通过使用获胜指数列表的列表来节省几行并进行处理。

    另外,正如@chi 指出的(我的猜测),tileWinsp1winsp2wins 可能应该返回一个 Bool

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多