1.5 聲明和初始化變量
變量代表了計(jì)算機(jī)內(nèi)存的某一部分,該部分被保留下來(lái)用于存儲(chǔ)、檢索和操作數(shù)據(jù)。如果需要記錄玩家的得分,則可以為它專門(mén)創(chuàng)建一個(gè)變量。這樣一來(lái),就可以讀取并顯示玩家得分。如果玩家將空中的外星敵人擊斃,還可以將得分更新。
1.5.1 Game Stats程序簡(jiǎn)介
Game Stats程序顯示在太空射擊游戲中需要記錄的諸如玩家得分、擊毀敵人數(shù)目以及玩家防護(hù)盾是否開(kāi)啟等信息。該程序使用了一組變量來(lái)完成這些任務(wù)。程序如圖1-5所示。
圖1-5 游戲中每條數(shù)據(jù)都存儲(chǔ)在一個(gè)變量中
從Course Technology網(wǎng)站(www.courseptr.com/downloads)或本書(shū)合作網(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;
}