# [C++] Delayed action of srand() - coordinates for object

This topic is 1885 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,
I've created the small program where the ball is moving all the time on the screen to random coordinates made like that:

[source lang="cpp"]srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;[/source]
It's included in while(!gameover) function. That moves the ball:

[source lang="cpp"]void moveBall()
{
if(ballposition.x > ballX)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < ballX)
{
ballposition.x += ballspeed;
}
if(ballposition.y > ballY)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < ballY)
{
ballposition.y += ballspeed;
}
}[/source]

The only problem is that the ball is moving to the right coordinates X and Y, then sometimes stays for a moment and then another move and so on. When I try to delete the "srand(time(NULL));" it causes the ball to move really fast in each direction but no lag. How can I fix this?

##### Share on other sites
I don't see any calls to rand() in that code, so I am having a hard time following what it's doing. What exactly are randx' and randy'?

##### Share on other sites
How is randx and randy being set?

I'm not yet sure if this is your problem, I think you should post a bit more code, but srand(time(NULL)); should (in most simple programs) only be called once: when your game starts up. Not every frame of your game.

Could you post your entire main loop, cutting out the portions that don't involve randomness or the ball movement? I'd like to see the flow of your code, to mentally walk through it and see what's up.

##### Share on other sites
What is the intent of your program? Should it pick a random point, move to it, pick a new point, moves slowly to it, etc, etc? Or should the ball just meander around in a random fashion?

##### Share on other sites
Oh, sorry. Random numbers are defined here:
[source lang="cpp"]#define randx rand()*100%1175
#define randy rand()*100%585[/source]

The whole code:

[source lang="cpp"]#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_image.h"
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#define randx rand()*100%1175
#define randy rand()*100%585

using namespace std;

SDL_Surface * screen;
SDL_Surface * background;
SDL_Surface * ball;
SDL_Rect ballposition;
SDL_Event event;
int mouseX, mouseY;
int ballX = randx, ballY = randy;
int oldx, oldy;
int ballspeed = 1;
bool gameover = false;

void moveBall()
{
if(ballposition.x > ballX)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < ballX)
{
ballposition.x += ballspeed;
}
if(ballposition.y > ballY)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < ballY)
{
ballposition.y += ballspeed;
}
}

int main(int argc, char * args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE);
ballposition.x = 500;
ballposition.y = 400;
ballposition.h = 80;
ballposition.w = 80;
while(!gameover)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;

while(SDL_PollEvent(event))
{
if(event.type == SDL_QUIT)
{
SDL_Quit();
return 0;
}
if(event.type == SDL_MOUSEMOTION)
{
mouseX = event.motion.x;
mouseY = event.motion.y;
}
if(event.button.button == SDL_BUTTON_LEFT
&&
( mouseX >= ballposition.x &&
mouseX <= ballposition.x + ballposition.w ) &&
( mouseY >= ballposition.y &&
mouseY <= ballposition.y + ballposition.h ) )
{
ballspeed++;
Mix_PlayChannel(0, click, 0);
}
}
moveBall();
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(ball, NULL, screen, &&ballposition);
SDL_Flip(screen);
}
}
[/source]

The point of the game is just to click on the moving ball which causes increase of its speed. Edited by selve

##### Share on other sites
With the srand line in your program, ballX and ballY are being set to a single value for an entire second, then changes to another value. This is because the 'time' function precision is only one second, and you're using that to seed the random number generator.

With the srand removed (it should be removed, generally you only want to seed your RNG once), then your code is setting ballX and ballY to a new value every single frame, so the balls movement is more volatile.

What I guess you really want to do is change your code so that srand is called only during program initialisation, and add a condition so that you only set ballX and ballY to new values once the ball has reached the target.

##### Share on other sites
So how should it look like?
I've did this in ball moving function:
[source lang="cpp"]if(ballposition.x == ballX && ballposition.y == ballY)
{
targetreached = true;
}
[/source]
And this in while(!gameover):
[source lang="cpp"]if(targetreached)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;
targetreached = false;
}
[/source]

But it is still not working ;/ The ball is just moving to one position and then doesn't move any more. Edited by selve

##### Share on other sites

