計算機科学のブログ

namespaces and classes - Organizing your code - class, reuse

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 3(namespaces and classes - Organizing your code)、p.183(Exercise)の解答を求めてみる。

コード

Guy.cs

namespace BettingGame;

internal class Guy
{
    public string? Name;
    public int Cash;

    public void WriteMyInfo()
    {
        Console.WriteLine($"{Name} has {Cash} bucks.");
    }
    public int GiveCash(int amount)
    {
        if (amount <= 0)
        {
            Console.WriteLine($"{Name} says: {amount} isn't a valid amount");
            return 0;
        }
        if (amount > Cash)
        {
            Console.WriteLine($"{Name} says: I don't have enough cash to give you {amount}");
            return 0;
        }
        Cash -= amount;
        return amount;
    }
    public void ReceiveCash(int amount)
    {
        if (amount <= 0)
        {
            Console.WriteLine($"{Name} says: {amount} isn't an amount I'll take");
        }
        else
        {
            Cash += amount;
        }
    }
}

Program.cs

using BettingGame;

double odds = 0.75;
Guy player = new Guy() { Name = "The player", Cash = 100 };

Console.WriteLine("Welcome to the casino. The odds are 0.75");

while (player.Cash > 0)
{
    player.WriteMyInfo();
    Console.Write("How much do you want to bet: ");
    string? howMuch = Console.ReadLine();
    if (int.TryParse(howMuch, out int amount))
    {
        int pot = player.GiveCash(amount);
        if (pot > 0)
        {
            pot *= 2;
            if (Random.Shared.NextDouble() > odds)
            {
                Console.WriteLine($"You win {pot}");
                player.ReceiveCash(pot);
            }
            else
            {
                Console.WriteLine("Bad luck, you lose.");
            }
        }
    }
    else
    {
        Console.WriteLine("Invalid");
    }
}
Console.WriteLine("The house always wins.");

入出力結果(Terminal, Zsh)

% dotnet run
Welcome to the casino. The odds are 0.75
The player has 100 bucks.
How much do you want to bet: 36
bad luck, you lose.
The player has 64 bucks.
How much do you want to bet: 27
You win 54
The player has 91 bucks.
How much do you want to bet: 83
bad luck, you lose.
The player has 8 bucks.
How much do you want to bet: 8
You win 16
The player has 16 bucks.
How much do you want to bet: a
Invalid
The player has 16 bucks.
How much do you want to bet: 16
You win 32
The player has 32 bucks.
How much do you want to bet: 32
Bad luck, you lose.
The house always wins.
%