Gameboy Development Forum

Discussion about software development for the old-school Gameboys, ranging from the "Gray brick" to Gameboy Color
(Launched in 2008)

You are not logged in.

#1 2021-09-07 18:22:57

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

I'm trying to generate a random number in GBDK

I'm trying to generate a random number in GBDK between 24 and 144 and I can't seem to get it to work.

My code looks like this:     invader_x = rand() % (144 - 24 + 1) + 24; // move invader to random x position   

and I have:     #include <rand.h>      at the top of my code


Any help woulfd be appreciated, thanks

Brian

Offline

 

#2 2021-09-08 04:43:41

toxa
Member
Registered: 2020-02-13
Posts: 309

Re: I'm trying to generate a random number in GBDK

And what is the problem? It does not compile or produce wrong values? Do you use GBDK-2020?

Offline

 

#3 2021-09-08 12:56:44

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

Wrong values, my sprite ends up off the left side of the screen sometimes.

Offline

 

#4 2021-09-15 18:15:11

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

Anybody?

Offline

 

#5 2021-09-15 18:57:37

toxa
Member
Registered: 2020-02-13
Posts: 309

Re: I'm trying to generate a random number in GBDK

Do you use GBDK-2020?

Offline

 

#6 2021-09-16 13:47:17

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

Yes, and I'm including rand.h

Offline

 

#7 2021-09-16 15:09:48

toxa
Member
Registered: 2020-02-13
Posts: 309

Re: I'm trying to generate a random number in GBDK

you must offset your sprite 8 pixels by X. top-left corner of visible screen for sprites is: X==8, Y==16

Offline

 

#8 2021-09-16 15:50:23

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

Is this the correct code to generate a random number between 24 and 140?

invader_x = rand() % (140 - 24 + 1) + 24;

Also is this all I need above in my code to set it up?

void initarand (uint8_t seed );


I'm still having trouble getting this to work sad

Offline

 

#9 2021-09-17 11:17:36

toxa
Member
Registered: 2020-02-13
Posts: 309

Re: I'm trying to generate a random number in GBDK

bkumanchik wrote:

invader_x = rand() % (140 - 24 + 1) + 24;

rand() returns a signed char which is -128..127. to make rand() return a positive value within 0..255 you must cast it to unsigned char:

Code:

r = ((unsigned char)rand() % (140 - 24 + 1)) + 24;

Offline

 

#10 2021-09-17 11:29:38

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

Thanks, I'll try that

Offline

 

#11 2021-09-17 19:08:51

bkumanchik
Member
Registered: 2021-09-07
Posts: 10

Re: I'm trying to generate a random number in GBDK

That did it, Thanks!

Offline

 

Board footer

Powered by PunBB
© Copyright 2002–2005 Rickard Andersson