Search code examples
haskellgraphicsgloss

How to draw a chess board in gloss haskell?


I am just started haskell gloss. I learnt a little about it functions. I am trying to draw a chess board in haskell. The main problem is that everything is being drawn in the center. If I used the function translate the board is being draw at random position. That's probably because translate moves from moves the distance given from current position not to the exact point which is given.

Is there a way in gloss haskell so that we can move to a specific point like setTransform or translateTo. Or is there any function which tells coordinates of current point at which we are at.

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)

Edit: I don't want to fix this specific problem by using some math tricks. What I want to know is that how can I translate to a specfic position. Like when I do someFunc 0 0 the position should go to 0 0 top right corner.

If its not possible please tell the way to get the current transform point.


Solution

  • There is no existing Gloss function that will take an arbitrary picture and move it so its top-left corner is in the top-left corner of the screen. All existing transformation functions in Gloss are relative, so there's no way to make an "absolute" move to a specific point.

    The best you can probably do is arrange to draw your picture so its origin matches its top-left corner, and then translate it up and left by half the screen height and width.

    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