Build A C# Monkey Console App: A Fun Guide

by ADMIN 43 views

Hey guys! Ready to dive into a fun C# project? We're going to build a Monkey Console Application that lets you manage and display data about different monkey species. It's a cool way to learn about C# and console applications, with a touch of fun thanks to some awesome ASCII art. This project is perfect for beginners and a great way to level up your C# skills. We'll cover everything from creating the Monkey model to building an interactive menu. Let's get started!

Setting Up Your Monkey Console App

First things first, let's set up the project. We're going to use the .NET CLI to scaffold our application. This is super easy, and it gets you started with a basic console app structure. Open up your terminal or command prompt, and navigate to the directory where you want to create your project. Then, run the following command:

dotnet new console -o MyMonkeyApp

This command creates a new console application named MyMonkeyApp. The -o option specifies the output directory, which will also be named MyMonkeyApp. Next, let's open the project in your favorite code editor. I recommend Visual Studio Code (VS Code), as it is free and has great support for C# development. You can open the project by navigating to the MyMonkeyApp directory and opening the MyMonkeyApp.csproj file or the directory itself in VS Code.

Diving into the Monkey Model

Now, let's define our Monkey model class. This class will represent a monkey and will hold all the relevant information about it. Create a new file named Monkey.cs in your project directory and add the following code:

public class Monkey
{
    public string Name { get; set; }
    public string Location { get; set; }
    public int Population { get; set; }
    public string Description { get; set; }
}

This is a simple class with four properties: Name, Location, Population, and Description. We'll use these properties to store the monkey's name, where it lives, its population size, and a brief description. These properties are automatically public, so you can access them directly. This is a clean and concise way to define our data structure.

The MonkeyHelper: Your Monkey Data Companion

Next up, we're going to create a static class called MonkeyHelper. This class will handle all the data-related operations for our monkeys. Think of it as the brain behind our application's data handling. Create a new file named MonkeyHelper.cs and add the following code:

using System;
using System.Collections.Generic;
using System.Linq;

public static class MonkeyHelper
{
    private static readonly List<Monkey> _monkeys = new List<Monkey>()
    {
        new Monkey { Name = "Chimpanzee", Location = "Africa", Population = 300000, Description = "Highly intelligent and social primates." },
        new Monkey { Name = "Gorilla", Location = "Africa", Population = 310000, Description = "The largest primate, known for their strength." },
        new Monkey { Name = "Mandrill", Location = "Africa", Population = 2000, Description = "Colorful primates with distinctive facial features." },
        new Monkey { Name = "Orangutan", Location = "Asia", Population = 104700, Description = "Known for their long arms and reddish fur." },
        new Monkey { Name = "Tamarin", Location = "South America", Population = 10000, Description = "Small, arboreal monkeys with varied appearances." }
    };

    private static int _randomMonkeyRequests = 0;

    public static List<Monkey> GetMonkeys()
    {
        return _monkeys;
    }

    public static Monkey GetMonkeyByName(string name)
    {
        return _monkeys.FirstOrDefault(m => m.Name == name);
    }

    public static Monkey GetRandomMonkey()
    {
        _randomMonkeyRequests++;
        Random random = new Random();
        int index = random.Next(0, _monkeys.Count);
        return _monkeys[index];
    }

    public static int GetRandomMonkeyRequestCount()
    {
        return _randomMonkeyRequests;
    }
}

Key Methods in MonkeyHelper

  • GetMonkeys(): Returns a list of all available monkeys.
  • GetMonkeyByName(string name): Retrieves a monkey by its name, returning null if not found.
  • GetRandomMonkey(): Selects and returns a random monkey from the list. It also increments a counter to track how often this method is called.
  • GetRandomMonkeyRequestCount(): Returns the number of times GetRandomMonkey() has been called.

Data Seeding

In the MonkeyHelper, we have initialized a list of monkeys called _monkeys with hard-coded sample data. This is just to get us started. Later, we can replace this with data from a database or an API. This approach makes the application easy to run and test from the get-go.

Building the Console Menu

Now for the fun part: creating the interactive menu in Program.cs. This is where the user interacts with our application. It's the main loop that handles user input and calls the appropriate methods from MonkeyHelper. Open Program.cs and replace the contents with the following:

using System;
using System.Collections.Generic;

