CSI
CSC126
Spring 2007
Courtesy:
Prof. L. Petingi
Find the Treasure
Switch, If,
Loops
A treasure is
hidden someplace ! The coordinates (x1,y1) are determined randomly, using the
code that is listed at the end of this lab. The purpose of the game is for the
Explorer to find the Treasure !
The explorer is
allowed to go North, South, West or East. The Explorer is first positioned at
location (30,30). If the explorer goes North, only the y coordinate is
increased by 1. Similarly if the explorer goes South the y coordinate is
decreased by 1. In the same fashion the x coordinate is increased or decreased
by 1 depending if the explorer goes East
or West,
respectively.
Each time the
Explorer ‘moves’, the distance between the Explorer and the treasure is
computed. Distance = sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1))
When the Explorer’s position is the same as the Treasure’s position,
the Explorer wins the Treasure !!
Procedures
1. You must
use a
2. At the
start of the loop, display the message "Please enter direction (n,s,e,w),
or x to exit: ".
3. Now,
get the position from the keyboard.
4. Update the
Explorer’s coordinates
5. Calculate
the distance from the explorer to the treasure:
Distance =
sqrt(static_cast<double>((x-x1)*(x-x1)+(y-y1)*(y-y1)))
6. Display the distance from the Treasure (this information will clue
the Explorer to either keep going in the same direction or switch directions).
7. Decisions……………
If
the distance is greater than 8
then you display the message "you are too far from the treasure".
If
the distance is greater than 4 and
less or equal to 8 you display the message "you are far from the
treasure".
If
the distance is less or equal
to 4 you display the message "you are getting closer to the
treasure".
Also,
check if you have reached the treasure (i.e., x=x1, and y=y1); and if so, Get out of the loop and display the message
"congratulations, you have reached the treasure".
8. At the end
of each loop display the message "Your
location is: ( x,y); where x and y
are the
Explorer’s
coordinates
9. Make sure that you print out how many steps it took to reach
the treasure
----------------------------------------------------------------------------------------------------------------------------
#include
<iostream>
#include
<cstdlib>
#include
<ctime>
#include
<cmath>
Using
namespace std;
int main ()
{
int
x=30,y=30; //
Explorer’s coordinates
int
x1,y1; //
Treasure’s coordinates
char
dir='a';
float
distance;
bool
treasure=false;
srand(time(0)); // secretly seed the rand
function !
x1=rand( ) %30 + 1; // x1 is randomly set to a number
between 1 //and 30
y1=rand( ) % 30 + 1; // y1 is randomly set to a number
between //1and 30;
//write loop to find the treasure