//------------------------------------------------- // // A very small predator/prey example. // // We have a grid world on which there lives a rabbit and // a fox, which move about randomly. // // Simon Parsons // March 14th 2007 // //------------------------------------------------- // Include C++ library definitions #include // For cin cout #include // For rand #include // For sqrt #include // For time using namespace std; //------------------------------------------------- // // Declare methods // Make a random movement. Either go forwards, go backwards // or do not move. int makeRandomMove(void) { int movement; movement = rand() % 3; if(movement == 0) { return 0; } if(movement == 1) { return 1; } if(movement == 2) { return -1; } } // Keep the fox and the rabbit in a 10 by 10 grid int wrapAround(int coordinate) { if(coordinate > 10) { return 0; } else if(coordinate < 0) { return 10; } else { return coordinate; } } // Give the position of the fox and the rabbit. void displayPosition(int xF, int yF, int xR, int yR) { cout << "The fox is at: (" << xF << ", " << yF << ")" << endl; cout << "The rabbit is at: (" << xR << ", " << yR << ")" << endl; } //------------------------------------------------ // // The main body of the program int main() { // Declare variables int xFox; // Fox's x position int yFox; // Fox's y position int xRabbit; // Rabbit's x position int yRabbit; // Rabbit's y position char c; // User's input bool quit = false; // Do we want to quit? // Initialisation. Pick locations of fox and rabiit randomly srand(time(NULL)); // Set the random seed xFox = rand() % 11; yFox = rand() % 11; xRabbit = rand() % 11; yRabbit = rand() % 11; while(!quit) { // Move both fox and rabbit randomly, using wrapAround to make // sure that they stay within the grid. xFox = wrapAround(xFox + makeRandomMove()); yFox = wrapAround(yFox + makeRandomMove()); xRabbit = wrapAround(xRabbit + makeRandomMove()); yRabbit = wrapAround(yRabbit + makeRandomMove()); displayPosition(xFox, yFox, xRabbit, yRabbit); // Get input from user cout << endl << "Enter y to quit, n to continue "; cin >> c; if (c=='y') { quit = true; } } cout << "Bye" << endl; return 0; }