Overview

This lab is about getting some practice writing programs that use structs. We'll try to have some fun in the process, though. Folks always ask to do something game-like, so that's what we'll do. We're going to keep everything in the terminal, since dealing with graphics libraries would take us a bit too far off-topic for one lab period. However, we will use a libarary called "curses" (actually "ncurses") to allow us to write to arbitrary positions in the terminal window and to read keystrokes in a "nonblocking" manner.

Submission

Your instructor may or may not require a live demo. Ask them. Either way, an electronic submission is required.
This lab must be submitted before you leave for Thanksgiving break.
Submit up to and including the furtherst step you have working properly. So, if you finished all steps, submit as:
~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp lab11v3.cpp lab11v4.cpp lab11v5.cpp lab11v6.cpp lab11v7.cpp
If you only finished up through Step 2, submit as: ~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp
If you only finished up through Step 3 (a or b), submit as: ~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp lab11v3.cpp
If you only finished up through Step 4, submit as: ~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp lab11v3.cpp lab11v4.cpp
If you only finished up through Step 5, submit as: ~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp lab11v3.cpp lab11v4.cpp lab11v5.cpp
If you only finished up through Step 6, submit as: ~/bin/submit -c=IC210 -p=Lab11 lab11v2.cpp lab11v3.cpp lab11v4.cpp lab11v5.cpp lab11v6.cpp

Part 1: ncurses basics (name lab11v1.cpp)

The ncurses library views your terminal window as a big 2D table of single-character positions. So think of coordinates as (row,col) rather than (x,y). Thinking of it this way, (0,0) is the upper left corner of the terminal window. To use ncurses, you need to do a
#include <curses.h>
in your .cpp files, and you need to compile with the -l ncurses compiler flag, like:

g++ lab11v1.cpp -o lab11v1 -l ncurses

Create and compile lab11v1.cpp under your account. This source code demonstrates some simple aspects of ncurses. Here's a few comments:

Initializing Ncurses


  WINDOW *W = initscr();  
  cbreak();
  noecho(); 
  nodelay(W,true);
  curs_set(0);
  
This code should appear at the point in your main when you're ready to go into "ncurses mode". When this is executed, the screen goes blank and you are ready to write to arbitrary locations in the terminal window. The variable W is important. It's a pointer to a struct object that the ncurses library defines. You'll need to pass W to many ncurses functions.

Exiting Ncurses


// Loop forever until user enters 'q'
char c;
while((c = wgetch(W)) && c != 'q')
{
  // do nothing
}

