STOP PRESS! The full book is now available DIRECTLY from Amazon with lower shipping costs!
This program uses a 2D array of strings to displayed a row of animated space invaders.
Loops are used to control where on the screen each space invader is being drawn, as well as which frame needs to be drawn for the invaders - arms up... arms down... arms up... arms down...
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cpp
I used invasion.cpp
To compile from the command-line:
g++ -o invasion.cpp invasion
To run from the command-line:
./invasion
Code is below...
#include <iostream> // Display text on screen
#include <sstream> // stringstream converts int to ASCII
#include <unistd.h> // sleep pauses between frames
using namespace std; // Abbreviations for cout and endl
int main()
{
// 2D array for invader graphics
string invader[8][2]; // 8 rows tall, 2 different animation frames
invader[0][0] = " # # ";
invader[1][0] = " # # ";
invader[2][0] = " ######### ";
invader[3][0] = " ## ### ## ";
invader[4][0] = "#############";
invader[5][0] = "# ######### #";
invader[6][0] = "# # # #";
invader[7][0] = " ## ## ";
invader[0][1] = " # # ";
invader[1][1] = "# # # #";
invader[2][1] = "# ######### #";
invader[3][1] = "### ### ###";
invader[4][1] = "#############";
invader[5][1] = " ######### ";
invader[6][1] = " # # ";
invader[7][1] = " ## ## ";
// Control which invader to display
// Will alternate between frame 0 and frame 1
int frames = 0;
// Make text green
cout << "\e[32m";
// Infinite loop to display invader forever
while ( true )
{
for ( int invaderNum = 0; invaderNum < 5; invaderNum++ )
{
// Display current animation frame for invader
for ( int line = 0; line < 8; line++ )
{
// Move to correct row and column using escape-sequence
int rowNum = 3 + line;
stringstream convertRowToASCII;
convertRowToASCII << rowNum;
string rowNumASCII;
convertRowToASCII >> rowNumASCII;
int colNum = 17 * invaderNum;
stringstream convertColToASCII;
convertColToASCII << colNum;
string colNumASCII;
convertColToASCII >> colNumASCII;
cout << "\e[" << rowNumASCII << ";";
cout << colNumASCII << "H";
// Display current row on the screen
cout << invader[line][frames % 2] << endl;
} // for loop that displays single frame
} // for loop that counts which invader being displayed
sleep( 1 ); // Pause before displaying next frame
frames++;
} // end of infinite while loop
return 0;
}
Find out more - buy the book on Amazon...