The practice problem asks me to create an array of spaceship structures and a program that will continuously update their position as long as they are all within a 1024x728 grid. this is my code
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int num;
struct spaceShip
{
int x;
int y;
};
int randRange (int low, int high);
spaceShip update (spaceShip ship);
bool inbounds (spaceShip my_ships[],int num);
int main ()
{
cout << "How many space ships would you like to simulate?\n";
cin >> num;
spaceShip my_ships[num];
cout << "Generating random starting coordinates..." << endl;
for (int i = 0; i < num; i++)
{
my_ships[i].x = randRange(0,1024);
my_ships[i].y = randRange(0,728);
}
cout << "The starting coordinates are:\n";
for (int i = 0; i < num; i++)
{
cout << "Ship " << i + 1 << ": ";
cout << "(" << my_ships[i].x << "," << my_ships[i].y << ")" << endl;
}
cout << "Simulating movement..." << endl;
bool checker = inbounds(my_ships,num);
while(checker == true)
{
for (int i = 0; i < num; i++)
{
update(my_ships[i]);
}
}
cout << "One of the ships is now out of bounds.\n";
cout << "The final positions were:\n";
for (int i = 0; i < num; i++)
{
cout << "Ship " << i + 1 << ": ";
cout << "(" << my_ships[i].x << "," << my_ships[i].y << ")" << endl;
}
}
bool inbounds (spaceShip my_ships[], int num)
{
for (int i = 0; i < num; i++)
{
if (my_ships[i].x >= 1024 || my_ships[i].y >= 728)
{
return false;
}
}
return true;
}
int randRange (int low, int high) {
return rand() % (high - low + 1) + low;
}
spaceShip update (spaceShip ship)
{
int operation = randRange(1,2);
int movement = randRange(1,10);
switch (operation)
{
case 1: ship.x += movement;
ship.y += movement;
return ship;
break;
case 2: ship.x -= movement;
ship.y -= movement;
return ship;
break;
}
}
and this is the output i see:
$ ./ship_struct.exe
How many space ships would you like to simulate?
4
Generating random starting coordinates...
The starting coordinates are:
Ship 1: (308,261)
Ship 2: (387,680)
Ship 3: (500,483)
Ship 4: (577,354)
Simulating movement...
and it just gets stuck there. can anyone tell me why this is happening?