Let’s Go Bowling – Solution

You may find my solution for this month’s Exercise to be more complex than necessary, but there’s a method to my madness.

First, I chose to use a structure, frame, to hold the information about the single frame bowled:

struct frame {
    char b1,b2;
    int ball1,ball2,score;
};

This choice came about as I was coding and realized that each frame has distinct elements that I wanted to keep: The first ball’s value, the second ball’s value, and then the characters used for each ball’s “value” (always a single digit), plus the total score.

Second, I chose to split up the solution into separate functions:

ball() retrieves a random number within a specific range. The range was added so that the second ball rolled would not exceed the number of pins standing.

get_frame() fills a frame structure. This function “rolls” the balls, then sets each frame structure member accordingly. It tests for a strike, spare, calculates the proper score and assigns characters for each ball rolled.

Finally, the main() function is blessedly brief, thanks to the other two functions. It initializes the randomizer, fetches a frame structure, then displays the results.

Here is my solution:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct frame {
    char b1,b2;
    int ball1,ball2,score;
};

int ball(int pins)
{
    return( rand() % (pins + 1));
}

void get_frame(struct frame *f)
{
    f->ball1 = ball(10);
    if(f->ball1==10)
    {
        f->ball2 = 0;
        f->b1 = 'X';
        f->b2 = ' ';
        f->score = 10;
        return;
    }

    f->ball2 = ball(10 - f->ball1);
    f->score = f->ball1 + f->ball2;
    f->b1 = f->ball1 ? '0' + f->ball1 : '-';
    f->b2 = f->ball2 ? '0' + f->ball2 : '-';
    if( f->score==10 )
        f->b2 = '/';
}

int main()
{
    struct frame game;

    srand((unsigned)time(NULL));

    get_frame(&game);

    printf("| %c|%c|\n",game.b1,game.b2);
    printf("| %2d |\n",game.score);

    return(0);
}

Remember that my code presents only one possible solution. My observation is that no one correct solution exists, and if your code displays consistent results and doesn’t blow up the computer, you’re doing well.

As a heads-up, I used this modular design for another, nefarious reason: Next month’s Exercise is to code entire bowling game simulation, 10 frames. If you think of this month’s problem in that perspective, then you can see why I made the choices I did.

Leave a Reply