[数据结构]Life_Game

//main.cpp

#include"Life.h"
#include<iostream>
#include<string>
using namespace std;
void main() {
	cout << "********************************* Life Game**********************************" << endl;
	cout << "please enter the location you want live, just like \"m n\"" << endl;
	cout << "enter \"-1 -1\" to end enter" << endl;
	Life example;
	example.Initialize();
	example.Print();
	while (1) {
		cout << "enter \"yes\" to the next generation" << endl;
		string s;
		cin >> s;
		if (s == "yes") {
			example.UpDate();
			example.Print();
		}
		else break;
	}
	system("pause");
}
//Life.h

#pragma once
#include<iostream>
using namespace std;

const int maxrow = 20, maxcol = 60;//界限

class Life
{
public:
	void Initialize();//游戏初始化 
	void UpDate();//更新 
	void Print();//输出游戏结果 
	Life() { 
		for (int i = 1; i <= maxrow; i++)
			for (int j = 0; j <= maxcol; j++)
				arr[i][j] = 0;
	}
private:
	int arr[maxrow + 2][maxcol + 2];
	int neighbour_count(int row,int col);
};

Life.cpp

#include"Life.h"
#include<iostream>
#include<string>
using namespace std;
void Life::Initialize() {
	int row, col;
	do {
		cin >> row >> col; 
		if (row >= 1 && row <= maxrow)
			if (col >= 1 && col <= maxcol)
				arr[row][col] = 1;
			else {
				cout << "out of range" << endl;
				break;
			}
	} while (row != -1 && col != -1);
}
void Life::Print() {
	system("cls");
	int row, col;
	for (row = 1; row <= maxrow; row++) {
		for (col = 1; col <= maxcol; col++) {
			if (arr[row][col] == 0)cout << "□";
			else cout << "●";
		}
		cout << endl;
	}
}
void Life::UpDate() {
	int new_arr[maxrow + 2][maxcol + 2];
	for (int i = 1; i <= maxrow; i++)
		for (int j = 0; j <= maxcol; j++)
			new_arr[i][j] = 0;
	for (int row = 1; row <= maxrow; row++) {
		for (int col = 1; col <= maxcol; col++) {
			switch (neighbour_count(row,col))
			{
			case 2:
				new_arr[row][col] = arr[row][col];
				break;
			case 3:
				new_arr[row][col] = 1;
				break;
			default:
				new_arr[row][col] = 0;
				break;
			}
		}
	}
	for (int i = 0; i <= maxrow; i++)
		for (int j = 0; j <= maxcol; j++)
			arr[i][j] = new_arr[i][j]; 

}
int Life::neighbour_count(int row, int col) {
	int sum = 0;
	for (int i = row - 1; i <= row + 1; i++)
		for (int j = col - 1; j <= col + 1; j++)
			if (arr[i][j] == 1)sum++;
	return (sum - arr[row][col]);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值