C
C#•7mo ago
Zeksy

My First Ever C-Sharp Mini Project!

Hey there! I've invested 6 hours in learning C# so far and cleared the basics overall/got a rough idea of the syntax. I'm a python programmer working with that language for over a year. After finishing the basics, I just made my first C# minigame, RPS nothing too crazy. The goal was to achieve a program with the properties: -> The program takes input from the user -> Until the input is rock, paper or scissor, the program asks the user to re-try because invalid input -> There are aliases for rock, paper and scissor such as r, p and s. So if a user types r the program should automatically understand that they are picking rock and continue from there. -> Making computer pick a random choice from RPS -> Declaring the win/loss with a custom message. I succeeded in achieving it without external help yippies and here's what the code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
internal class RPS
{
static void Main(string[] args)
{

List<string> PossibleChoices = new List<string> {"rock", "paper", "scissor"};

// A dictionary that stores alternative names for RPS entires
Dictionary<string, List<string> > ChoicesDictionary = new Dictionary<string, List<string>>
{
{ "rock" , new List<string> {"rock", "rocks", "r"} },
{ "paper" , new List<string> {"papers", "p", "paper"} },
{ "scissor" , new List<string> {"s", "scissors", "scissor"} },
};


// A dictionary that tells who wins against who
Dictionary <string, string> WinsAgainst = new Dictionary<string, string>
{
{ "rock" , "scissor"},
{ "paper" , "rock"},
{ "scissor" , "paper"},
};

string MyChoice = "";
do
{
Console.WriteLine("Welcome to the game of Rock Paper and Scissor!\nTo play, make a choice!\n");
MyChoice = Console.ReadLine() ?? "";
if (! PossibleChoices.Contains(MyChoice.ToLower()))
{
foreach (string key in ChoicesDictionary.Keys)
{
if (ChoicesDictionary[key].Contains(MyChoice))
{
MyChoice = key;
break;
}
}
if (! PossibleChoices.Contains(MyChoice.ToLower()))
{
Console.WriteLine($"{MyChoice} is not a valid choice try again\n");
}

};

} while (! PossibleChoices.Contains(MyChoice.ToLower()));

Random random = new Random();
string computerChoice = PossibleChoices[random.Next(PossibleChoices.Count)];


string status = "";
if (computerChoice == MyChoice)
{
status = "The game resulted in a draw";
}
else if (WinsAgainst[MyChoice] == computerChoice) {
status = "Congrats! You won the game!";
}
else status = "You lost, sadly. Better luck next time!";
Console.WriteLine($"You chose {MyChoice} & Computer chose {computerChoice} " + status);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
internal class RPS
{
static void Main(string[] args)
{

List<string> PossibleChoices = new List<string> {"rock", "paper", "scissor"};

// A dictionary that stores alternative names for RPS entires
Dictionary<string, List<string> > ChoicesDictionary = new Dictionary<string, List<string>>
{
{ "rock" , new List<string> {"rock", "rocks", "r"} },
{ "paper" , new List<string> {"papers", "p", "paper"} },
{ "scissor" , new List<string> {"s", "scissors", "scissor"} },
};


// A dictionary that tells who wins against who
Dictionary <string, string> WinsAgainst = new Dictionary<string, string>
{
{ "rock" , "scissor"},
{ "paper" , "rock"},
{ "scissor" , "paper"},
};

string MyChoice = "";
do
{
Console.WriteLine("Welcome to the game of Rock Paper and Scissor!\nTo play, make a choice!\n");
MyChoice = Console.ReadLine() ?? "";
if (! PossibleChoices.Contains(MyChoice.ToLower()))
{
foreach (string key in ChoicesDictionary.Keys)
{
if (ChoicesDictionary[key].Contains(MyChoice))
{
MyChoice = key;
break;
}
}
if (! PossibleChoices.Contains(MyChoice.ToLower()))
{
Console.WriteLine($"{MyChoice} is not a valid choice try again\n");
}

};

} while (! PossibleChoices.Contains(MyChoice.ToLower()));

Random random = new Random();
string computerChoice = PossibleChoices[random.Next(PossibleChoices.Count)];


string status = "";
if (computerChoice == MyChoice)
{
status = "The game resulted in a draw";
}
else if (WinsAgainst[MyChoice] == computerChoice) {
status = "Congrats! You won the game!";
}
else status = "You lost, sadly. Better luck next time!";
Console.WriteLine($"You chose {MyChoice} & Computer chose {computerChoice} " + status);
}
}
}
It's working as intended but no doubt that I could make improvements in the code. Anyone whos more experienced with the lang please tell me how would you approach it/what changes would you make to achieve the same thing in much easier/better way or simply put, how can I improve the program
7 Replies
Zeksy
ZeksyOP•7mo ago
It was also my first Python project when I was learning it a year ago, pretty glad of where I stand in terms of py now so I thought I'd recreate the same thing in c# to progress further. Here's what the py code looked like if anyone is interested xD
import random
choices = ["rock", "paper", "scizor"]

choicesDictionary = {

"rock": {
"alias": ["r", "rocks", "1"],
"win": "scizor",
"lose": "paper",
},

"paper": {
"alias": ["p", "papers", "2"],
"win": "rock",
"lose": "scizor",
},

"scizor": {
"alias": ["s", "scizors", "3"],
"win": "paper",
"lose": "rock",
},


}

playerChoice = input("Make your choice:\n")

if playerChoice not in choices:
for choice in choicesDictionary.keys():
if playerChoice in choicesDictionary[choice]["alias"]:
playerChoice = choice
break

while playerChoice not in choices:
playerChoice = input("Make your choice:\n")
if playerChoice not in choices:
for choice in choicesDictionary.keys():
if playerChoice in choicesDictionary[choice]["alias"]:
playerChoice = choice

computer = random.choice(choices)

if choicesDictionary[playerChoice]["win"] == computer: status = "You won the game!"
if choicesDictionary[playerChoice]["lose"] == computer: status = "You lost the game!"
if playerChoice == computer: status = "The game resulted in a draw!"


print(f"The game started! You chose {playerChoice}")
print(f"Computer chose {computer}! {status}")
import random
choices = ["rock", "paper", "scizor"]

choicesDictionary = {

"rock": {
"alias": ["r", "rocks", "1"],
"win": "scizor",
"lose": "paper",
},

"paper": {
"alias": ["p", "papers", "2"],
"win": "rock",
"lose": "scizor",
},

"scizor": {
"alias": ["s", "scizors", "3"],
"win": "paper",
"lose": "rock",
},


}

playerChoice = input("Make your choice:\n")

if playerChoice not in choices:
for choice in choicesDictionary.keys():
if playerChoice in choicesDictionary[choice]["alias"]:
playerChoice = choice
break

while playerChoice not in choices:
playerChoice = input("Make your choice:\n")
if playerChoice not in choices:
for choice in choicesDictionary.keys():
if playerChoice in choicesDictionary[choice]["alias"]:
playerChoice = choice

computer = random.choice(choices)

if choicesDictionary[playerChoice]["win"] == computer: status = "You won the game!"
if choicesDictionary[playerChoice]["lose"] == computer: status = "You lost the game!"
if playerChoice == computer: status = "The game resulted in a draw!"


print(f"The game started! You chose {playerChoice}")
print(f"Computer chose {computer}! {status}")
I just re-created it in c# and guess it wasn't bad even tho this one has a lot better readablity
Keswiik
Keswiik•7mo ago
More of a fit for #code-review
Pobiega
Pobiega•7mo ago
Suffers a bit from primitive obsession. C# has a rich type system, use it instead of just having string everywhere. I'd create an enum for choices instead of using a string and create methods to break up the long block of code.
static class Program
{
private static readonly Dictionary<Choice, Choice> WinsAgainst =
new() { [Choice.Rock] = Choice.Scissors, [Choice.Paper] = Choice.Rock, [Choice.Scissors] = Choice.Paper, };

static void Main()
{
Console.WriteLine("Rock, Paper, Scissors! Enter your choice: ");
Choice playerChoice;
while (true)
{
var choice = ParseChoice(Console.ReadLine());
if (choice != null)
{
playerChoice = choice.Value;
break;
}

Console.WriteLine("Invalid choice. Try again.");
}

// we don't need to declare a new random instance every time, just use Random.Shared
var computerChoice = (Choice)Random.Shared.Next(0, 3);

Console.WriteLine($"Computer chose {computerChoice}");

if (playerChoice == computerChoice)
{
Console.WriteLine("It's a tie!");
}
else if (WinsAgainst[playerChoice] == computerChoice)
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine("You lose!");
}
}

static Choice? ParseChoice(string? input) =>
input?.ToLowerInvariant() switch
{
"1" => Choice.Rock,
"r" => Choice.Rock,
"rock" => Choice.Rock,
"2" => Choice.Paper,
"p" => Choice.Paper,
"paper" => Choice.Paper,
"3" => Choice.Scissors,
"s" => Choice.Scissors,
"scissors" => Choice.Scissors,
_ => null
};
}

