Games: Managing the screen and handling events
Prof. Brian D. Davison
Computer Science & Engineering, Lehigh University
Announcements
- Monday's class will be in the PL122 lab
- New project 7 due Thursday
- Get help on p6 during Monday's class
- Builds on existing code
- Adds full-screen animation and keypress input
- Today:
Writing a video game for UNIX
- Book mentions that UNIX was written in order to play the game "Space Travel"
- Games are fun to write and use
- Character-based games are somewhat like graphics games, but with fewer/bigger pixels
- Games provide a rationale for considering how to multi-task
- See the rot program as an example.
Writing a video game for UNIX
- We need to learn
- Draw stuff on the screen at particular positions
- Draw stuff at particular times
- Use both above to do animation
- Get input without stopping animation
Using curses to write on the screen
- Curses is a library of functions that allow a programmer to position the cursor and control the appearance of text on the terminal screen
- Screen is a grid (row, col)
- Basic functions
- initscr() - Initialize curses library and tty
- endwin() - Turn off curses and resets tty
- refresh() - Makes user's screen look like internal representation
- move(row,col) - Moves cursor to given screen position
- addstr(str) - Draws string s on the screen at current position
- addch(ch) - Draws char ch on the screen at current position
- clear() - Clears the screen
- Let's examine a first example
Using curses to write on the screen
- Very simple. Better effects are possible through loops and conditionals.
- Examine a better example.
- Note that there are two screens -- a virtual one on which you draw,
and a real one, that gets a copy of the virtual one when refresh() is called.
Drawing things at specific times
- We need to have images appear at certain times.
- Initially, we'll use sleep() in our example.
- Note that we need to call refresh() each time!
- The illusion of animation is handled simply by erasing and drawing again. See example.
- Here's a slightly better one that bounces some text.
- Still need better control of time (1 sec is too slow) and user input.
How is sleep() implemented?
- sleep() works much like people do...
- It sets an alarm for how long to snooze
- Pause until the alarm goes off
- See sleep example.
- In general, timing control will involve the use of signals.
- Recall that a signal is like a 'software interrupt', and a process can either 1) accept the default action; 2) ignore the signal; or 3) invoke a function.
- We can test how signals are handled using a
simple program.