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

Started by
22 comments, last by L. Spiro 11 years, 4 months ago
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]
Advertisement
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?
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);
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]
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?

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]
No, you should just use
balltarget.x = rand() % SCREEN_WIDTH;

What was the intention of the `100'?

So if I want a normal random not multiplied should I do this:
[/quote]
Why do you think that would work?
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!

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

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

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?

This topic is closed to new replies.

Advertisement