Search code examples
haskellncurses

NCurses continously update x and y coordinate in moveCursor


I want to make some sort of game with a snake-like mechanic where you use your arrowkeys to change the coordinate of your snake. But since reassignment of variables isn't a thing in haskell I'm unsure of how to do this. Here is my code:

import Control.Monad
import UI.NCurses

main :: IO ()
main = runCurses $ do
    w <- defaultWindow
    forever $ do
        e <- getEvent w Nothing
        updateWindow w $ do
            moveCursor 0 0
            drawString (show e)
        render

I want it to print the key pressed (drawString (show e)) and then change the cursor to previous x+1, previous y+1, then draw the next key pressed then change the cursor and so on.

How do you do this in NCurses? If reassignment was possible it would be simple, like

loop forever:
moveCursor x y
print
x = x+1
y = y+1

But reassignment doesn't work so what can I do instead?


Solution

  • Curse, ncurse, and recurse:

    loop w x y = do
        e <- getEvent w Nothing
        updateWindow w $ do
            moveCursor x y
            drawString (show e)
        render
        loop w (x+1) (y+1)
    
    main = runCurses $ do
        w <- defaultWindow
        loop w 0 0