Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

On pseudorandom numbers and Tetris

Name: Anonymous 2009-11-15 11:24

So I'm programming a Tetris clone in Sepples and SDL. I need a method of generating a random number between 0 and 6 (seven different types of blocks) that gives a, more or less, even chance for each value to occur. I could use ctime and cstdlib to generate a pseudorandom number, then modulus that number by 7, but that wouldn't be an even chance. Some pieces would fall more often than others.

How does /prog/ get their pseudorandoms to be convincing?

Name: Anonymous 2009-11-15 12:01

Weird, I just wrote a Tetris clone earlier this week. Here's mine...

typedef int bag_t;

// Replace this with whatever you like; it should
// produce integers in the range [0, limit).
int
randomint(int limit)
{
    return rand() % limit;
}

bag_t
fillbag()
{
    int bag = 01234567;
    for (int n = 1; n < 7; n++) {
        int k = randomint(n + 1);
        int kv = (bag >> (3 * k)) & 7;
        int nv = (bag >> (3 * n)) & 7;
        bag &= ~((7 << (3 * k)) | (7 << (3 * n)));
        bag |= (kv << (3 * n)) | (nv << (3 * k));
    }
    return bag;
}

int
nextpiece(bag_t *pbag)
{
    if (*pbag == 0)
        *pbag = fillbag();
    int r = (*pbag) & 7;
    *pbag >>= 3;
    return r - 1;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List