So how should it look like?
I've did this in ball moving function:
[source lang="cpp"]if(ballposition.x == ballX &amp;&amp; ballposition.y == ballY)
{
targetreached = true;
}
[/source]
And this in while(!gameover):
[source lang="cpp"]if(targetreached)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 &amp;&amp; abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;
targetreached = false;
}
[/source]

But it is still not working ;/ The ball is just moving to one position and then doesn't move any more.

I'm sure I saw a couple of clever minds in this thread commenting on the behaviour of srand() and rand()
and also, where srand() should be placed due to this behavior: on startup.
I'm also sure you'll be better off not using #defines when you can avoid it.

##### Share on other sites

while(!gameover) { srand(time(NULL));

if(targetreached) { srand(time(NULL)); 

You are not supposed to srand so much. srand should only be used right at the beginning of the program, in the main function.

int main(void) { srand(time(0)); /*main loop...*/ return 0; };

Also, don't use those misleading macros, just use the expression explicitly.
 #define SCREEN_WIDTH 1175 #define SCREEN_HEIGHT 585 ... ballX = (rand() * 100) % SCREEN_WIDTH; ballY = (rand() * 100) % SCREEN_HEIGHT;  Edited by ultramailman

##### Share on other sites
As SuperVGA is saying, call srand() a single time at the beginning of your program and don't use macros. You could also benefit from better variable names. In particular ballX and ballY look like they would describe the ball's position, but they actually represent the target position for the ball.

Since you are using ballposition.x and ballposition.y somewhere in the code, you must already have a type to represent positions, so use it: Instead of ballX and ballY have a single variable ball_target.

Also, what's the point of having oldx and oldy? In the part of the code where they are used it looks like the position of the ball already contains that information, and I am guessing the code would become more readable if you use that instead.

Oh, the while' condition in the loop selects a random point that is in the 300-pixel-wide cross centered around the current location of the ball. Is that what the intention was? Edited by Álvaro

##### Share on other sites
Thanks all, now it's working.
[source lang="cpp"]if(ballposition.x == balltarget.x && ballposition.y == balltarget.y)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/source]

I used:
[source lang="cpp"]if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/source] Edited by selve

##### Share on other sites
In C++, the preprocessor should generally be reserved for including files, include guards and other forms of conditional compilation (such as platform specific implementations). You should not use it for constants, or functions. There are places where it is of use, such as a custom ASSERT() macro.

So ultramailman's code should look like:
 const int SCREEN_WIDTH = 1175; const int SCREEN_HEIGHT = 585; ... ballX = (rand() * 100) % SCREEN_WIDTH; ballY = (rand() * 100) % SCREEN_HEIGHT; 

You can use helper functions to remove redundancy and help simply the code:
 const int SCREEN_WIDTH = 1175; const int SCREEN_HEIGHT = 585; const int RANDOM_GRANULARITY = 100; int random(int max) { return (std::rand() * RANDOM_GRANULARITY) % max; } // ... ballX = random(SCREEN_WIDTH); ballY = random(SCREEN_HEIGHT); 

But it is still not working ;/ The ball is just moving to one position and then doesn't move any more.
[/quote]
Are you sure targetreached becomes true? If so, does the logic for changing the ball's target get called?

Your code allows the ball's speed to be faster than a single pixel, yet you require the ball to perfectly hit the target pixel in order to compute a new target. An alternative is to test if the distance between the ball's position and the target position is less than the ball's speed.

Can you post a full copy of your current code?

##### Share on other sites
Here's the whole code:

[source lang="cpp"]#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_image.h"
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#define SCREEN_WIDTH 1175
#define SCREEN_HEIGHT 585

using namespace std;

SDL_Surface * screen;
SDL_Surface * background;
SDL_Surface * ball;
SDL_Rect ballposition;
SDL_Rect balltarget;
SDL_Event event;
int mouseX, mouseY;
int oldx, oldy;
int ballspeed = 3;
bool gameover = false;
bool targetreached = false;

void moveBall()
{
if(ballposition.x > balltarget.x)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < balltarget.x)
{
ballposition.x += ballspeed;
}
if(ballposition.y > balltarget.y)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < balltarget.y)
{
ballposition.y += ballspeed;
}
if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}
}

