【问题标题】:How to draw a chess board in gloss haskell?如何在光泽haskell中绘制棋盘?
【发布时间】:2021-04-06 03:19:47
【问题描述】:

我刚刚开始使用 haskell 光泽。我对它的功能有所了解。我正在尝试在 haskell 中绘制棋盘。主要问题是一切都被绘制在中心。如果我使用translate 函数,则该板将在随机位置绘制。这可能是因为 translate 从当前位置给定的距离移动,而不是给定的确切点。

gloss haskell 中有没有一种方法可以移动到特定点,例如 setTransformtranslateTo。或者是否有任何函数可以告诉我们当前所在点的坐标。

module Main where

import Graphics.Gloss
import Lib (someFunc)

blockSize :: Float
blockSize = 50

board :: [[Int]]
board = replicate 8 (replicate 8 0)

drawTile :: Float -> Float -> Color -> Picture
drawTile a b col = translate a b $ color col $ rectangleSolid blockSize blockSize

-- drawRow :: Int -> Pictur
-- drawRow =

toInt :: Float -> Integer
toInt = round

getColor :: Float -> Float -> Color
getColor i j = if even $ toInt ((i * 8) + j) then red else blue

screenHeight = 700

screenWidth = 1000

drawing :: Picture
drawing = pictures [drawTile (row * blockSize) (e * blockSize) (getColor row e) | row <- [0 .. 8], e <- [0 .. 8]]

-- moveToStart = viewPortTranslate

main :: IO ()
main = display (InWindow (show board) (screenWidth, screenHeight) (10, 10)) white (translate 0 0 drawing)

编辑:我不想通过使用一些数学技巧来解决这个特定问题。我想知道的是我怎样才能翻译到一个特定的位置。就像我做someFunc 0 0时一样,位置应该转到右上角0 0

如果不可能,请告诉获取当前变换点的方法。

【问题讨论】:

  • 请分享您的尝试。
  • @WillemVanOnsem 我发布了我的代码。请检查一下。
  • 我无法重现:如果我用 even $ toInt (i + j) 替换 getColor,我会得到 imgur.com/a/vuqYe8d
  • @WillemVanOnsem 我猜你无法理解我的问题。板的顺序不是问题。问题是它在中心绘制。虽然我希望它从左上角开始。
  • 那么您也应该查看窗口大小,因此translate (fromIntegral screenWidth/2-8.5*blockSize) (fromIntegral screenHeight/2-8.5*blockSize) $ pictures ...(这是针对 9x9 板,因为您使用了 [0 .. 8],或者您可以将 translate (fromIntegral screenWidth/2-7.5*blockSize) (fromIntegral screenHeight/2-7.5*blockSize) $ pictures 用于 8x8 板。

标签: haskell graphics gloss


【解决方案1】:

没有现有的 Gloss 函数可以拍摄任意图片并将其移动,使其左上角位于屏幕的左上角。 Gloss 中现有的所有变换函数都是相对的,因此无法“绝对”移动到特定点。

您可能做的最好的事情就是安排绘制您的图片,使其原点匹配其左上角,然后将其向上和向左平移屏幕高度和宽度的一半。

import Graphics.Gloss

-- chess board with top-left corner at (0,0), one unit in width and height
chess = scale (1/8) (1/8) $ pictures [square x y | x <- [0..7], y <- [0..8]]
  where square x y =
          Color (if even (x+y) then red else black) $
          translate (fromIntegral x+0.5) (-fromIntegral y -0.5) $ rectangleSolid 1 1

main = display (InWindow "Layout" (1000,700) (10,10)) white $
  -- scale to a 700x700 square (with origin still at top-level corner)
  -- then translate origin from default position at center of window
  -- to top-left corner, by moving half the window width and height
  translate (-500) 350 $ scale 700 700 chess

【讨论】:

  • 感谢您的回答。两个侧面问题,1) 对于 2d 图形,有没有比光泽更好的库(更好的意思是更多的功能)2) haskell 是否适合制作 2d 应用程序?
  • 我认为diagrams(见gallery)可能是我见过的最复杂的2D绘图包,但我用的不多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多