Recipe 17-1: Space Game

This recipe is inspired by the classic 1970s arcade game Space Invaders. The object is to kill the alien forces before they reach planet Earth (represented by the bottom of the screen). You can move your spaceship left and right using the “a” and “l” keys, and fire your cannon by pressing the “f” key. You get only one cannon shot at a time.

Technologies Used

  • kill, trap, and SIGALRM for timing
  • Advanced uses of read for timely response to keystrokes
  • tput to control the terminal
  • ANSI colors for display
  • Arrays, particularly passing arrays to functions
  • Basic mathematics to calculate position and collision detection

Concepts

The concepts behind the game itself are fairly simple. The aliens march from left to right and back again, and are coming down the screen toward you, so they move down one text row every time they get to the right-hand side of the screen. This is implemented by increasing the ceiling variable each time; the aliens are rendered at (row*2) + ceiling; multiplying by 2 means that there is a blank row between each wave of aliens, and adding the ever-increasing ceiling to this value means that the whole army gets lower over time.

You have a laser cannon, which is represented by a pair of variables, cannonX and cannonY, which keep track of where it is. cannonX is necessary because the laser keeps going in a vertical line even after you move, so it starts out the same as your ship’s position, but remains independent of the ship after it is launched. ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.