haskell中的简单Snake游戏功能

问题描述 投票:4回答:1

我需要为我的期末学习项目编写一个简单的蛇游戏,但是我被困在最后一个功能上。我想我真的不知道如何完美地使用数据结构。函数doInstruction应该为此测试用例doInstruction (Turn East) (North, [(5, 7), (5, 6)], 2) == (East, [(5, 7), (5, 6)], 2)传回True。我做错了什么?

我的代码:

data Dir = West
    | North
    | East
    | South deriving (Eq, Show)

type Position = (Int, Int)
type Snake = (Dir, [Position], Int)

data Instruction = Move | Turn Dir deriving (Eq, Show)

isOppositeDir :: Dir -> Dir -> Bool
isOppositeDir West East = True
isOppositeDir East West = True
isOppositeDir North South = True
isOppositeDir South North = True
isOppositeDir _ _ = False

oppositeDir :: Dir -> Dir
oppositeDir West = East
oppositeDir East = West
oppositeDir North = South
oppositeDir South = North

nextPos :: Dir -> Position -> Position
nextPos x (a,b)
    | x == West = (a - 1 , b)
    | x == East = (a + 1 , b)
    | x == North = (a , b + 1)
    | x == South = (a , b - 1)
    | otherwise = (a , b)

doInstruction :: Instruction -> Snake -> Snake
doInstruction ins s 
    | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])

我得到的错误:

E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:19: error:
    Data constructor not in scope: Dir :: Dir
   |
34 |     | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
   |                   ^^^

E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:38: error:
    Data constructor not in scope: Dir :: Dir
   |
34 |     | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
   |                                      ^^^

E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:44: error:
    Data constructor not in scope: Position :: Position
   |
34 |     | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
   |                                            ^^^^^^^^

E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:63: error:
    Data constructor not in scope: Position
   |
34 |     | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
   |                                                               ^^^^^^^^
haskell
1个回答
3
投票

您需要使用模式匹配来“解压缩”数据构造函数。 Haskell中的变量以lowercase开头。因此,我们可以解压缩Instruction对象和代表蛇的3元组的包装:

doInstruction :: Instruction -> Snake -> Snake
doInstruction (Turn dir) (_, p, l) = (dir, p, l)
© www.soinside.com 2019 - 2024. All rights reserved.