View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

Sign up now

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

23 replies to this topic

### #1selve  Members

Posted 21 November 2012 - 10:23 AM

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?

### #2Álvaro  Members

Posted 21 November 2012 - 10:29 AM

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'?

### #3Servant of the Lord  Members

Posted 21 November 2012 - 10:32 AM

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.
It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #4rip-off  Moderators

Posted 21 November 2012 - 11:35 AM

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?

### #5selve  Members

Posted 21 November 2012 - 11:55 AM

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%585using 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); Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav"); screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE); background = IMG_Load("images/texture.jpg"); ball = IMG_Load("images/ball.png"); 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, 21 November 2012 - 12:18 PM.

### #6C0lumbo  Members

Posted 21 November 2012 - 11:59 AM

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.

### #7selve  Members

Posted 21 November 2012 - 12:11 PM

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, 21 November 2012 - 12:40 PM.

### #8SuperVGA  Members

Posted 21 November 2012 - 12:44 PM

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.

### #9ultramailman  Prime Members

Posted 21 November 2012 - 12:50 PM

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, 21 November 2012 - 12:51 PM.

### #10Álvaro  Members

Posted 21 November 2012 - 12:58 PM

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, 21 November 2012 - 01:00 PM.

### #11selve  Members

Posted 21 November 2012 - 01:05 PM

Thanks all, now it's working.
Instead of using:
[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, 21 November 2012 - 01:11 PM.

### #12rip-off  Moderators

Posted 21 November 2012 - 01:05 PM

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.

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?

### #13selve  Members

Posted 21 November 2012 - 01:08 PM

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 585using 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); Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav"); screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE); background = IMG_Load("images/texture.jpg"); ball = IMG_Load("images/ball.png"); 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, 21 November 2012 - 01:11 PM.

### #14Álvaro  Members

Posted 21 November 2012 - 01:10 PM

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?

### #15selve  Members

Posted 21 November 2012 - 01:14 PM

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?

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, 21 November 2012 - 01:14 PM.

### #16Álvaro  Members

Posted 21 November 2012 - 01:46 PM

No, you should just use
balltarget.x = rand() % SCREEN_WIDTH;

What was the intention of the 100'?

### #17rip-off  Moderators

Posted 21 November 2012 - 03:23 PM

So if I want a normal random not multiplied should I do this:

Why do you think that would work?

### #18rip-off  Moderators

Posted 21 November 2012 - 04:50 PM

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!

### #19L. Spiro  Members

Posted 21 November 2012 - 04:54 PM

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, 21 November 2012 - 04:55 PM.

### #20selve  Members

Posted 22 November 2012 - 09:31 AM

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?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.