[C] 生命游戏源码

写着玩儿的,不保证效率。另外运行环境为WIN10、64位。


#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <string.h>

#define ALIVE 1
#define DIED 0

#define S_ALV "#"
#define S_DED "."

// 初始化时的填充概率(%)
#define CHANCE 15
// 刷新时间(ms)
#define TM 500

#define LINE 25
#define COLS 50
#define LENG (LINE * COLS)

char cMap_a[LENG] = { 0 };
char temp[LENG] = { 0 };
int iStep = 0;

// 坐标转换
void pst(int num, int * xp, int * yp){
	* xp = num / COLS;
	* yp = num % COLS;
	return;
}

// 初始化
void init(int chc){
	srand(time(NULL));
	for(int i = 0; i < LENG; i++){
		cMap_a[i] = ((rand() % 100) + 1 <= chc);
	}
	return;
}

// 显示
void show(){
	system("cls");
	for(int i = 0; i < LINE; i++){
		for(int  j = 0; j < COLS; j++){
			printf("%s", cMap_a[i * COLS + j] ? S_ALV : S_DED);
		}
		printf("\n");
	}
	printf("step: %d\n", iStep++);
	return;
}

// 计算周围“生”的数量
int cnt(int num){
	int x, y, rsl = 0;
	pst(num, &x, &y);
	for(int i = -1; i <= 1; i++){
		int i1 = x + i;
		if(i1 < 0 || i1 >= LINE){
			continue;
		}
		for(int j = -1; j <= 1; j++){
			int j1 = y + j;
			if(j1 < 0 || j1 >= COLS){
				continue;
			}
			if(i == 0 && j == 0){
				continue;
			}
			rsl += cMap_a[i1 * COLS + j1];
		}
	}
	return rsl;
}

// 刷新
void calc(){
	for(int i = 0; i < LENG; i++){
		int num = cnt(i);
		if(3 == num){
			temp[i] = ALIVE;
		}else if (2 == num){
			temp[i] = cMap_a[i];
		}else{
			temp[i] = DIED;
		}
	}
	memcpy(cMap_a, temp, sizeof(temp)); 
	return;
}

int main(int argc,char * argv[]){
	init(CHANCE);
	while(1){
		show();
		Sleep(TM);
		calc();
	}
	return EXIT_SUCCESS;
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注