C++ 带有';生物';移动错误(C+;+;)
对于这个任务,我必须让一个生物“C”在一个环境(20x20阵列)上并移动它 第一次,它工作并移动生物,但第二次+,它不工作。 这是代码。是的,我知道这很混乱,但我仍然有一个新的C++(我不介意更正:D)。此外,作为任务的一部分,该生物必须处于生命体类别中 单击以运行cpp.sh链接C++ 带有';生物';移动错误(C+;+;),c++,arrays,C++,Arrays,对于这个任务,我必须让一个生物“C”在一个环境(20x20阵列)上并移动它 第一次,它工作并移动生物,但第二次+,它不工作。 这是代码。是的,我知道这很混乱,但我仍然有一个新的C++(我不介意更正:D)。此外,作为任务的一部分,该生物必须处于生命体类别中 单击以运行cpp.sh链接 #include <iostream> #include <ctime> #include <string> using namespace std; class LifeF
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
class LifeForm{
public:
int x, y;
char array[20][20];
string name(){
return "Control";
}
char symbol(){
return 'C';
}
void xy(){
x = (rand() % 18) + 1; //random position in x
y = (rand() % 18) + 1; //random position in y
array[x][y] = symbol();
}
void step(){
for (int a = 0; a < 20; a++){
for(int b = 0; b < 20; b++){
array[a][b] = '0';
}
}
array[x + 1][y + 1] = symbol();
if (x > 19 || x < 2 || y > 19 || y < 2){
cout << "The creature cannot move any further without leaving the environment!" << endl;
array[x][y] = '0';
array[x - 1][y - 1] = symbol();
}
system("pause");
system("cls");
find(array);
for (int a = 0; a < 20; a++){
for (int b = 0; b < 20; b++){
cout << array[a][b] << " ";
}
cout << endl;
}
}
void step10(){
//todo
}
void find(char array[][20]){
for (int a = 0; a < 20; a++){
for (int b = 0; b < 20; b++){
if (array[a][b] != '0'){
cout << "Found Creature '" << name() << "' in row " << a + 1 << ", column " << b + 1 << "." << endl;
}
}
}
}
};
int main(){
LifeForm creature;
srand((unsigned) time(0)); //randomize
for (int a = 0; a < 20; a++){ //initilize array to all 0's
for (int b = 0; b < 20; b++){
creature.array[a][b] = '0';
}
}
creature.xy();
creature.find(creature.array);
for (int a = 0; a < 20; a++){ //display the array
for (int b = 0; b < 20; b++){
cout << creature.array[a][b] << " ";
}
cout << endl;
}
creature.step();
string a;
bool abc;
do{
cout << "\n--- What would you like to do? --------------" << endl;
cout << "S for Step | S10 for Step 10 | E for Exit" << endl;
cout << "---------------------------------------------" << endl;
cin >> a;
if (a == "S" || a == "s") {
creature.step();
abc = true;
}else if (a == "S10" || a == "s10") {
creature.step10();
abc = true;
}else{
abc = false;
system("pause");
}
}while(abc == true);
}
#包括
#包括
#包括
使用名称空间std;
班级生活型{
公众:
int x,y;
字符数组[20][20];
字符串名(){
返回“控制”;
}
字符符号(){
返回“C”;
}
void xy(){
x=(rand()%18)+1;//x中的随机位置
y=(rand()%18)+1;//y中的随机位置
数组[x][y]=symbol();
}
无效步骤(){
对于(int a=0;a<20;a++){
对于(int b=0;b<20;b++){
数组[a][b]=“0”;
}
}
数组[x+1][y+1]=symbol();
如果(x>19 | | x<2 | | y>19 | | y<2){
cout在方法步骤中,您从不更新生物的当前位置。在这行数组[x+1][y+1]=symbol();
中,您更新数组。但是您应该将其重写为:
x++;
y++;
array[x][y] = symbol();
通过这样做,您可以确保在更改位置表示(您在屏幕上绘制的阵列)时,生物的当前位置得到正确更新。仅在程序中调用srand
一次。嗯,没有解决问题。