Click here to Skip to main content
15,885,904 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi so I have completed a rock paper scissors game a and these are the winning rules


<pre lang="ASP.NET"><pre>

<pre>@inject Choices choices 

<div class="container">
    <div class="row mt-3">
        <div class="col-6 text-center text-uppercase"><h1>You : @playerScore</h1></div>
        <div class="col-6 text-center text-uppercase"><h1>Computer :@computerScore</h1></div>
    </div>
    <div class="row mt-3" style="height:200px;">
        <div class="col-6 text-center choosen-image">
            @playerChoiceImage
        </div>
        <div class="col-6 text-center choosen-image">
            @computerChoiceImage
        </div>
    </div>
    <div class="text-center mt-3" style="height:40px;">
        <h3>@message</h3>
    </div>
    <div class="row mt-3">
        @foreach(var i in Enumerable.Range(0,3))
        {
            var choice = i;
            <div class="col-4 text-center image-to-choose" @onclick="(()=> OnPlayerMadeChoice(choice))">
                @choices[i]
            </div>
        }
    </div>
    <div class="text-center mt-5">
        <button class="btn btn-primary" @onclick="Reset">Reset</button>
    </div>
</div>




C#
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RockPaperScissors.Components
{
    public partial class Game
    {
        private int playerScore;
        private int computerScore;
        private string playerChoiceImage;
        private string computerChoiceImage;
        private string message;

        private readonly Action<int> playerMadeChoice;
        private readonly Action<int> computerMadeChoice;
        private readonly Action<int, int> bothMadeChoice;

        private readonly Random random;

        public Game()
        {
            random = new Random();

            playerMadeChoice = (playerChoice) => 
            {
                playerChoiceImage = choices[playerChoice];
                computerMadeChoice(playerChoice);
            };

            computerMadeChoice = (playerChoice) => 
            {
                var computerChoice = random.Next(2);
                computerChoiceImage = choices[computerChoice];
                StateHasChanged();

                bothMadeChoice(playerChoice, computerChoice);
            };

            bothMadeChoice = (playerChoice, computerChoice) => 
            {
                var (_, _, playerWon, computerWon, message) = WinningRules[playerChoice, computerChoice];
                this.message = message;
                playerScore = playerWon ? ++playerScore : playerScore;
                computerScore = computerWon ? ++computerScore : computerScore;

                StateHasChanged();
            };
        }

        protected override void OnInitialized() => SetDefaultMessage();
        private void SetDefaultMessage() => message = "Make a choice";
        private void OnPlayerMadeChoice(int playerChoice) => playerMadeChoice(playerChoice);

        private void Reset()
        {
            SetDefaultMessage();
            playerScore = computerScore = 0;
            playerChoiceImage = computerChoiceImage = string.Empty;
        }

        [Inject]
        public WinningRules WinningRules { get; set; }
    }
}


C#
namespace RockPaperScissors.Components
{
    public class Choices
    {
        private readonly Dictionary<int, string=""> choices =
            new Dictionary<int, string=""> 
            {
                {0, "✊" },
                {1, "✋" },
                {2, "✌️" }
            };

