扫雷
/*****************************
* 单位
* ***
* 时间
* 2011年8月20日
* 编写人
* ***
*****************************/
#ifndef _MINE_BUTTON_H
#define _MINE_BUTTON_H
#include <string>
using namespace std;
class MineButton
{
public:
int x;
int y;
string text;
bool isMine;
bool isClear;
public:
MineButton();
};
#endif
#include "minebutton.h"
MineButton::MineButton():x(-1),y(-1),isClear(false),isMine(false)
{
}
#ifndef _SWEEP_MINE_H
#define _SWEEP_MINE_H
#include "minebutton.h"
#define ROWS 10
#define COLS 10
#define NUM 50
class SweepMine
{
private:
int rows;
int cols;
int num ;
MineButton pool[ROWS][COLS];
bool isOver;
public:
SweepMine();
void init();
void start();
void sweepMineAt(int,int);
void explosion();
int getCount(int,int);
void dealEmpty(int,int);
bool validate(int,int);
void print();
};
#endif
#include "sweepmine.h"
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
string nm[10]={
"⊙","①","②","③","④","⑤","⑥","⑦","⑧","雷"
};
SweepMine::SweepMine()
{
rows=ROWS;
cols=COLS;
num=NUM;
init();
}
void SweepMine::init()
{
isOver=false;
//是否被点击
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
pool[i][j].x=i;
pool[i][j].y=j;
pool[i][j].text="笑";
}
}
//产生随机雷区
srand(time(NULL));
//以时间变化随机
for( i=0;i<num;)
{
int x=rand()%rows;
int y=rand()%cols;
if(!pool[x][y].isMine)
{
pool[x][y].isMine=true;
i++;
pool[x][y].text="笑";
}
}
}
void SweepMine::start()
{
int x,y;
do
{
print();
cout << "-->";
cin >> x >> y;
if(!cin)
{
cin.clear();
cin.ignore(100,'\n');
continue;
}
if(!validate(x,y))
{
continue;
}
sweepMineAt(x,y);
}while(!isOver);
}
void SweepMine::sweepMineAt(int x,int y)
{
pool[x][y].isClear=true;
if(pool[x][y].isMine)
explosion();
else
{
int cnt = getCount(x,y);
if(cnt==0)
{
dealEmpty(x,y);
}
else
{
pool[x][y].text=nm[cnt];
}
}
}
void SweepMine::explosion()
{
isOver=true;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(pool[i][j].isMine)
{
pool[i][j].text="雷";
}
}
}
print();
}
int SweepMine::getCount(int x,int y)
{
int cnt = 0;
for(int i=x-1;i<=x+1;i++)
{
for(int j=y-1;j<=y+1;j++)
{
if(!validate(i,j))
continue;
if(pool[i][j].isMine)
cnt++;
}
}
return cnt;
}
void SweepMine::dealEmpty(int x,int y)
{
pool[x][y].text=" ";
for(int i=x-1;i<=x+1;i++)
{
for(int j=y-1;j<=y+1;j++)
{
if(!validate(i,j))
continue;
if(!pool[i][j].isClear)
sweepMineAt(i,j);
}
}
}
bool SweepMine::validate(int x,int y)
{
if(x<0||x>=rows||y<0||y>=cols)
return false;
else
return true;
}
void SweepMine::print()
{
system("clear");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
cout << pool[i][j].text << ' ';
}
cout << endl;
}
}
int main()
{
SweepMine sm;
sm.start();
return 0;
}