View Full Version : Random number generation using C code

west_dweller79

02-14-2005, 12:19 AM

Dear all, currently i'm doing a snake game, but i don't know how i can generate the food randomly when the snake eat it. Can someone help me?

I know i need to generate a random number to light up the led/food with x and y co-ordinate, but how should i do it?

I'm using ledrow[0] and ledcol[0] for the food co-ordinate.

Pls help

Thanks in advance

west_dweller

Mhtml

02-14-2005, 01:20 AM

You can use the rand() function from the standard libraries. You will most likely need to scale it within your bounds of 0,MAX_ROW and 0,MAX_COL so here is a good page explaining how to use the rand() function.

http://members.cox.net/srice1/random/crandom.html

Dunna

02-14-2005, 02:55 AM

Make sure you don't forget to seed the random number with srand(), or else the "random" numbers will always come out the same! Use the following:

#include <stdlib.h>

void main()

{

srand( (UNSIGNED)time(NULL) ); // <- Borrowed from MSDN

}

Put that line in your main (or WinMain) function and link in the stdlib.h and you'll be good to go! :thumbsup:

west_dweller79

02-14-2005, 05:45 PM

Sorry, i still don't know who to generate the number randomly. This is the code that i copy from the web and i did some modification.

void setfood(void)

{

int seed;

double r, x;

int y, z;

seed = 600;

srand(seed);

r = ( (double)rand() / (double)(RAND_MAX+1) );

x = (r * maxcol-1);

y = -1*((int) x);

z = (y + 1);

printf("random number %5d %5d\n",y,z);

row[0] = y;

col[0] = z;

}

Also what is the different between srand and rand ???

Thanks in advance

west_dweller

Mhtml

02-15-2005, 04:12 AM

srand() seeds the number generator.

rand() generates a random number.

Given a seed, and some fixed constants a set of mathematical operations are recursively performed. I believe they use modulus and some other operations in these sequence of operations.

void setfood(void)

{

int x, y;

x = y = 0;

x = rand()%MAX_COL+1;

y = rand()%MAX_ROW+1;

col[0] = x;

row[0] = y;

}

int main() {

srand(time(NULL));

return 0;

}

rand() will return a *random* number between 0 and RAND_MAX.

rand()%MAX_COL+1 will return a number between 0 and MAX_COL.

rand()%MAX_ROW+1 will return a number between 0 and MAX_ROW.

Continually seeding the generator with a changing seed, in this case it's time() (which is the number of seconds since Jan 1, 1970), changes the outcome of the mathematical operations and hence a new number.

[edit:] Realised a mistake or two, I only just woke up.

Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.