|
-
April 2nd, 2012, 04:51 AM
#1
Simulation: Tortoise & Hare race (srand question)
Hello guys,
I'm a new member here, and I'm currently trying to learn C++ by myself, I have some minor experience with programming through the C language.
I've been using a book to learn the language and there are some exercises that I am to take after each chapter, one of them requires me to simulate a race between a hare & a tortoise, I have a question regarding srand()
Here's my code:
Code:
// EX08.12
// Simulation: The Tortoise and the Hare
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void moveTortoise(int * const turtoisePosition);
void moveHare(int * const harePosition);
int main()
{
// seed rand
srand(time(0));
enum Status {HAREWINS, TORTOISEWINS, TIE, CONTINUE};
Status gameStatus = CONTINUE;
// initialize starting position for the race
int tortoise = 1;
int hare = 1;
// begin race
cout << "BANG!!!!\nAND THEY'RE OFF!!!!\n";
while (gameStatus == CONTINUE)
{
// move the contenders
moveTortoise(&tortoise);
moveHare(&hare);
// show race status
for (int line = 0; line < 70; line++)
{
if ((line == tortoise) && (line == hare))
cout << "Ouch!";
else if (line == tortoise)
cout << 'T';
else if (line == hare)
cout << 'H';
else
cout << '-';
}
cout << endl;
// determine whether one or the other reached the end line
if ((tortoise >= 70) && (hare >= 70))
{
cout << "It's a tie." << endl;
gameStatus = TIE;
}
else if (tortoise >= 70)
{
cout << "TORTOISE WINS!! YAY!!!" << endl;
gameStatus = TORTOISEWINS;
}
else if (hare >= 70)
{
cout << "Hare wins. Yuch!" << endl;
gameStatus = HAREWINS;
}
}
}
void moveTortoise(int * const tortoisePosition)
{
int step = 1 + rand() % 10;
// move tortoise
if ((step >= 1) && (step <= 5))
*tortoisePosition += 5;
else if ((step >=6) && (step <= 7))
*tortoisePosition -= 6;
else if ((step >= 8) && (step <= 10))
*tortoisePosition += 1;
if (*tortoisePosition < 1)
*tortoisePosition = 1;
}
void moveHare(int * const harePosition)
{
int step = 1 + (rand() % 10);
// move hare
if ((step >= 1) && (step <= 2));
else if ((step >= 3) && (step <= 4))
*harePosition += 9;
else if (step == 5)
*harePosition -= 12;
else if ((step >= 6) && (step <= 8))
*harePosition += 1;
else if ((step >= 9) && (step <= 10))
*harePosition -= 2;
if (*harePosition < 1)
*harePosition = 1;
}
My question is about line 15
If I place the line inside functions moveHare() and moveTortoise() the code produces repeated results, i.e. not random, but if I place it inside main() the code works correctly, what causes this?
Thank you for your help.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|