int main(int argc, char * args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE);
ballposition.x = 500;
ballposition.y = 400;
ballposition.h = 80;
ballposition.w = 80;
srand(time(0));
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
while(!gameover)
{
while(SDL_PollEvent(&amp;event))
{
if(event.type == SDL_QUIT)
{
SDL_Quit();
return 0;
}
if(event.type == SDL_MOUSEMOTION)
{
mouseX = event.motion.x;
mouseY = event.motion.y;
}
if(event.type == SDL_MOUSEBUTTONDOWN)
if(event.button.button == SDL_BUTTON_LEFT
&amp;&amp;
( mouseX >= ballposition.x &&
mouseX <= ballposition.x + ballposition.w ) &amp;&amp;
( mouseY >= ballposition.y &&
mouseY <= ballposition.y + ballposition.h ) )
{
ballspeed++;
Mix_PlayChannel(0, click, 0);
}
}
moveBall();
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(ball, NULL, screen, &amp;ballposition);
SDL_Flip(screen);
}
}
[/source] Edited by selve

##### Share on other sites
 balltarget.x = (rand() * 100) % SCREEN_WIDTH;[/quote]

That code basically picks a random column that is a multiple of the greatest common divisor of 100 and SCREEN_WIDTH. Are you sure that's what you want?

##### Share on other sites

 balltarget.x = (rand() * 100) % SCREEN_WIDTH;

That code basically picks a random column that is a multiple of the greatest common divisor of 100 and SCREEN_WIDTH. Are you sure that's what you want?
[/quote]
So if I want a normal random not multiplied should I do this:

[source lang="cpp"]balltarget.x = ( (rand() * 100) % SCREEN_WIDTH) / 2;[/source] Edited by selve

##### Share on other sites
No, you should just use
balltarget.x = rand() % SCREEN_WIDTH;

What was the intention of the 100'?

##### Share on other sites

So if I want a normal random not multiplied should I do this:
[/quote]
Why do you think that would work?

