我想用haskell
光泽创建一个简单的动画。我希望在前4秒,每个矩形都会将颜色更改为更暗的颜色。问题是,经过相对较长的链接后,没有任何事情发生 -
出现所有矩形并且它们不会改变颜色
这是我使用的以下代码 -
window :: Display
window = InWindow "Simon" (width, height) (offset, offset)
background :: Color
background = black
data SimonGame = Game {
rectangleGreen::Picture,
rectangleRed::Picture,
rectangleBlue::Picture,
rectanglYellow::Picture
} deriving Show
initialState :: SimonGame
initialState = Game
{ rectangleGreen = translate (-100) (0) $ color green $ rectangleSolid 60 60,
rectangleRed = translate (100) (0) $ color red $ rectangleSolid 60 60,
rectangleBlue = translate (0) (100) $ color blue $ rectangleSolid 60 60,
rectanglYellow = translate (0) (-100) $ color yellow $ rectangleSolid 60 60
}
render :: SimonGame -> Picture
render game = pictures
[ rectangleGreen game,
rectangleRed game,
rectangleBlue game,
rectanglYellow game
]
updateBoard :: Float-> SimonGame -> SimonGame
updateBoard 1.0 game = game {
rectangleGreen = translate (-100) (0) $ color (dark green) $ rectangleSolid 60 60,
rectangleRed = translate (100) (0) $ color red $ rectangleSolid 60 60,
rectangleBlue = translate (0) (100) $ color blue $ rectangleSolid 60 60,
rectanglYellow = translate (0) (-100) $ color yellow $ rectangleSolid 60 60
}
updateBoard 2.0 game = game {
rectangleGreen = translate (-100) (0) $ color green $ rectangleSolid 60 60,
rectangleRed = translate (100) (0) $ color (dark red) $ rectangleSolid 60 60,
rectangleBlue = translate (0) (100) $ color blue $rectangleSolid 60 60,
rectanglYellow = translate (0) (-100) $ color yellow $rectangleSolid 60 60
}
updateBoard 3.0 game = game {
rectangleGreen = translate (-100) (0) $ color green $ rectangleSolid 60 60,
rectangleRed = translate (100) (0) $ color red $ rectangleSolid 60 60,
rectangleBlue = translate (0) (100) $ color (dark blue) $rectangleSolid 60 60,
rectanglYellow = translate (0) (-100) $ color yellow $rectangleSolid 60 60
}
updateBoard 4.0 game = game {
rectangleGreen = translate (-100) (0) $ color green $ rectangleSolid 60 60,
rectangleRed = translate (100) (0) $ color red $ rectangleSolid 60 60,
rectangleBlue = translate (0) (100) $ color blue $rectangleSolid 60 60,
rectanglYellow = translate (0) (-100) $ color (dark yellow) $rectangleSolid 60 60
}
updateBoard _ game = game
main :: IO ()
main = animate window background frame
where
frame :: Float -> Picture
frame seconds = render $ updateBoard seconds initialState
答案 0 :(得分:4)
永远不要对浮点数进行等式检查。 (或者,如果你这样做,总是假设结果可能是False
,即使数字在概念上是相等的。)
在你的情况下,这在概念上并非如此,因为animate
在一些有限的时间点被调用;为什么这些包括任何精确的整数秒?
解决此问题的一种简单方法是查找舍入到整秒的时间。
updateBoard :: Int -> SimonGame -> SimonGame
updateBoard 1 game = game { ... }
updateBoard 2 game = game { ... }
...
main = animate window background frame
where
frame :: Float -> Picture
frame seconds = render $ updateBoard (floor seconds) initialState