上个周末参加GDCR2013,今年的题目还是Game of Life,通过一天的交流和联系,确实收“货”不少,今后考虑陆续以这个题目不断锻炼自己的编码能力,用一小时编写程序,总结并删除,然后增加限制条件,继续练习。此外,使用不同的语言练习也是一个很好的学习语言的方法。
我也准备将这一题目作为2014年的重点,以强化编码能力的途径之一。
以下代码为VS2008下调试运行通过的,UT代码采用cpputest,写的不好暂时不贴了。
#ifndef LIFE_GAME_H
#define LIFE_GAME_H
const int MAXSIZE = 30;
class LifeGame
{
public:
LifeGame(int times);
void setSeeds(int x[], int y[], int len);
void start();
void setRunTimes(int times);
void print();
private:
void initGame();
int getNeighborNum(int x, int y);
void calcAlive(int x, int y);
void generateNext();
int runTimes;
int curSelect; //0 or 1
int matrix[2][MAXSIZE][MAXSIZE];
};
#endif
#include <iostream>
#include <windows.h>
#include <string.h>
#include "LifeGame.h"
using namespace std;
LifeGame::LifeGame(int times)
{
runTimes = times;
initGame();
}
void LifeGame::start()
{
while(runTimes > 0)
{
this->print();
this->generateNext();
Sleep(1);
system("cls");
--runTimes;
}
}
void LifeGame::setRunTimes(int times)
{
runTimes = times;
}
void LifeGame::initGame()
{
memset(matrix, 0, 2*MAXSIZE*MAXSIZE*sizeof(int));
curSelect = 0;
}
void LifeGame::setSeeds(int x_array[], int y_array[], int len)
{
for(int i=0; i<len; ++i)
{
int x = x_array[i];
int y = y_array[i];
matrix[curSelect][x][y] = 1;
}
}
void LifeGame::generateNext()
{
for(int i=0; i<MAXSIZE; ++i)
{
for(int j=0; j<MAXSIZE; ++j)
{
calcAlive(i,j);
}
}
curSelect = 1 - curSelect;
}
int LifeGame::getNeighborNum(int i, int j)
{
int num_life = 0;
if(i-1>= 0 && j-1>=0 && matrix[curSelect][i-1][j-1])
++num_life;
if(i-1>=0 && matrix[curSelect][i-1][j] )
++num_life;
if(i-1>=0 && j+1<MAXSIZE && matrix[curSelect][i-1][j+1])
++num_life;
if(j-1>=0 && matrix[curSelect][i][j-1])
++num_life;
if(j+1<MAXSIZE && matrix[curSelect][i][j+1])
++num_life;
if(i+1<MAXSIZE && j-1>=0 && matrix[curSelect][i+1][j-1] )
++num_life;
if(i+1<MAXSIZE && matrix[curSelect][i+1][j])
++num_life;
if(i+1<MAXSIZE && j+1<MAXSIZE && matrix[curSelect][i+1][j+1])
++num_life;
return num_life;
}
void LifeGame::calcAlive(int x, int y)
{
int map[2][9]={{0,0,0,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0}};
int sum=getNeighborNum(x,y);
int current_value = matrix[curSelect][x][y];
int nextSelect = 1 - curSelect;
matrix[nextSelect][x][y]= map[current_value][sum];
}
void LifeGame::print()
{
for(int i =0; i<MAXSIZE; ++i)
{
for(int j =0; j<MAXSIZE; ++j)
{
if(matrix[curSelect][i][j]==1)
{
cout<<"*";
}
else
{
cout<<" ";
}
}
cout<<endl;
}
}
#include <iostream>
#include "LifeGame.h"
void GetRandArrayX(int arrX[], int num)
{
for(int i =0; i<num; ++i)
{
arrX[i] = rand()%(MAXSIZE-1);
}
}
void GetRandArrayY(int arrY[], int num)
{
for(int i =0; i<num; ++i)
{
arrY[i] = rand()%(MAXSIZE-1);
}
}
int main()
{
const int seedsNum = MAXSIZE * (MAXSIZE/5);
int seed_x[seedsNum]={0};
int seed_y[seedsNum]={0};
GetRandArrayX(seed_x, seedsNum);
GetRandArrayY(seed_y, seedsNum);
LifeGame game(200);
game.setSeeds(seed_x, seed_y, seedsNum);
game.start();
system("PAUSE");
}