Rock, Paper, Scissor game - how to end when one wins three times?

前端 未结 3 423
悲哀的现实
悲哀的现实 2021-01-16 04:19

I am writing a Rock(Sten), Paper(Påse), Scissor(Sax) game, that plays against the computer. It works and all but I want to break the game when one off the two wins three tim

3条回答
  •  日久生厌
    2021-01-16 04:53

    Instead of trying to fix your code with the current methods I would suggest adding the following to make your code easier to follow:

    1: Use enums to give a clear meaning to numbers.

    public enum Choice
    {
        Rock,
        Paper,
        Scissor
    }
    
    public enum WinResult
    {
        Won,
        Tie,
        Lost
    }
    

    2: Add a method to ask input from user and return the result.

    private Choice GiveChoice()
    {
        // This is a label where we can jump to if the input was invalid.
        start:
    
        // Ask the question.
        Console.Clear();
        Console.WriteLine("Choose (0:Rock, 1:Paper, 2:Scissor):");
        string answer = Console.ReadLine();
        int result = -1;
    
        // Validate and re-ask if invalid.
        if (!int.TryParse(answer, out result) || (result < 0 && result > 2))
            goto start;
    
        return (Choice) result;
    }
    

    3: Add a method to compare 2 results from eachother.

    // Returns if v1 has won, tied or lost from v2. (Left to right)
    private WinResult CompareForWinner(Choice v1, Choice v2)
    {
        if (v1 == Choice.Paper)
        {
            if (v2 == Choice.Paper)
                return WinResult.Tie;
            if (v2 == Choice.Rock)
                return WinResult.Lost;
    
            return WinResult.Won;
        }
        if (v1 == Choice.Rock)
        {
            if (v2 == Choice.Paper)
                return WinResult.Lost;
            if (v2 == Choice.Rock)
                return WinResult.Tie;
    
            return WinResult.Won;
        }
    
        // v1 = Scissor.
        if (v2 == Choice.Paper)
            return WinResult.Won;
        if (v2 == Choice.Rock)
            return WinResult.Lost;
    
        return WinResult.Tie;
    }
    

    It's not a direct answer to your question. But I think it will help you solve it yourself.

提交回复
热议问题