##### Share on other sites
I've gone through your code in detail, if you are interested in feedback:
 // I like to include the standard headers first #include <iostream> // Note: time.h is a C header. In C++, we use <ctime> #include <ctime> // This is also a C header, but it is unnecessary // C++ has a built-in boolean type // #include <stdbool.h> // This is the recommended way to include SDL. It is works we #include "SDL.h" #include "SDL_ttf.h" #include "SDL_mixer.h" #include "SDL_image.h" // This isn't actually used, so I've removed it // #include <windows.h> // Do not use #define for constants // The preprocessor doesn't understand C++ const int SCREEN_WIDTH = 1280; const int SCREEN_HEIGHT = 720; // The size of the ball is fixed, so we can use a constant // Alternatively, we could use ballImage->w and ballImage->h const int BALL_SIZE = 80; using namespace std; // Note: no globals! // This is a type to represent a position on the screen struct Point { int x; int y; }; // This helper function returns true if "point" is inside "rectangle" bool pointInRectangle(Point point, SDL_Rect rect) { // Using early returns from a boolean function makes it easier to // write this function. The alternative would be a massive boolean // expression that is harder to parse and understand. if(point.x < rect.x || point.x > (rect.x + rect.w)) { return false; } if(point.y < rect.y || point.y > (rect.y + rect.h)) { return false; } return true; } // Instead of having lots of variables called "ball", we can // wrap them all in a single structure with short names. struct Ball { Point position; Point target; int speed; }; // This is a helper function. We would otherwise have to duplicate this // logic twice, once where the target has been reached, another time // when we are initialisating the ball. Point pickRandomTarget() { // I've removed the * 100 as has been discussed in the thread // Also note the way we can infer the size of the target area // rather than have extra constants for this int x = rand() % (SCREEN_WIDTH - BALL_SIZE); int y = rand() % (SCREEN_HEIGHT - BALL_SIZE); Point target = { x, y }; return target; } // Passing the ball by reference means that we can avoid making // "ball" a global, yet we can still change the value in main() void moveBall(Ball &ball) { // This makes it a little easier to write this function // Instead of having to write ball.position.x > ball.target.x Point &position = ball.position; Point &target = ball.target; // These conditions are related, but mutually exclusive // I've moved the second condition to an "else" clause if(position.x > target.x) { position.x -= ball.speed; } else if(position.x < target.x) { position.x += ball.speed; } // The whitespace above helps they eye notice the // transition from X to Y in this next segment if(position.y > target.y) { position.y -= ball.speed; } else if(position.y < target.y) { position.y += ball.speed; } // Separating these expressions into a variables helps make // the condition that follows more reasonable. int distanceX = abs(position.x - target.x); int distanceY = abs(position.y - target.y); if(distanceX < ball.speed && distanceY < ball.speed) { target = pickRandomTarget(); } } int main(int argc, char * args[]) { // Putting this first thing makes it hard to accidentally call // rand() before the seed has been changed srand(time(0)); // You need to check for errors when you call functions that may return them if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { // It is also nice to have a way of finding out what went wrong... // This is really good when you distribute your game and you have // to debug the game on someone elses computer! cerr << "Failed to initialise SDL: " << SDL_GetError() << endl; return 1; } // This is a neat trick to allow us to return early from main() without // having to remember to call all the cleanup functions atexit(&SDL_Quit); // SDL_Mixer is another library whose initialisation must be checked for errors if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) < 0) { // A better approach would be to disable sound in this case, but play // on. We could set "click" to NULL to indicate this. // // This is the "easy" way: bail out immediately! cerr << "Failed to initialise SDL_Mixer: " << Mix_GetError() << endl; return 1; } atexit(&Mix_CloseAudio); // Here, we can re-use our SCREEN_(WIDTH|HEIGHT) constants! SDL_Surface *screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_DOUBLEBUF | SDL_SWSURFACE); if(!screen) { cerr << "Failed to set video mode: " << SDL_GetError() << endl; return 1; } Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav"); if(!click) { cerr << "Failed to load click sound: " << Mix_GetError() << endl; return 1; } SDL_Surface *background = IMG_Load("images/texture.jpg"); if(!background) { cerr << "Failed to load background image: " << IMG_GetError() << endl; // This is what atexit() helps us avoid, but we cannot use atexit() for this Mix_FreeChunk(click); return 1; } SDL_Surface *ballImage = IMG_Load("images/ball.png"); if(!ballImage) { cerr << "Failed to load ball image: " << IMG_GetError() << endl; // As you can see, it is getting worse! // There are other ways to handle this, but we can manage for the moment. Mix_FreeChunk(click); SDL_FreeSurface(background); return 1; } // It would be better to use a constructor, but one step at a time! Ball ball; // It is nice not to have magic numbers. Starting the ball in the center is // as good as anywhere, but it will work better if the size of the screen is changed ball.position.x = SCREEN_WIDTH / 2; ball.position.y = SCREEN_HEIGHT / 2; ball.target = pickRandomTarget(); // It is nice to make conditions such that they are naturally true bool running = true; // "while running" is (marginally) easier to understand than "while not game over" while(running) { // We can declare this event just before use, avoiding the need for a global SDL_Event event; while(SDL_PollEvent(&event)) { // Again, these conditions are related but mutually exclusive // So I've chained them. if(event.type == SDL_QUIT) { // By ending the loop here, we naturally fall off the end of main() // This runs our cleanup code running = false; } else if(event.type == SDL_MOUSEBUTTONDOWN) { // I prefer to always include curly braces around every condition // This makes it easier to change the program. // // Consider the following code: // if(condition) // actionA(); // // Imagine we need to add a second action: // if(condition) // actionA(); // actionB(); // // If the curly braces are forgotten, then actionA() remains conditional // but actionB will be called unconditionally! if(event.button.button == SDL_BUTTON_LEFT) { // There is no reason to track the position of the mouse // The SDL Button event also tells us where the click occurred Point mousePosition = { event.button.x, event.button.y }; // This is an example of bundling data needed by a function // into one object, rather than resorting to globals // or having lots of function parameters! SDL_Rect ballRectangle = { ball.position.x, ball.position.y, BALL_SIZE, BALL_SIZE }; // This is where our helper function comes in handy // It really simplifies understanding this code if(pointInRectangle(mousePosition, ballRectangle)) { ball.speed++; Mix_PlayChannel(0, click, 0); } } } } // Remember, moveBall() takes a reference, so the values inside "ball" // are actually updated moveBall(ball); SDL_BlitSurface(background, NULL, screen, NULL); // Note: there is no need to fill in the width and height of this rectangle // SDL takes the width and height of the blit from the "source" rectangle // You've set that to NULL, so the entire image will be used. SDL_Rect destination = { ball.position.x, ball.position.y }; SDL_BlitSurface(ballImage, NULL, screen, &destination); SDL_Flip(screen); } Mix_FreeChunk(click); SDL_FreeSurface(background); SDL_FreeSurface(ballImage); // Usually in C++, this isn't necessary // main() has a special exception from the need to always explicitly return a value // However, SDL #defines main to SDL_main, so it can provide platform specific // code where necessary. // // This is a good example of the preprocessor conflicting with your code return 0; } 
