Skip to content

C# Random Fortune

Get a random fortune!

Create a random fortune generator; a C# console application that selects a random element from a string array. The output is formatted to resemble the slip of paper found in a fortune cookie.

  • Array of strings
  • Instance of Random
  • Formatting output

Example Output

random fortune generator screenshot

random fortune generator screenshot

UML

random fortune generator class diagram

Code

The code for our random fortune generator is straightforward. Inside our Main function there are 4 statements:

  • Title = "Fortune";
  • Fortune fortune = new Fortune();
  • WriteLine("(Press enter to exit)");
  • ReadKey();

The first statement sets the title in the window's bar. We can use Title without specifying the type name Console because at the top of our document we have a 'using static' directive.

Title = "Fortune";

Without the directive it would be:

Console.Title = "Fortune";

The second statement makes an instance of Fortune (called 'fortune').

The third statement writes out a message to the screen to let players know they can press enter to exit (although any key will work). The last statement waits for a key press before continuing. Once a key is pressed, the application will close.

Program.cs

/*
 * Random Fortune Generator
 * by Your Name, Date
 *  
 * This work is a derivative of 
 * "Random Fortune Generator" by http://programmingisfun.com, used under CC BY.
 * https://creativecommons.org/licenses/by/4.0/
 */
using static System.Console;

namespace RandomFortune
{
    class Program
    {
        static void Main()
        {
            Title = "Fortune";
            Fortune fortune = new Fortune();
            WriteLine("(Press enter to exit)");
            ReadKey();
        }
    }
}

Fortune Class

The Fortune class has two fields: an instance of Random, and an array of strings (which holds the fortunes). The constructor has two variables (a random number, and a string that holds the random fortune).

Two methods are in the class: Format and Border. Format changes the background and foreground colors, adds some new lines, and calls the Border method twice. Border creates a line of decorative symbols above and below the fortune (in this case, the equal symbol). Passing in the length of the fortune text (as message.Length) allows the Border width to match the size of the fortune.

Fortune.cs

/*
 * Random Fortune Generator
 * by Your Name, Date
 *  
 * This work is a derivative of 
 * "Random Fortune Generator" by http://programmingisfun.com, used under CC BY.
 * https://creativecommons.org/licenses/by/4.0/
 */
using System;
using static System.Console;

namespace RandomFortune
{
    class Fortune
    {
        Random random = new Random();
        //fortunes from https://joshmadison.com/2008/04/20/fortune-cookie-fortunes/
        string[] fortunes = {
            "A faithful friend is a strong defense.",
            "A fresh start will put you on your way.",
            "A person of words and not deeds is like a garden full of weeds.",
            "Demand more from yourself, others respect you deeply.",
            "Determination is what you need now.",
            "Don’t let your limitations overshadow your talents.",
            "Feeding a cow with roses does not get extra appreciation.",
            "If a true sense of value is to be yours it must come through service.",
            "If certainty were truth, we would never be wrong.",
            "If you continually give, you will continually have.",
            "If you look in the right places, you can find some good offerings.",
            "If you think you can do a thing or think you can’t do a thing, you’re right.",
            "If you wish to see the best in others, show the best of yourself.",
            "If you’re feeling down, try throwing yourself into your work.",
            "Imagination rules the world.",
            "In the end all things will be known.",
            "It is better to deal with problems before they arise.",
            "It is honorable to stand up for what is right, however unpopular it seems.",
            "It is worth reviewing some old lessons.",
            "It takes courage to admit fault.",
            "It’s time to get moving. Your spirits will lift accordingly.",
            "Listen to everyone. Ideas come from everywhere.",
            "Living with a commitment to excellence shall take you far.",
            "The human mind, once stretched by a new idea, never regains the original dimensions.",
            "Miles are covered one step at a time.",
            "The end of something marks the start of something new.",
            "New people will bring you new realizations.",
            "Now is the time to try something new.",
            "Physical activity will dramatically improve your outlook today.",
            "Pandas like eating bamboo, but I prefer mine dipped in chocolate.",
            "Practice makes perfect.",
            "Protective measures will prevent costly disasters.",
            "Put your mind into planning today. Look into the future.",
            "Rest has a peaceful effect on your physical and emotional health.",
            "Savor your freedom – it is precious.",
            "Sift through your past to get a better idea of the present.",
            "Success is a journey, not a destination.",
            "Swimming is easy. Staying afloat is hard.",
            "Take the high road.",
            "Stand up again after falling.",
            "The only people who never fail are those who never try.",
            "The person who will not stand for something will fall for anything.",
            "The philosophy of one century is the common sense of the next.",
            "There is no mistake so great as that of being always right.",
            "There is no such thing as an ordinary cat.",
            "Things don’t just happen; they happen just.",
            "Those who care will make the effort.",
            "You are a person of another time.",
            "You are almost there.",
            "You can see a lot just by looking.",
            "You can’t steal second base and keep your foot on first.",
            "You have an active mind and a keen imagination.",
            "You have the power to write your own fortune.",
            "Your dreams are worth your best efforts to achieve them.",
            "Your leadership qualities will be tested and proven.",
            "Your mind is a great asset.",
            "Your talents will be recognized and suitably rewarded."
        };

        public Fortune()
        {
            //choose a random number within the range of the string array 'fortunes'
            int number = random.Next(fortunes.Length);
            //select the fortune stored at that index number
            string fortune = fortunes[number];
            Format(fortune);
        }

        //Change background and foreground color for the fortune ('message')
        public void Format(string message)
        {
            BackgroundColor = ConsoleColor.White;
            ForegroundColor = ConsoleColor.Blue;
            Write("\n\n");
            Border(message.Length);
            WriteLine(message);
            Border(message.Length);
            Write("\n\n");
            ResetColor();
        }

        //Create a border that is the same length as the fortune string
        public void Border(int spaces)
        {
            for (int i = 0; i < spaces; i++)
            {
                Write("=");
            }
            Write("\n");
        }
    }
}

Code is also on GitHub as a gist.

Improve Your Random Fortune Generator

Suggestions to expand on this application:

  • Allow players to see another fortune without closing the application and reloading it.
  • Choose a fortune using information from the player. For example, you can add up the numbers for their birthday. One way could be to add numbers and reduce; 9/1/1990 is 9+1+1990 (2000). 2000 is then reduced (2+0+0+0 = 2) so their "birth date fortune" could be array element 2.
  • Improve the overall look and feel of the application. Add some text at the beginning to set the tone, and maybe an ASCII graphic.