// Clean up after ncurses
endwin();
Ncurses (at least as we've initialized it) changes the model for how we read data. You fetch the next character with a call to wgetch(W). The funny thing is that this is "non-blocking I/O", which means that you don't hang around and wait for input to come. If you call wgetch(W) and nobody presses a key, wgetch simply returns immediately with an error code. Contrast this with cin >> c or cin.get(). Thus, this loop just spins waiting for wgetch(W) to report that the user has pressed q. The endwin() function call is required in order for ncurses to clean up after itself and restore the terminal window.

Drawing something


wmove(W,0,0);
waddch(W,'1');
wrefresh(W);
usleep(800000);     // need: #include <unistd.h>
The model for writing to the screen in ncurses is this:
  1. move the cursor to a position in the terminal window grid
    int wmove(WINDOW* W, int row, int col);
  2. write a character at the current cursor position (which has the side effect of incrementing the cursor's column coordinate)
    int waddch(WINDOW* W, char c);
  3. whatever wmove's and waddch's you've done don't actually show up on the screen until you call the wrefresh function.
    int wrefresh(WINDOW *win);
Note the calls to usleep(time_us) (defined in unistd.h), which is like the sleep(s) function we've used before, except with finer resolution. The argument is the time to sleep given in micro-seconds.

Part 1b: debugging pro-tip

Suppose in the Part1 code we wanted to print out an debugging message "Printed a 2!" just after writing the "2". We'd just add the line
cout << "Printed a 2!" << endl;
... immediately after the waddch(W,'2');. Compile and run that. What you will find is that this message pops up in the middle of our ncurses screen and messes things up. The "3" is no longer printed immediately to the right of the "2". It's a real problem when your debugging messages cause new bugs! So how can we write out debugging messages in an ncurses program?
  1. Use the standard error output stream (cerr) instead of standard out (cout) for the debugging message. This doesn't solve the problem immediately, but it helps. To see how ...
  2. Change your error message(s) to use cerr rather than cout, e.g.
    cerr << "Printed a 2!" << endl;
    ... and run your program like this:
    ~/$ ./lab11v1 2> err
    What this does is run your program as usual except that any output written to standard error (cerr) gets "redirected" to the file err, which is created or overwritten each time this is run. Let your program run to completion, then give the command cat err to see what is written.
  3. Now, what you'd really like is to see the debugging output as it happens. Here's how you do that: Open a separate terminal window, cd to the lab directory containing your program and the "err" file, and give the command
    ~/$ tail -f err
    Go back to your original terminal and type something like this:
    ~/$ echo "whoooooooo" > err
    You should see the whoooooo pop up in the other terminal. Spooky, eh?
  4. Now run lab11v1 in the original terminal like this:
    ~/$ ./lab11v1 2> err
    ... and watch as your ncurses window is pure and unblighted by debugging messages, but the message does pop up at the appropriate time in the second window.
    What's going on here:
    • 2> err is telling the shell to redirect standard error (cerr in our program) output to the file err.
    • Meanwhile, tail -f is constantly monitoring the file err, printing out any new lines that get written to the file.
    You can keep rerunning, compiling and debugging your program without ever having to rerun tail -f, which is nice.
Note: This debugging technique is really useful!

Part 2: coming and going (name lab11v2.cpp)

Write a program that works as follows:
  1. Before going into ncurses mode, read in input from the user like this
    4
    a (10,15)
    x (14,29)
    k (5,5)
    x (18,37)
  2. The program should be now in ncurses mode.
  3. Draw the objects to the screen.
  4. Pause for a moment.
  5. Erase them from the screen. Erasing an object means writing a ' ' in the appropriate position.
  6. If the user has pressed 'q', terminate the program.
  7. Otherwise, pause for a moment, and then go back to step 3.

Important! I fully expect that this will be done with a good design that makes use of structs --- probably more than one --- and functions, and that the solution would work for a wide variety of inputs, not only for the input shown here.

Part 3: You got to move it, move it (name lab11v3.cpp)

Now we will animate things, i.e. each character will move on the screen. To start things off, let's have a single character, drawn as an 'X', and let's have the little X start at row 15, column 30. The character will have a direction associated with it — north, south, east or west. Start your X moving to the right (i.e., east). Note: design this program keeping in mind that ultimately there will be many characters moving simulatneously.

Your program will consist of a loop:

do {
  // draw characters 
  // i.e., 1. erase them in the old positions 
  //       2. draw them in the new positions
  // use only  wmove and waddch
  //  -- don't use wrefresh and usleep now; they will come later
  
  wrefresh(W);   // refresh the screen
  usleep(80000); // sleep for 80,000 usecs. This corresponds to flipping the next "frame" in an animation.

  // use wgetch to see if the user has pressed 'q'

  // move character one step in its current direction

}while('q' has not been pressed);

Important! At some point your character moves off the screen, and ncurses goes crazy --- nothing it draws makes sense anymore. Just kill the program with ctrl-c, and don't worry about it.

Of course at this point your character moves off the screen and things are not that interesting. So, to add a little drama let's say that at each step, To make the character wander around a bit, let's say that at each step, immediately before actually moving, the character has a 1-in-10 chance of turning (changing its current direction by a 90 degree turn) before taking a step. Having decided to turn, it'll be 50/50 whether the turn is right or left.

Note: seed the random number generator with


srand(time(0));   // need: #include <cstdlib>
                  //       #include <ctime>
or else it will do the same thing every time — that would be boring!

Recall: The following code will print "yes" with probabilty 1/10:


    if( rand() % 10 == 0 )
      cout << "yes" << endl;
    

Part 4 (going further): Momma should I build a wall? (name lab11v4.cpp)

Though your single animated character makes random turns, eventually it's going to make its way off the screen and strange things will happen. It'd be much cooler if the screen acted like a walled-in space that the character cannot escape. So let's do that. The only real difficulty here is that you need to know the height and width of the terminal window (in characters). Ncurses has a function for that:
int getmaxyx(WINDOW* W, int& row, int& col);
So the call getmaxyx(W,h,w) sets h to the number of rows on the screen, and w to the number of columns. Note, then, that the valid positions you can wmove(W,row,col) to are when 0 ≤ row < h and 0 ≤ col < w.

Now that you can get the height and width of the terminal window, when you come to a "move" step you must check to see whether the move in question would take you off the screen. If it does, then instead of moving just change direction and leave it at that. Make the character "bounce" by simply reversing direction (north goes to south, east to west, etc). If you do this, your character will be walled in and will never leave the terminal window.

Part 5 (going further): Yes it's that easy (name lab11v5.cpp)

Now, instead of one randomly moving character, make it 20 (or 40 or 1000 or whatever you want!). If you've done things right, you should be able to do this trivially. If you haven't made good use of structs and functions, it might be painful!

Important! Only do wrefresh(W); once per loop iteration, do it after all characters have been redrawn, and do it immediately prior to the call to usleep This is the way animations work: draw a whole new scene, and only overlay it once when it is all complete.

Part 6 (going further): Imperio (name lab11v6.cpp)

Now, let's make one character that's different. This will be a character that the user controls. To keep it simple, we'll use the a,s,d,w keys. Immediately after the usleep(), and prior to actually moving anyone, do a
char kb = wgetch(W);
... and if kb is an 'a', change the one character's direction to west, a 'd', change it to east, an 's' change it to south, and a 'w', change it to north. Note that this one character won't be subject to the random direction changes, and we won't worry about the walls for him ... it'll be up to the user to keep the player on the board.

(Typing a 'q' should still be used to quit the game.)

Part 7 (going further): And in the end ... (name lab11v7.cpp)

One last thing, if the user-controlled character collides with one of the other characters, or runs off the board, he dies and the game is over. When that happens, you might want to pause for a second or two before exiting ncurses. Oh, it'd also be a nice touch to report the number of steps (or seconds) the user stayed alive. You could add other fun things ... the tempo could increase, or more guys could enter the game or ... whatever else you can think of.