4
\$\begingroup\$

I am a beginner programmer trying to go past the simple tutorials like Codecademy. I decided to make a rock paper scissors game to get some practice in making projects. Any feedback is welcome!

using System;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;

namespace ConsoleApp1
{
    class Program
    {
        static public int game()
        {
            int winner = 0;
            int input;
            Random random = new Random();
            //show options
            Console.WriteLine("1.Rock");
            Console.WriteLine("2.Paper");
            Console.WriteLine("3.Scissors");
            //get user input
            try
            {
                input = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                input = 4;
            }
            //pick random input for opponent
            int opponent = random.Next(3);
            Console.Clear();
            //logic and stuff
            if(input == 1)
            {
                if(opponent == 0)
                {
                    Console.WriteLine("Tie! The opponent picked rock.");
                    winner = 0;
                }
                else if(opponent == 1)
                {
                    Console.WriteLine("you lost! The opponent picked paper.");
                    winner = 1;
                }
                else if(opponent == 2)
                {
                    Console.WriteLine("you won! The opponent picked scissors.");
                    winner = 2;
                }

            }
            else if(input == 2)
            {
                if (opponent == 0)
                {
                    Console.WriteLine("you won! The opponent picked scissors.");
                    winner = 2;
                }
                else if (opponent == 1)
                {
                    Console.WriteLine("Tie! The opponent picked paper.");
                    winner = 0;
                }
                else if (opponent == 2)
                {
                    Console.WriteLine("you lost! The opponent picked scissors.");
                    winner = 1;
                }

            }
            else if(input == 3)
            {
                if (opponent == 0)
                {
                    Console.WriteLine("you lost! The opponent picked rock.");
                    winner = 1;
                }
                else if(opponent == 1)
                {
                    Console.WriteLine("you won! The opponent picked scissors.");
                    winner = 2;
                }
                else if(opponent == 2)
                {
                    Console.WriteLine("Tie! The opponent picked scissors.");
                    winner = 0;
                }

            }
            else
            {
                Console.WriteLine("Pick a Number between 1 and 3!");
                winner = 0;
            }
            //return score
            return winner;
        }
        static void Main(string[] args)
        {
            int playerScore = 0;
            int opponentScore = 0;
            bool keepPlaying = true;
            char i = 'y';
            Console.WriteLine("Welcome to Rock paper scissors!");
            
            while (keepPlaying)
            {
                int gameResult = game();
                
                if (gameResult == 1)
                {
                    opponentScore++;
                }
                else if (gameResult == 2)
                {
                    playerScore++;
                }
                else if(gameResult != 0)
                {
                    Console.WriteLine("Something went wrong!");
                }
                string s = String.Format("Your score:{0} Opponents score:{1}", playerScore, opponentScore);
                Console.WriteLine(s);
                Console.WriteLine("Do you want to keep playing? y/n");
                try
                {
                    i = Convert.ToChar(Console.ReadLine());
                }
                catch
                {
                    i = 'n';
                }
                if (i != 'y')
                {
                    keepPlaying = false;
                }
                
            }
        }
    }
}
```
\$\endgroup\$
1
  • \$\begingroup\$ I would suggest a look at this answer. It has some good points for you to consider. \$\endgroup\$
    – user33306
    Aug 2, 2020 at 3:46

2 Answers 2

1
\$\begingroup\$

You mix data and logic, this is bad seperarion and makes the code hard to maintain and refactor.

I would move the rules to a data structure and query it for who is winner. Here is an example i did for another stackexhange question.

class Program
{
    private enum Type
    {
        Rock = 0, 
        Paper = 1,
        Scissor = 2
    }

    private interface IPLayerInput
    {
        Type GetInput();
    }

    private class KeyboardPlayerInput : IPLayerInput
    {
        public Type GetInput()
        {
            return (Type)Enum.Parse(typeof(Type), Console.ReadLine() ?? string.Empty);
        }
    }

    private class AiPLayerInput : IPLayerInput
    {
        private readonly Type[] _values;
        private readonly Random _rand;

        public AiPLayerInput()
        {
            _values = Enum.GetValues(typeof(Type)).Cast<Type>().ToArray();
            _rand = new Random();
        }

        public Type GetInput()
        {
            return _values[_rand.Next(0, _values.Length)];
        }
    }

    private class Player
    {
        private readonly IPLayerInput _input;

        public Player(string name, IPLayerInput input)
        {
            _input = input;
            Name = name;
        }

        public int Score { get; set; }
        public string Name { get; }

        public void RequestNewHand()
        {
            CurrentHand = _input.GetInput();
        }

        public Type CurrentHand { get; private set; } 
    }

    static void Main()
    {
        var rules = new Type?[,] { 
            { null, Type.Paper, Type.Rock }, 
            { Type.Paper, null, Type.Scissor }, 
            { Type.Rock, Type.Scissor, null } };


        var players = new List<Player> {new Player("AI", new AiPLayerInput()), new Player("Hooman", new KeyboardPlayerInput())};

        Player winner = null;
        while (winner == null)
        {
            players.ForEach(p => p.RequestNewHand());
            foreach (var player in players)
            {
                var score = players.Count(p => p != player && rules[(int)player.CurrentHand, (int)p.CurrentHand] == player.CurrentHand);
                player.Score += score;
            }

            winner = players.SingleOrDefault(p => p.Score >= 3);
        }

        Console.WriteLine($"Winner is {winner.Name}");

    }
}
\$\endgroup\$
1
\$\begingroup\$

Here are a few links https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netcore-3.1 A newer method of parsing an Int32 in C#.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch a way to simplify your if statements.

Also, it isn't the best practice to put a lot of code into the main method. Try adding a public void static run() method and then calling that from the main method.

using System;
using System.Collections.Generic;
using System.Text;

namespace RockPaperScissors
{
    class Program
    {
        public static int playerScore = 0;
        public static int opponentScore = 0;

        static void Main(string[] args)
        {
            run();
        }

        public static void run()
        {
            bool? roundResult = null;
            bool playAgain = false;
            Random rng = new Random();
            int opponentNumber = rng.Next(1, 4);

            while (roundResult == null || playAgain)
            {
                Console.WriteLine("1.Rock\n2.Paper\n3.Scissors");
                Console.Write("Please Input A Number: ");

                Int32.TryParse(Console.ReadLine(), out int input);
                //Console.WriteLine(input);

                roundResult = compare(input, opponentNumber);
                if (roundResult == null)
                {
                    Console.WriteLine("\nRound Was A Tie. Try Again\n");
                    Console.WriteLine();
                }

                Console.WriteLine($"\nPlayer Score: {playerScore}\nOpponent Score: {opponentScore}\n");

                if (roundResult != null)
                {

                    bool validInput = false;
                    while (!validInput)
                    {
                        Console.Write("\nPlay Again? Y/N: ");
                        string playAgainInput = Console.ReadLine().ToLower();
                        switch (playAgainInput)
                        {
                            case "y":
                                playAgain = true;
                                validInput = true;
                                break;
                            case "n":
                                playAgain = false;
                                validInput = true;
                                break;
                            default:
                                Console.WriteLine("Invalid Input");
                                validInput = false;
                                break;
                        }
                    }
                }
            }



        }

        public static string getHandForm(int number)
        {
            string handForm = "";
            switch (number)
            {
                case 1:
                    handForm = "Rock";
                    break;
                case 2:
                    handForm = "Paper";
                    break;
                case 3:
                    handForm = "Scissors";
                    break;
                default:
                    Console.WriteLine("Invalid Number");
                    break;
            }

            return handForm;
        }

        public static bool? compare(int player, int opponent)
        {

            string playerHand = getHandForm(player);
            string opponentHand = getHandForm(opponent);
            //True equals Round Won, False equals Round Loss, Null equals round tie
            bool? roundBool = null;

            if (opponent != player)
            {
                switch (playerHand)
                {
                    case "Rock":
                        switch (opponentHand)
                        {
                            case "Scissors":
                                //Player Wins
                                roundBool = true;
                                break;
                            case "Paper":
                                //Player Loses
                                roundBool = false;
                                break;
                        }
                        break;
                    case "Scissors":
                        switch (opponentHand)
                        {
                            case "Rock":
                                //Player Loses
                                roundBool = false;
                                break;
                            case "Paper":
                                //Player Wins
                                roundBool = true;
                                break;
                        }
                        break;
                    case "Paper":
                        switch (opponentHand)
                        {
                            case "Rock":
                                //Player Wins
                                roundBool = true;
                                break;
                            case "Scissors":
                                //Player Loses
                                roundBool = false;
                                break;
                        }
                        break;
                }
            }

            if (roundBool == true)
            {
                Console.WriteLine($"Player Wins! Opponent Choose: {opponentHand} You Choose: {playerHand}");
                playerScore++;
            }
            else if (roundBool == false)
            {
                Console.WriteLine($"Opponent Wins! Opponent Choose: {opponentHand} You Choose: {playerHand}");
                opponentScore++;
            }

            return roundBool;
        }

    }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Review! It's a nice first answer, but links can rot. You can leave them, but also please summarize the essential points in the text of your answer. \$\endgroup\$
    – Edward
    Aug 2, 2020 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.