对于这项任务,我必须创造一个生物' C'在一个环境(20x20阵列)上移动它。
第一次,它运作并移动生物,但第二次+,它没有。
所以这里是代码。是的,我知道它非常混乱,但我仍然是c ++的新手(我不会介意更正:D)。此外,作为作业的一部分,该生物必须在LifeForm类中。
单击here以获取要运行的cpp.sh链接。
#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);
}
所以,正如你所看到的,我试图让这个生物在用户选择时移动一次,但它会保持在同一位置。
答案 0 :(得分:1)
在方法step
中,您永远不会更新生物的当前位置。在此行array[x + 1][y + 1] = symbol();
中更新数组。但你应该改写它:
x++;
y++;
array[x][y] = symbol();
通过这样做,您可以确保在更改位置的表示(您在屏幕上绘制的数组)时正确更新生物的当前位置。