1.5 聲明和初始化變量
變量代表了計算機內(nèi)存的某一部分,該部分被保留下來用于存儲、檢索和操作數(shù)據(jù)。如果需要記錄玩家的得分,則可以為它專門創(chuàng)建一個變量。這樣一來,就可以讀取并顯示玩家得分。如果玩家將空中的外星敵人擊斃,還可以將得分更新。
1.5.1 Game Stats程序簡介
Game Stats程序顯示在太空射擊游戲中需要記錄的諸如玩家得分、擊毀敵人數(shù)目以及玩家防護盾是否開啟等信息。該程序使用了一組變量來完成這些任務(wù)。程序如圖1-5所示。
圖1-5 游戲中每條數(shù)據(jù)都存儲在一個變量中
從Course Technology網(wǎng)站(www.courseptr.com/downloads)或本書合作網(wǎng)站(http://www. tupwk.com.cn/downpage)上可以下載到該程序的代碼。程序位于Chapter 1文件夾中,文件名為game_stats.cpp。
// Game Stats
// Demonstrates declaring and initializing variables
#include <iostream>
using namespace std;
int main()
{
int score;
double distance;
char playAgain;
bool shieldsUp;
short lives, aliensKilled;
score = 0;
distance = 1200.76;
playAgain = 'y';
shieldsUp = true;
lives = 3;
aliensKilled = 10;
double engineTemp = 6572.89;
cout << "\nscore: " << score << endl;
cout << "distance: " << distance << endl;
cout << "playAgain: " << playAgain << endl;
//skipping shieldsUp since you don’t generally print Boolean values
cout << "lives: " << lives << endl;
cout << "aliensKilled: "<< aliensKilled << endl;
cout << "engineTemp: " << engineTemp << endl;
int fuel;
cout << "\nHow much fuel? ";
cin >> fuel;
cout << "fuel: " << fuel << endl;
typedef unsigned short int ushort;
ushort bonus = 10;
cout << "\nbonus: " << bonus << endl;
return 0;
}