Add a feature to randomly scatter rocks over the field
Where to put the code
The CreateNewField method sets each field element to soil:
1 static void CreateNewField(char[,] Field)
2 {
3 int Row = 0;
4 int Column = 0;
5 for (Row = 0; Row < FIELDLENGTH; Row++)
6 {
7 for (Column = 0; Column < FIELDWIDTH; Column++)
8 {
9 Field[Row, Column] = SOIL;
10 }
11 }
12 Row = FIELDLENGTH / 2;
13 Column = FIELDWIDTH / 2;
14 Field[Row, Column] = SEED;
15 }
We could generate a random number and if it is within a certain range set ROCK instead of SOIL.
The new code
1 static void CreateNewField(char[,] Field)
2 {
3 int Row = 0;
4 int Column = 0;
5 Random RandomInt = new Random();
6 for (Row = 0; Row < FIELDLENGTH; Row++)
7 {
8 for (Column = 0; Column < FIELDWIDTH; Column++)
9 {
10 if (RandomInt.Next(0, 20) == 1)
11 {
12 Field[Row, Column] = ROCKS;
13 }
14 else
15 {
16 Field[Row, Column] = SOIL;
17 }
18 }
19 }
20 Row = FIELDLENGTH / 2;
21 Column = FIELDWIDTH / 2;
22 Field[Row, Column] = SEED;
23 }
I started by copying the RandomInt and the if statement from SimulateSpring. The declaration of RandomInt must take place outside of the loops, otherwise you are likely to generate the same random number. I have changed the range of the random number to better reflect the probability of a rock, ie 1 in 20.
if the random number is a 1 then it adds a rock. if the random number is not a 1 then it adds soil.
As above but with a function to decide
1 static void CreateNewField(char[,] Field)
2 {
3 int Row = 0;
4 int Column = 0;
5 Random RandomInt = new Random();
6 for (Row = 0; Row < FIELDLENGTH; Row++)
7 {
8 for (Column = 0; Column < FIELDWIDTH; Column++)
9 {
10 Field[Row, Column] = GetSquare();
11 }
12 }
13 Row = FIELDLENGTH / 2;
14 Column = FIELDWIDTH / 2;
15 Field[Row, Column] = SEED;
16 }
And the GetSquare function:
1 static char GetSquare()
2 {
3 char choice='';
4 Random RandomInt = new Random();
5 if (RandomInt.Next(0, 20) == 1)
6 {
7 choice = ROCKS;
8 }
9 else
10 {
11 choice = SOIL;
12 }
13 return choice;
14 }