Tech Off Post

Single Post Permalink

View Thread: Yet another C# dice question.
  • User profile image
    Pop Catalin Sever

    here's one way to do it :

    using System;
    using System.Runtime.InteropServices;
    using System.Security.Principal;
    using System.Security.Permissions;
    using System.Windows.Forms;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection.Emit;
    using System.Reflection;

    namespace DiceGame {
        class Program {
            static void Main(string[] args) {

                // Create 2 arrays of integers to hold player dice rolls
                int[] player1 = new int[6];
                int[] player2 = new int[6];

                // Create a random number generator
                Random randomGenerator = new Random();

                // Roll dice 5 times for each player
                for (int i = 0; i < 5; i++) {
                    // Increment the array value at the position generated by the dice roll
                    // for example a dice roll of 3 increments the array at posion 3
                    int diceRoll = 0;
                    diceRoll = randomGenerator.Next(6);
                    player1[diceRoll]++;
                    //Write Player 1  dice roll
                    Console.WriteLine("Player 1 rolled: {0}", diceRoll + 1);
                    diceRoll = randomGenerator.Next(6);
                    player2[diceRoll]++;
                    //Write Player 2  dice roll
                    Console.WriteLine("Player 2 rolled: {0}", diceRoll + 1);
                }

                // Find max number of rolls with the same value
                // we effectively search the position in the arrays holding the max value
                int maxPlayer1 = 0, maxPlayer2 = 0;
                for (int i = 1; i < 5; i++) {
                    if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
                    if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
                }

                // Write results to console;
                if (player1[maxPlayer1] > player2[maxPlayer2])
                    Console.WriteLine("Player 1 won with {0} rolls of {1}", player1[maxPlayer1], maxPlayer1 + 1);
                else
                if (player2[maxPlayer2] > player1[maxPlayer1])
                    Console.WriteLine("Player 2 won with {0} rolls of {1}", player2[maxPlayer2], maxPlayer2 + 1);
                else
                    Console.WriteLine("Tie");
            }
        }
    }


    As an exercise  try to refactor the code to use functions that take a player numeber to do the work.