2021-11-08

Interactive graphics demo using Haskell on code.world.

You can write Haskell using https://code.world/haskell. There is a demo video for CPS students (kind of poor sound quality).

Demo Code

{-# LANGUAGE OverloadedStrings #-}

import CodeWorld

{--
main = do drawingOf $ pictures [ myRect2, myRect, coordinatePlane ]
  where myRect = colored red $ translated 4 2.5 $ solidRectangle 8 5
        myRect2 = colored (RGBA 0 0 1.0 0.5) $ solidRectangle 6 2
--}

data GameState = GameState { showRed :: Bool, showBlue :: Bool}

initialModel = GameState True True

eventHandler :: Event -> GameState -> GameState
eventHandler (KeyPress _) game@(GameState r b) = game{showRed = not r}
eventHandler (PointerPress _) (GameState r b) = GameState r (not b)
eventHandler _ game = game

main = do activityOf initialModel eventHandler drawHandler 

maybeVisible color True = color
maybeVisible color False = (RGBA 0 0 0 0) -- transparent

drawHandler :: GameState -> Picture
drawHandler g@(GameState r b) =
  pictures [ blueRect,
             redRect ]
     where redRect = colored (maybeVisible red (showRed g))$ 
                  translated 4 2.5 $ 
                  solidRectangle 8 5
           blueRect = colored (maybeVisible (RGBA 0 0 1.0 0.5) b)$
                  solidRectangle 6 2

Notes on Code

There are two “more difficult than necessary” items shown above:

  • The eventHandler for KeyPress shows an alternate way to update a struct that is equivalent to the Racket code (struct-copy GameState game [showRed (not r)])
  • The drawHandler variable redRect shows how to use the showRed accessor to get the r boolean out of the GameStruct.
Last modified August 18, 2023: 2022-2023 End State (7352e87)