enum Choice
{
Rock,
Paper,
Scissors
}
static class Program
{
private static readonly Dictionary<Choice, Choice> WinsAgainst =
new() { [Choice.Rock] = Choice.Scissors, [Choice.Paper] = Choice.Rock, [Choice.Scissors] = Choice.Paper, };

static void Main()
{
Console.WriteLine("Rock, Paper, Scissors! Enter your choice: ");
Choice playerChoice;
while (true)
{
var choice = ParseChoice(Console.ReadLine());
if (choice != null)
{
playerChoice = choice.Value;
break;
}

Console.WriteLine("Invalid choice. Try again.");
}

// we don't need to declare a new random instance every time, just use Random.Shared
var computerChoice = (Choice)Random.Shared.Next(0, 3);

Console.WriteLine($"Computer chose {computerChoice}");

if (playerChoice == computerChoice)
{
Console.WriteLine("It's a tie!");
}
else if (WinsAgainst[playerChoice] == computerChoice)
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine("You lose!");
}
}

static Choice? ParseChoice(string? input) =>
input?.ToLowerInvariant() switch
{
"1" => Choice.Rock,
"r" => Choice.Rock,
"rock" => Choice.Rock,
"2" => Choice.Paper,
"p" => Choice.Paper,
"paper" => Choice.Paper,
"3" => Choice.Scissors,
"s" => Choice.Scissors,
"scissors" => Choice.Scissors,
_ => null
};
}

enum Choice
{
Rock,
Paper,
Scissors
}
Zeksy
ZeksyOP•7mo ago
I see, I don't get most of this code maybe because I just started but will dive deep into it shortly :salute:
Pobiega
Pobiega•7mo ago
yeah thats fine, just wanted to show a less string-focused solution would look like
leowest
leowest•7mo ago
static Choice? ParseChoice(string? input) =>
input?.ToLowerInvariant() switch
{
"1" or "r" or "rock" => Choice.Rock,
"2" or "p" or "paper" => Choice.Paper,
"3" or "s" or "scissors" => Choice.Scissors,
_ => null
};
static Choice? ParseChoice(string? input) =>
input?.ToLowerInvariant() switch
{
"1" or "r" or "rock" => Choice.Rock,
"2" or "p" or "paper" => Choice.Paper,
"3" or "s" or "scissors" => Choice.Scissors,
_ => null
};
Pobiega
Pobiega•7mo ago
oh yeah 😄
Want results from more Discord servers?
Add your server