Build the Game's View
00:11 Curses is a library supported by most operating systems that allows you to arbitrarily position the cursor in your terminal and write a string. Python includes a wrapper to curses in the standard library.
00:37 Curses expects a reference to a function or method that takes no arguments. It then calls this method to print out the state, so our code will determine which pattern to use, how many iterations to display, and the size of the bounding box.
01:15 I’ve designed the code to separate the presentation of the grid from the grid itself. This is a common pattern in visualization code. If you’ve ever heard of a model-view-controller, it’s similar to this approach.
01:28 The key reason for doing this is you can now add a different visualizer, say a GUI library, without making any changes to the grid code. The class on screen here encapsulates the code needed to display our grid using calls to the curses library.
All of these values get stored in the class for later reference. The entry point to all of our views is the
show() method. If you write another view as part of the homework, yes, there’s homework.
draw() method only gets called once. The loop and frame calculations are embedded inside of here. The first step in
draw() is to create a grid, no different from how it was done in the REPL in previous lessons.
02:53 Then there’s a bit of setup work. This call makes the screen’s cursor invisible so you don’t see it when it is writing to the terminal. And before writing to the screen, you need a blank tableau.
addstr() method is what draws the screen. The two zeros are the coordinates of the starting position, and then it is simply a call to the grid’s
as_string() method, which returns the string representation of the grid.
Now that you’ve drawn it, once you enter the game loop and draw each subsequent frame once for each generation specified in the constructor. Once drawn, you calculate the frame’s next data set, repeat the call to
addstr() to print it out, and tell curses to update the screen.
Finally, before looping again, you want to pause for a moment. How long is a moment? Well, it depends on the frame rate in the constructor.
sleep() takes seconds, so one over the frame rate tells you how many fractions of a second to pause until the next frame is due.
Become a Member to join the conversation.