(very) Minigame Monday: 21

 21:

  • The concept:

Seeing as I wanted to spend time on the game jam this Monday, I decided to do something very simple. My task was to create the card game 21; nothing unique, but a good chance to practice efficient programming. To give a quick summary of the game, you are dealt two cards, and can draw additional cards. The aim is to get as close to 21 as possible without going over. There are a couple of rules that added a bit of depth to the programming (for example aces can be either 1 or 11), but on the whole a pretty simple task.

  • The challenge:

I did want to handle the deck in the most effecient way possible and avoid making the shuffling more complex than it needed to be. I decided to use a list to store the deck, because lists, unlike other storage containers, are able to efficiently add elements at a given point with constant complexity. This allowed me to shuffle the deck in a single for loop without the added linear complexity of adding the elements that using vectors would require. However, lists don't have a random access operator, so getting to the right position to add an element was still linear in complexity. I suspect both vectors and lists perform similar with my method. My code to produce a shuffled deck is as follows:

list<int> ShuffleDeck()
{
    /* initialize random seed: */
    srand(time(NULL));

    list<int> deck;
    deck.clear();
    for (int i = 0; i < 52; i++)
    {
        list<int>::iterator pos = deck.begin();
        int addSpot = (floor(rand() % (deck.size() + 1)));
        for (int j = 0; j < addSpot; j++)
            pos++;
        deck.emplace(pos, i);
    }
    return deck;
}

After looking into it now, after the fact, it looks like the most efficent way of shuffling an array is by swapping elements, which can be done in linear time. I think I was pretty unlikely to find this solution however, as it's not obvious that the result is always shuffled with equal probablity. 

  • The result:


 It's a game of 21! It's pretty basic, but it follows all of the rules. You can play it for yourself and look at the full code on my github: https://github.com/RedDragonMakesGames/21/tree/main/21%20project.

Comments

Popular posts from this blog

Armageddump (Boss Rush Jam 2023)

Imperfect Control: Gameplay

Hair of the Wolf (GameOff 2022)