        public string this[int choiceKey] => choices[choiceKey];
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RockPaperScissors.Components
{
    public class WinningRules
    {
        private readonly IList<(int, int, bool, bool, string)> winningRules =
            new List<(int, int, bool, bool, string)>
            {
                (0,0, false, false, "You both select Rock, it's tie"),
                (0, 1, false, true, "Paper beats Rock, you lose"),
                (0, 2, true, false, "Rock beats Scissors, you win"),
                (1, 0, true, false, "Paper beats Rock, you win"),
                (1, 1, false, false, "You both select Paper, it's tie"),
                (1, 2, false, true, "Scissors beats Paper, you lose"),
                (2, 0, false, true, "Rock beats Scissors, you lose"),
                (2, 1, true, false, "Scissors beats Paper, you win"),
                (2, 2, false, false,"You both select Scissors, it's tie")
            };

        public (int, int, bool, bool, string) this[int playerChoice, int computerChoice]
            => winningRules.Single(w => w.Item1 == playerChoice && w.Item2 == computerChoice);
    }
}






What I am looking to add is to allow the game to pick a winner after every 3 rounds, whoever wins 2 out of 3 matches gets to be the winner. Additionally, I am also hoping to add a feature where the game would inform users which were the most used moves to win the game.

What I have tried:

I have tried to look for ways of implementing the idea however I am not sure how I should. I have followed along with the tutorial and found the GitHub repository if the full project is needed

GitHub - estyval/RockPaperScissors: Rock Paper Scissors game with BlazorWebAssembly[^]
Posted
Updated 29-Jul-21 18:44pm
v4
Comments
CHill60 29-Jul-21 8:34am    
I can't follow that link just now, so why have you not shared the code that actually runs the game. That way we might be able to help you with the loop for the 3 rounds and persisting the score
CodeRed001 29-Jul-21 11:45am    
how should I share the code sorry, should I copy and paste them here?
CHill60 29-Jul-21 12:15pm    
Yes - there is an "Improve question" link near the bottom of your post (if it is not visible, hover your mouse over your question)
You can paste the relevant code into the What I have tried section.
Don't delete the link you already have, I'm sure other members will be able to access it - it's just some external links are blocked on some work laptops
CodeRed001 30-Jul-21 10:24am    
hi, the author of the project has actually sent me some guides however I am still stuck - as using while if statements and counter and still noting getting the result i wanted.

this is the file

namespace RockPaperScissorsGame.Components
{


///

/// this class will track the number of rounds/matched that has been played
/// when the number will reach the max value (for example :3)
/// an event will be raised
///



public class RoundTracker
{
private readonly int max = 3;
private int current = 0;

private void RestartRound() => current = 0;


public void Increase()
{
current += 1;
if (current == max)
OnRoundLimitReached(EventArgs.Empty);
}
protected virtual void OnRoundLimitReached(EventArgs e)
{
RestartRound();
EventHandler handler = RoundLimitReached;
handler?.Invoke(this, e);
}

public event EventHandler RoundLimitReached;

}
}


public Game()


{
random = new Random();
roundTracker = new RoundTracker();

// Register to this event to get notify when the number of round/match will reach the limit
roundTracker.RoundLimitReached += (o, arg) =>
{
// Number of round/match has been reached
//TODO: add any logic you want here

};
CodeRed001 29-Jul-21 13:55pm    
Hi, just added the most relevant code, hope this will help to understand the project a bit better, sorry if the structure is not the best, very new to the system

1 solution

What if there are three draws in a row: repeat the game until there at least one win ?

I suggest you isolate the logic of determining the winner; I use this example with my students, trying to teach the concept of separation of concerns:
namespace YourNameSpace
{
    public enum RPSChoice
    {
        Rock,
        Paper,
        Scissors
    }

    public enum RPSOutcome
    {
        Tie,
        User1Win,
        User2Win
    }

    // Rock wins against scissors.
    // Scissors win against paper.
    // Paper wins against rock.

    public static class RPS
    {
        public static RPSOutcome RPSPlay(RPSChoice u1choice, RPSChoice u2choice)
        {
            if (u1choice == u2choice) return RPSOutcome.Tie;

            switch (u1choice)
            {
                case RPSChoice.Rock:
                    switch (u2choice)
                    {
                        case RPSChoice.Scissors:
                            return RPSOutcome.User1Win;
                        default: // paper: user 2 wins
                            return RPSOutcome.User2Win;
                    }

                // left for you to write ...

                case RPSChoice.Paper:
                    switch (u2choice)
                    {
                        // ?
                    }

                default: // RPSChoice.Scissors:
                    switch (u2choice)
                    {
                        // ?
                    }
            }
        }
    }
}
To verify your logic is correct:
foreach(RPSChoice choice1 in Enum.GetValues(typeof(RPSChoice)))
{
    foreach (RPSChoice choice2 in Enum.GetValues(typeof(RPSChoice)))
    {
        Console.WriteLine($"user1: {choice1} user2: {choice2} result = {RPS.RPSPlay(choice1, choice2)}");
    }
}
You should see this in the Output window:
user1: Rock user2: Rock result = Tie
user1: Rock user2: Paper result = User2Win
user1: Rock user2: Scissors result = User1Win
user1: Paper user2: Rock result = User1Win
user1: Paper user2: Paper result = Tie
user1: Paper user2: Scissors result = User2Win
user1: Scissors user2: Rock result = User2Win
user1: Scissors user2: Paper result = User1Win
user1: Scissors user2: Scissors result = Tie
 
Share this answer
 
v2
Comments
CodeRed001 30-Jul-21 10:21am    
hi, the author of the project has actually sent me some guides however I am still stuck - as using while if statements and counter and still noting getting the result i wanted.

this is the file

namespace RockPaperScissorsGame.Components
{


///
/// this class will track the number of rounds/matched that has been played
/// when the number will reach the max value (for example :3)
/// an event will be raised
///



public class RoundTracker
{
private readonly int max = 3;
private int current = 0;

private void RestartRound() => current = 0;


public void Increase()
{
current += 1;
if (current == max)
OnRoundLimitReached(EventArgs.Empty);
}
protected virtual void OnRoundLimitReached(EventArgs e)
{
RestartRound();
EventHandler handler = RoundLimitReached;
handler?.Invoke(this, e);
}

public event EventHandler RoundLimitReached;

}
}


public Game()


{
random = new Random();
roundTracker = new RoundTracker();

// Register to this event to get notify when the number of round/match will reach the limit
roundTracker.RoundLimitReached += (o, arg) =>
{
// Number of round/match has been reached
//TODO: add any logic you want here

};
BillWoodruff 30-Jul-21 11:20am    
imho, you need to step back from fiddling with code you don't understand and focus on making a clear outline pf how your games proceeds.

"Divide and conquer" is a classic strategy for programmers: you break a complex task into smaller tasks.

Isolate the functional units of:

1. input: getting players choices

2.gane olay : what the codemi show you here does

3.repeating game play some number of times and deciding on a winner

4.data storage

5.reporting outcomes

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900