⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 thegameoflife.cpp

📁 模拟生命游戏的更新换代过程,可根据用户需要打印微生物的每一代群落布局.
💻 CPP
字号:
// TheGameOfLife.cpp : 定义控制台应用程序的入口点。
//

#include<iostream.h> //"stdafx.h"
//using namespace std;//::cout;
//using std::cin;
//using std::endl;
 const int maxrow=20,maxcol=60;
void instructions();
bool user_says_yes();
class Life
{
public:
	void initialize();
	void print();
	void update();
int neighbor_count(int row,int col);
private:
	int grid[maxrow+2][maxcol+2];
	
};
void instructions()
{
	cout<<"Welcome to Conway'game of Life."<<endl;
	cout<<"This game users a grid of size "<<maxrow<<"by"<<maxcol<<"in which"<<endl;
    cout<<"each cell can either be occupied by an organism or not ."<<endl;
		cout<<"The occupied cells change from generation to generation "<<endl;
	cout<<"according to the number of neiboring cells which are alive."<<endl;
}
bool user_says_yes()
{
	char r;
	int isAnserRight=0;
	while(!isAnserRight)
	{
		cout<<"Do you want to see the next generation?(y/n) "<<endl<<"Answer:";
	    cin>>r;
        if(r=='y'||r=='Y'||r=='n'||r=='N')  isAnserRight=1;
		else cout<<"Answer the question with (y or n),please"<<endl;
	}
	return (r=='Y'||r=='y')? true:false;
}
int Life::neighbor_count(int row,int col)
{
	int i,j;
	int count=0;
	for(i=row-1;i<=row+1;i++)
		for(j=col-1;j<=col+1;j++)
			count+=grid[i][j];
	count-=grid[row][col];
	return count;
		 
}
void  Life::initialize() 
{
int row,col;
for(row=0;row<=maxrow+1;row++)
for(col=0;col<=maxcol+1;col++)
grid[row][col]=0;
cout<<"List the coordinates for living cells."<<endl;
cout<<"Terminate the list with the the special pair -1 -1"<<endl;
cin>>row>>col;
while(row!=-1||col!=-1)
{
	if(row>=1&&row<=maxrow)
		if(col>=1&&col<=maxcol)
			grid[row][col]=1;
		else cout<<"column"<<col<<"is out of range."<<endl;
	else cout<<"Row"<<row<<"is out of range."<<endl;
	cin>>row>>col;
}

}
void  Life::print() 
{
int row,col;
cout<<"\nThe current Life congfiguration is:"<<endl;
for(row=0;row<=maxrow+1;row++)
{
for(col=0;col<=maxcol+1;col++)
if(grid[row][col]==1)
cout<<'#';
else if(row==0||row==maxrow+1) cout<<'-';
else if(col==0||col==maxcol+1) cout<<'|';
else cout<<'.';
cout<<endl;
}
cout<<endl;
}
void  Life::update()
{
int row,col;
int new_grid[maxrow+2][maxcol+2];
for(row=1;row<=maxrow;row++)
for(col=1;col<=maxcol;col++)
switch(neighbor_count(row,col))
{
case 2:
	new_grid[row][col]=grid[row][col];
	break;
case 3:
new_grid[row][col]=1;
break;
default:

new_grid[row][col]=0;

}
for(row=1;row<=maxrow;row++)
for(col=1;col<=maxcol;col++)
grid[row][col]=new_grid[row][col];

}

int  main(int argc, char* argv[])
{  char r;
	Life configuration;
    instructions();
	configuration.initialize();
  configuration.print();
  while(user_says_yes())
  {
        configuration.update();
          configuration.print();
  }
  //cin>>r;
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -