2D Arrays - Creating virtual Creatures?

So first I have to display a 2D array with all 0s, which is pretty easy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main (){
  int array[5][5];

  for(int a=0; a<5; a++){
        for(int b=0; b<5; b++){
            array[a][b] = 0;
        }
    }

    for(int a=0; a<5; a++){
        for(int b=0; b<5; b++){
            cout << array[a][b]  << " ";
        }
        cout << endl;
    }
}


So this displays
1
2
3
4
5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0


Next, this is where it gets confusing. I have to create a virtual creature by storing a letter into a random position in the array (the array can be up to 20x20 in size). Then make a function that searches the array for creatures, so it would search for that character. When it finds a creature, it should randomly decide to either move the creature to an adjacent position, or have it stay where it is. After, it should ask the user to create a new creature, or quit.

So how would I go about adding & modifying the current code to achieve what is listed above?
Last edited on
#Crypted

Here is how you can create an array, put in a 'C'reature, find it and display its position. To move it in a direction, you could create a random number of 1 to 4. If it's a 1, you could subtract from the row location, and make array[a-1][b] to equal 'C', and array[a][b] to become a '0', to remove the creature. A 2, you move the creature one space to the right, etc. Remembering always to remove it from the original location. I'll let you work on the rest of your program.

Ask again with your new code, with whatever problems you're facing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <ctime>

using std::cout;
using std::endl;
using std::cin;

const int Array_Size = 20; // Change to whatever size you need..

void Find_Creature(char array[][Array_Size]);

int main ()
{
 srand((unsigned) time(0)); //Randomize
 char array[Array_Size][Array_Size]; // Using char instead of int.
 int x,y;
 for(int a=0; a<Array_Size; a++)
 {
	for(int b=0; b<Array_Size; b++)
	{
	 array[a][b] = '0';
	}
 }
 x=rand()%Array_Size;
 y=rand()%Array_Size;
 array[x][y]='C';
 Find_Creature(array);

 for(int a=0; a<Array_Size; a++)
 {
	for(int b=0; b<Array_Size; b++)
	{
	 cout << array[a][b] << " ";
	}
	cout << endl;
 }
}

void Find_Creature(char array[][Array_Size])
{
 for(int a=0; a<Array_Size; a++)
 {
	for(int b=0; b<Array_Size; b++)
	{
	 if(array[a][b] !='0')
		cout << "Found a " << array[a][b] << " creature in row " << a+1 << ", column " << b+1 << "." << endl;
	}
 }
}
Thank you, I was able to finish the project successfully!
Topic archived. No new replies allowed.