This code isn't compiled or tested, so watch out!

##### Share on other sites

I used:
if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed) { balltarget.x = (rand() * 100) % SCREEN_WIDTH; balltarget.y = (rand() * 100) % SCREEN_HEIGHT; }

Wrong again. It should be:
 if(abs(ballposition.x-balltarget.x)< ballspeed || abs(ballposition.y-balltarget.y)< ballspeed) { balltarget.x = (rand() * 100) % SCREEN_WIDTH; balltarget.y = (rand() * 100) % SCREEN_HEIGHT; }
And no I am not talking about the difference in whitespace nor your use of [source] instead of [code].

L. Spiro Edited by L. Spiro

##### Share on other sites
But if would do " || " it will for example work like this:
The ball has reached Y point, but didn't reached X point, so the new X and the new Y are created.
And I want to do it if the ball reaches X and Y. Am I right?

##### Share on other sites

Wrong again. It should be:
 if(abs(ballposition.x-balltarget.x)< ballspeed || abs(ballposition.y-balltarget.y)< ballspeed) { balltarget.x = (rand() * 100) % SCREEN_WIDTH; balltarget.y = (rand() * 100) % SCREEN_HEIGHT; }

umm....no? (seriously, i'm trying to figure out why you think this would work, am i missing something?)

##### Share on other sites
I guess if you really intend to use "manhattan units" how about using
 if( ( abs(ballposition.x-balltarget.x) + abs(ballposition.y-balltarget.y) ) < (ballspeed * 2) ) { balltarget.x = rand() % SCREEN_WIDTH; balltarget.y = rand() % SCREEN_HEIGHT; } 

But as it seems to be about a ball, I feel inclined to suggest that you just use an actual velocity vector,
the root of the squares of dX and dY added. (Or don't do the root but work in squared units, if you can/want to.)

Even better, you could use a 2d vector struct
 struct 2dmotionvector { float dx; float dy; float len; float angle; } 
To define your velocity, and work with that instead of having only independent x and y speeds to deal with.
-You can use len and angle primarily, and then set dx and dy if you need it in later statements.
(What if you apply spin to the ball, or it bounces off a surface? Way easier with 2d vector math on composite types in my opinion) Edited by SuperVGA

##### Share on other sites
Well, L.Spiro has a version that will at least trigger at all (when one coordinate is getting close enough), while the other version looks like in the end the ball will reach one coordinate first, then start jittering around on one axis, move only along the other axis and finally find a new destination. It also means that if one coordinate is reached, the balls will effectively move at only half the speed.

So obviously I second the approach of using vectors, simply because the other code only allows for 45° steps in motion and I doubt that sudden changes of direction while heading towards a destination are intended.

##### Share on other sites

umm....no? (seriously, i'm trying to figure out why you think this would work, am i missing something?)

My version is based on the logic in his first post. “If both coordinates move by over 300 units, generate new coordinates, but if only the X or the Y moves by over 300, that is fine.”

For his revision I only didn’t notice that he had switched from > to <, which achieves the correct results.

Comments would go a long way here. Don’t be afraid; they don’t bite. I really couldn’t look too terribly closely because there is not a single comment anywhere, although the code I “corrected” was small enough that I could have paid more attention there.

I still don’t really understand the goal behind the code, and again I would insist on using vectors. Makes everything simple.

L. Spiro