Core C++

Lesson 55 : Space Invaders

Overview

In this C++ video tutorial, we demonstrate how animation and graphics were created during the early days of computers in games like Space Invaders.

Download Code

In the early days of computing, processors had very little power and memory. Computer programmers used the simplest and most efficient techniques for programming games. Two color graphics and bit shifts allowed programmers to create and animate high-resolution graphics fluidly.

Midway Space Invaders

Below, we have code that generates six frames of three lines of animation. In the first frame, the invaders start at the top left. In the next two frames, we use two right bit shifts to move the invaders to the other side of the screen. In the next frame, the invaders move down. Then they move back to the left in the next two frames.

The movement is accomplished via three functions: ShiftRowsRight(), ShiftRowsLeft(), and MoveRowsDown(). These functions are used to move the invaders right, left, and down the screen, respectively.

The screen is composed of three lines of 32 pixels each. The pixels are represented in binary digits or bits by the numbers 0 and 1, where 0 represents a black pixel and 1 represents a white pixel. The pixels are initialized in the array declaration for uiaInvaders inside the main() function. On the screen, the invaders are represented as four pixel clusters that move all the way to the other side before making their next move down. The screen is displayed via the PrintBitRows() function that calls the PrintBits() function to print each row of pixels.

#include <iostream>

void PrintBits(unsigned int uiBits) {
	for (int i = 31; i >= 0; --i) {
		std::cout << (((uiBits >> i) % 2) ? '1' : '0');
	}
}

void PrintBitRows(unsigned int uiaBitRows[]) {
	for (int i = 0; i < 3; ++i) {
		PrintBits(uiaBitRows[i]);
		std::cout << std::endl;
	}
	std::cout << std::endl;
}

void ShiftRowsRight(unsigned int uiaBitRows[]) {
	for (int i = 0; i < 3; ++i) {
		uiaBitRows[i] = (uiaBitRows[i] >> 1);
	}
}

void ShiftRowsLeft(unsigned int uiaBitRows[]) {
	for (int i = 0; i < 3; ++i) {
		uiaBitRows[i] = (uiaBitRows[i] << 1);
	}
}

void MoveRowsDown(unsigned int uiaBitRows[]) {
	for (int i = 0; i < 2; ++i) {
		uiaBitRows[i+1] = uiaBitRows[i];
	}
	uiaBitRows[0] = 0;
}

int main() {
	using namespace std;

	unsigned int uiaInvaders[3] = {0xCCCCCCCC, 0xCCCCCCCC, 0x0};

	for (int j = 0; j < 2; ++j) {
		PrintBitRows(uiaInvaders);
		ShiftRowsRight(uiaInvaders);
	}

	PrintBitRows(uiaInvaders);
	MoveRowsDown(uiaInvaders);

	for (int j = 0; j < 2; ++j) {
		PrintBitRows(uiaInvaders);
		ShiftRowsLeft(uiaInvaders);
	}
	PrintBitRows(uiaInvaders);

	// Keep the window open
	cin.get();
	return 0;
}

The output of the program is shown below with the six frames of animation separated by blank lines.

Space Invaders Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.