Lifting the Curse


Curses

Originally released with BSD in 80s the cursor optimization library was and is the default tool to make your CLI feel like GUI. Although there are a lot of ways to create a user interface for various viewports available today, there are still use cases where a programmer might want to make some interactive interface for their terminal users. It is now part of all major programming language ecosystems, either bundled with the official distribution or as a third party implementation.

Curses in Python

Python’s curses module is simply a wrapper around its native C interface and comes packaged with the language. Detailed documentation is available here.

Console manipulation

Whole point of curses is to manipulate cursor, which means placing anywhere in the given terminal viewport. This console independent approach treats available space as a matrix with row and column where any location can be addressed as a co-ordinate and used to place the cursor there and print anything. Terminal viewport’s dimension can be obtained using.

rows = curses.LINES
columns = curses.COLS

This space can be treated as a screen buffer with each pixel being a character and resolution defined by the available rows and columns.

Anatomy of curses program

Curses program run in a loop much like a game loop and have following stages

  • initialization of screen
  • setting up the screen options
  • clearing the screen
  • painting the screen character by character
  • refreshing the screen and then looping again for the next frame

    There is no need to have a frame rate as such. The screen buffer can wait for user input or use an internal clock to change the data.

  • exiting the screen and resetting all options

Examples

Few examples to get the feel of libcurses

Conway’s Game of life

Shows basic structure of the curses program and demonstrates user input form usage. source

{{< asciinema Tq6VB9QQ3VeATaOh8CWuj3C6Q >}}

Snake Game

Simple game mechanics to show frame rate control source

{{< asciinema 6SY2tukuFcG3ymYebHwCFZZHe >}}