namespace MyMonkeyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                DisplayMenu();
                string choice = Console.ReadLine();

                switch (choice.ToUpper())
                {
                    case "1":
                        ListMonkeys();
                        break;
                    case "2":
                        ShowMonkeyDetails();
                        break;
                    case "3":
                        ShowRandomMonkey();
                        break;
                    case "4":
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine("Invalid choice. Please try again.");
                        break;
                }
            }
        }

        static void DisplayMenu()
        {
            Console.WriteLine("\nMonkey Console Application");
            Console.WriteLine("1. List all monkeys");
            Console.WriteLine("2. Show monkey details");
            Console.WriteLine("3. Pick a random monkey");
            Console.WriteLine("4. Exit");
            Console.Write("Enter your choice: ");
        }

        static void ListMonkeys()
        {
            List<Monkey> monkeys = MonkeyHelper.GetMonkeys();
            foreach (var monkey in monkeys)
            {
                Console.WriteLine({{content}}quot;- {monkey.Name}");
            }
        }

        static void ShowMonkeyDetails()
        {
            Console.Write("Enter monkey name: ");
            string name = Console.ReadLine();
            Monkey monkey = MonkeyHelper.GetMonkeyByName(name);

            if (monkey != null)
            {
                Console.WriteLine({{content}}quot;\nName: {monkey.Name}");
                Console.WriteLine({{content}}quot;Location: {monkey.Location}");
                Console.WriteLine({{content}}quot;Population: {monkey.Population}");
                Console.WriteLine({{content}}quot;Description: {monkey.Description}");
            }
            else
            {
                Console.WriteLine("Monkey not found.");
            }
        }

        static void ShowRandomMonkey()
        {
            Monkey monkey = MonkeyHelper.GetRandomMonkey();
            Console.WriteLine({{content}}quot;\nRandom Monkey: {monkey.Name}");
            Console.WriteLine({{content}}quot;Requests for Random Monkeys: {MonkeyHelper.GetRandomMonkeyRequestCount()}");
        }
    }
}

Menu Options Explained

  • List all monkeys (1): This option displays a list of all the monkey names.
  • Show monkey details (2): Prompts the user to enter a monkey's name and then displays its details if found.
  • Pick a random monkey (3): Shows a randomly selected monkey's name and the number of times a random monkey has been requested.
  • Exit (4): Exits the application.

Console Menu Implementation

The Main method is the core of our application. It presents the menu and handles user input using a while loop. The switch statement processes the user's choice and calls the appropriate methods. The other methods (DisplayMenu, ListMonkeys, ShowMonkeyDetails, and ShowRandomMonkey) handle the display and data retrieval.

Adding ASCII Art for Visual Appeal

To make our console application more visually appealing, let's add some ASCII art. This is a fun way to add some personality to our app. You can find ASCII art online by searching for "ASCII art monkey". For the purpose of this example, I will show one, but you can add more.

Here's an example of how to incorporate the ASCII art in the ShowRandomMonkey method:

static void ShowRandomMonkey()
{
    Monkey monkey = MonkeyHelper.GetRandomMonkey();
    Console.WriteLine({{content}}quot;\nRandom Monkey: {monkey.Name}");
    Console.WriteLine({{content}}quot;Requests for Random Monkeys: {MonkeyHelper.GetRandomMonkeyRequestCount()}");
    Console.WriteLine("");
    Console.WriteLine("  _.--""--._");
    Console.WriteLine(" .'          `.");
    Console.WriteLine(" /   O      O   \");
    Console.WriteLine("|    \  ^^  /    |");
    Console.WriteLine("\     `----'     /");
    Console.WriteLine(" `._          _.'");
    Console.WriteLine("    `--------'");
}

When you run this, a monkey ASCII art will be displayed along with the random monkey's name and request count.

Expanding the Application

XML Documentation

Adding XML documentation makes your code easier to understand and maintain. You can add comments above each method and class to describe their purpose and how to use them. This allows you to generate documentation automatically. For example:

/// <summary>
/// Represents a monkey.
/// </summary>
public class Monkey
{
    /// <summary>
    /// Gets or sets the name of the monkey.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the location of the monkey.
    /// </summary>
    public string Location { get; set; }

    /// <summary>
    /// Gets or sets the population of the monkey.
    /// </summary>
    public int Population { get; set; }

    /// <summary>
    /// Gets or sets a description of the monkey.
    /// </summary>
    public string Description { get; set; }
}

Unit Tests

Writing unit tests is a crucial part of software development. It helps ensure that your code works as expected. You can use a testing framework like xUnit or NUnit to write tests for your methods in MonkeyHelper. Here’s a basic example using xUnit:

  1. Install xUnit: You'll need to add the xUnit package to your project. You can do this by right-clicking on your project in Visual Studio's Solution Explorer, selecting