How can you get a random number on GBDK?

1.1k views Asked by At

I'm new to C and to GBDK and I want to code a random number generator that decides between 0 and 1. Like a 'hacker' simulator.

I have tried a lot of examples from the Internet. But none worked.

Screenshot from the output of the last attempt I made: https://i.ibb.co/f8G39vX/bgberrors.png

Last attempt code:

#include <gb/gb.h>
#include <stdio.h>
#include <rand.h>

void init();

void main() 
{
        init();
        while(1)
        {
            UINT8 r = ((UINT8)rand()) % (UINT8)4;
            printf(r);
        }
}

void init()
{
    DISPLAY_ON;
}

How can I accomplish it?

1

There are 1 answers

0
basxto On
#include <gb/gb.h>
#include <stdint.h>
#include <stdio.h>
#include <rand.h>

void init();

void main()
{
        init();
        printf(" \n\n\n\n\n\n\n\n    PRESS START!\n");
        // abuse user input for seed generation
        waitpad(J_START);
        uint16_t seed = LY_REG;
        seed |= (uint16_t)DIV_REG << 8;
        initrand(seed);
        while(1)
        {
            UINT8 r = ((UINT8)rand()) % (UINT8)2;
            printf("%d", r);
        }
}

void init()
{
        DISPLAY_ON;
}

Tested with GBDK-2020 4.0.3

Also check the "rand" example in GBDK-2020.

Regarding the comments:

Yes, GBDK has it's own lib (including stdlib). It's probably a fork of SDCC's lib 20 years ago. Current SDCC has rand() in stdlib.h, but GBDK-2020 doesn't. Max is 0xFF, I don't know of a define for that.

Float should be avoided as much as possible, it's completely done in software, there is no hardware support for this. Double isn't really supported by the compiler and falls back to float.

There are no man pages, documentation is available here: https://gbdk-2020.github.io/gbdk-2020/docs/api/rand_8h.html or read the gbdk_manual.pdf comming with gbdk-2020