街机游戏“弹弹乐”源代码完整版如下:
#include
#include
#include
#include
#include
using namespace std;
//定义全局常量
const int ROWS = 15; //行
const int COLS = 15;//列
const int DIRECTIONS = 4;//方向
int score=0;
//定义方向
int dirX[]={-1,0,1,0};//每个方向改变量 上下左右
int dirY[]={0,1,0,-1};
//定义游戏地图
int map[ROWS][COLS]={0};
//定义地图中的元素code
enum Element{
Empty=0,
Block,
Player
};
struct Position{
int x;
int y;
friend bool operator == (Position A,Position B)
{
return (A.x==B.x)&&(A.y==B.y);
}
};
//游戏开始函数
void StartGame()
{
int n=4; //block数量
int blockNum;//随机放置block的个数
Position blockPos;
Position playerPos; //定义玩家位置
playerPos.x=7;
playerPos.y=7;
//放置blocks
srand(time(NULL));
while(n)
{
blockNum = rand()%ROWS + 1;
for (int i = 0; i < blockNum; i++) { //循环放置指定的block数量
blockPos.x = rand()%ROWS + 1;
blockPos.y = rand()%COLS + 1;
//确保block和player是不同的
if (!(playerPos == blockPos)) {
map[blockPos.x][blockPos.y] = Block;
n -= 1;
}
}
}
//把player放到指定位置
map[playerPos.x][playerPos.y]=Player;
//定义用于存储路径的结构体
vector
//开始玩游戏
while (true){
//清屏
system("cls");
//输出游戏地图和游戏分数
cout << "score:"<
for (int j=1;j<=COLS;j++){
switch (map[i][j]){
case Empty:
cout << " ";
break;
case Block:
cout << "[]";
break;
case Player:
cout << " o";// o 代表玩家
break;
default:
break;
}
}
cout << endl;
}
//判断玩家游戏是否结束
for (int i=0;i
testPos.x = playerPos.x + dirX[i];
testPos.y = playerPos.y + dirY[i];
if (testPos.x<1||testPos.x>ROWS||testPos.y<1||testPos.y>COLS){
cout << endl << "Game Over!!" << endl << "You score is:" << score <
cout << endl << "You path: " << endl;
size_t len = path.size();
for (size_t i = 0; i < len; i++) {
cout << "(" << path[i].x << "," << path[i].y << ") ";
}
system("pause");
return;
}
}
//获取用户输入
int inputKey;
cout<
//计算新位置
int dir;
switch (inputKey)
{
case 8:
dir=0;
break;
case 6:
dir=1;
break;
case 2:
dir=2;
break;
case 4:
dir=3;
break;
default:
dir=-1;
break;
}
Position newPos;
newPos.x = playerPos.x + dirX[dir];
newPos.y= playerPos.y + dirY[dir];
//3.检查要走到的位置是什么
if (map[newPos.x][newPos.y]==Block){
//3.1是block,走不了,位置不变
//把block移到新的位置
switch (dir){
case 0:
map[newPos.x-1][newPos.y] = Block;
//消除原来的block
map[newPos.x][newPos.y] = Empty;
break;
case 1:
map[newPos.x][newPos.y+1] = Block;
//消除原来的block
map[newPos.x][newPos.y] = Empty;
break;
case 2:
map[newPos.x+1][newPos.y] = Block;
//消除原来的block
map[newPos.x][newPos.y] = Empty;
break;
case 3:
map[newPos.x][newPos.y-1] = Block;
//消除原来的block
map[newPos.x][newPos.y] = Empty;
break;
default:
break;
}
}
else {
//3.2不是block,才移动玩家
map[playerPos.x][playerPos.y]=Empty;
map[newPos.x][newPos.y] = Player;
playerPos.x = newPos.x;
playerPos.y = newPos.y;
//加分
score += 1;
//记录路径
path.push_back(newPos);
}
}
}
int main()
{
StartGame();
return 0;
}