As we discussed on our previous Curses tutorial which can be found here, a library that supplies a terminal-independent screen-painting and keyboard-handling facility for text based terminals, we already showed how the library works painting a moving dot on the screen, but now we will use it to our advantage to develop a Menu for our curses application, in this case we will be building a “Snake game”, so the Menu will work accordingly.
We will start by defining a few methods that will help us to cycle thru our Menus with ease, and also will help our code to look neat and organized.
paint_title()
Since we will be navigating to many options in our application, it’s important to define a new title every time we have a different functionality in the screen.
def paint_title(win,var): |
paint menu()
This methods receives a curses window, since everything we will be painting will be painted on this window, first we paint a title with the paint_title() method we built, also we define our window timeout to -1 (making sure it waits until an input is received).
def paint_menu(win): |
wait_esc()
our wait_esc() function is a simple function that will wait for the [ESC] key to be pressed.
def wait_esc(win): |
Core Application
Now we will start building our core application, since we are building a curses application we will borrow most of the configurations already explained in the last tutorial and as the first thing the user will see will be the Menu, we will also paint it as follows:
stdscr = curses.initscr() #initialize console |
Functional Menu
Finally we will have simulated switch statement thru an if-elif-else sentence, and will run this statement as long as the exit option (6) is not pressed, since curses uses ASCII for keys and we will be using number 1-6, the ascii equivalents will be 49-54, every time we enter an option we will paint the option title on the screen and call our wait_esc() method, that will wait for [ESC] to be pressed and then we will return to the Main Menu by painting it and defining our keystroke to -1.
keystroke = -1 |
Check this project on GitHub.