我在C++做了一个高中课程的生活游戏。我们使用的网站没有C++的自动评分器,我的编程老师也不知道如何编程.所以我想要一些外部反馈!虽然我相信这个模拟工作,但我不确定代码的质量。我试着使它尽可能的可读性和流畅性,但我对C++还是新手。让我知道这段代码是如何"C++“的,以及我可能发现的任何陷阱。
我不知道这个网站使用的是什么版本的C++,但我相信它的前C++11版本?(由于缺乏智能指针)。
我非常喜欢在以下网站上运行它:https://codehs.com/sandbox/drakepickett/game-of-life
附注:-我增加了控制台清理和这样一个厚颜无耻的实验,以使它看起来很好。不确定使用我的方法清除控制台的安全性是:)
非常感谢!
以下是原始代码:
#include "util.h"
#include <vector>
#include <chrono>
#include <thread>
using namespace std;
struct Board
{
int BOARD_SIZE;
char liveCell;
char deadCell;
vector<vector<char> > cells;
void populateBoard()
{
int numLive = readInt(1, BOARD_SIZE*BOARD_SIZE, "Please enter number of active cells between 1 and " + to_string(BOARD_SIZE*BOARD_SIZE)+ ": ");
for (int i = 0; i < numLive; i++)
{
int x, y;
while (true)
{
x = randInt(0, this->BOARD_SIZE-1);
y = randInt(0, this->BOARD_SIZE-1);
if (this->cells[x][y] == this->deadCell) break;
}
this->cells[x][y] = this->liveCell;
}
}
Board(int size, char liveCell, char deadCell)
{
this->BOARD_SIZE = size;
this->liveCell = liveCell;
this->deadCell = deadCell;
for (int i = 0; i < this->BOARD_SIZE; i++)
{
vector<char> row;
for (int j = 0; j < this->BOARD_SIZE; j++)
{
row.push_back(this->deadCell);
}
this->cells.push_back(row);
}
populateBoard();
}
int getNumNeighbors(int row, int column)
{
int numNeighbors = 0;
vector<int> xRange;
vector<int> yRange;
if (row > 0) yRange.push_back(-1);
yRange.push_back(0);
if (row < this->cells.size()-1) yRange.push_back(1);
if (column > 0) xRange.push_back(-1);
xRange.push_back(0);
if (column < this->cells.size()-1) xRange.push_back(1);
for (int y : yRange)
{
for (int x : xRange)
{
if (x == 0 && y == 0) continue;
//cout <<"Y: " << row << " | Row: " << row+y << " _ X: " << column << " | Column: " << column + x << endl;
if (this->cells[row+y][column+x] == this->liveCell) numNeighbors++;
//cout << "We made it!" << endl;
}
}
return numNeighbors;
}
void update()
{
vector<vector<char> > b = this->cells;
for (int i = 0; i < this->BOARD_SIZE; i++)
{
for(int j = 0; j < this->BOARD_SIZE; j++)
{
int numNeighbors = getNumNeighbors(i, j);
if (this->cells[i][j] == this->liveCell && !(numNeighbors == 2 || numNeighbors == 3)) b[i][j] = this-> deadCell;
if (this->cells[i][j] == this->deadCell && numNeighbors == 3) b[i][j] = this->liveCell;
}
}
this->cells = b;
}
void print()
{
for (int i = 0; i < this->BOARD_SIZE; i++)
{
for (int j = 0; j < this->BOARD_SIZE; j++)
{
cout << this->cells[i][j] << " ";
}
cout << endl;
}
}
};
void cls()
{
using namespace std::chrono_literals;
this_thread::sleep_for(1000ms);
std::cout << "\x1B[2J\x1B[H";
}
int main()
{
Board board(15, 'X', '-');
int numIterations = readInt(0, 1000, "Run how many iterations? (0-1000): ");
for (int i = 0; i < numIterations; i++)
{
cls();
cout << "Iteration " << i << endl;
board.print();
board.update();
}
cls();
cout <<"Final Board" << endl;
board.print();
return 0;
}发布于 2022-01-04 07:09:03
2.BOARD_SIZE,死的和活的都可以是康斯特。因为一旦对象被初始化,它们就不会被更改。
https://codereview.stackexchange.com/questions/272601
复制相似问题