C# Homework Dice Game - c#

Im taking and Into c# course and Im having alot of fun learning, however Im getting stuck on this one assignment--I have to simulate rolling a 6 sided dice/die 500 times (user must input the number of rolls) while displaying the frequency of each side(1-6) and % roll. In addition I cant use arrays.
So To start what I did was Initiate a bool to loop my code because I have to ask the user if they want to roll again. Then I created a variable for dice1 and set it to a Random number between 1-6. I tried setting a variable to a console readline that was equal to the dice1 to have the user enter the number. This is pretty much where I get stuck and cant move forward.
I know many of you are much more knowledgeable than I am so It'd be great If anyone could give me some advice.
Here's what I have so far:
static void Main(string[] args)
{
//Initiate Looping Seqence
bool choice = true;
while (choice)
{
//Display Introduction and Instructions
Console.WriteLine("Welcome To The Dice Game!");
Console.WriteLine("This Program will simulate rolling a die and will track");
Console.WriteLine("the Frequency each value is rolled Then Display a Session Summary");
Console.WriteLine("Press any key to continue.....");
Console.ReadKey();
Console.Clear();
Console.WriteLine("How many times would you like to roll the die?");
Random randomNum = new Random();
int dice1;
dice1 = randomNum.Next(1, 7);
int choice2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine(dice1);
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Console.WriteLine("Would you Like to Run This Program Again?");
Console.WriteLine("Type \"yes\" to re-run or Type \"no\" to exit?");
Console.ReadKey();
string option;
option = Console.ReadLine();
}
}
// public static double RollDice()
//{
// was not sure if to create a dice roll method
//}
}
}

Have a break, take my code ヽ(^o^)丿
class Program {
#region lambda shortcuts
static Action<object> Warn = m => {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(m);
};
static Action<object> Info = m => {
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(m);
};
static Action<object> WriteQuery = m => {
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(m);
};
static Action BreakLine = Console.WriteLine;
#endregion
static void Main(string[] args) {
Console.Title = "The Dice Game";
while(true) {
bool #continue = RunDiceGame();
if(!#continue) {
break;
}
Console.Clear();
}
}
static bool RunDiceGame() {
//Display Introduction and Instructions
Info("Welcome To The Dice Game!");
Info("This Program will simulate rolling a dice and keeps track of the results");
BreakLine();
WriteQuery("Dice roll count: ");
int rollCount = ReadInt32();
WriteQuery("Random number generator seed: ");
Random rng = new Random(ReadInt32());
BreakLine();
BreakLine();
//map dice value to dice count
var diceValues = new Dictionary<int, int>((int)rollCount);
for(int i = 0; i < 6; i++) {
diceValues.Add(i, 0);
}
//roll dice
for(int i = 0; i < rollCount; i++) {
int diceValue = rng.Next(6); //roll 0..5
diceValues[diceValue]++;
}
//print results
for(int i = 0; i < 6; i++) {
int valueRollAbsolute = diceValues[i];
double valueRollCountRelative = valueRollAbsolute / (double) rollCount;
Info(string.Format("Value: {0}\tCount: {1:0,0}\tPercentage: {2:0%}", i + 1, valueRollAbsolute, valueRollCountRelative));
}
BreakLine();
BreakLine();
WriteQuery("Type 'yes' to restart, 'no' to exit.");
BreakLine();
return ReadYesNo();
}
#region console read methods
static int ReadInt32() {
while(true) {
string input = Console.ReadLine();
try {
return Convert.ToInt32(input);
} catch(FormatException) {
Warn("Not a number: " + input);
}
}
}
static bool ReadYesNo() {
while(true) {
string option = Console.ReadLine();
switch(option.ToLowerInvariant()) {
case "yes":
return true;
case "no":
return false;
default:
Warn("Invalid option: " + option);
break;
}
}
}
#endregion
}

Here is some code to simulate the rolls & get how many times a number popped up
int rollAmount = 500;
int dice;
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Random random = new Random();
for(int i = 0; i <= rollAmount; i++){
dice = random.next(1,7);
Console.Writeline("Roll " + i + ": " + dice.ToString());
if(dice == 1) s1++;
else if(dice == 2) s2++;
else if(dice == 3) s3++;
...
}
Console.Writeline("1 Percentage: " + ((s1 / rollAmount) * 100) + "%");
Console.Writeline("2 Percentage: " + ((s2 / rollAmount) * 100) + "%");
Console.Writeline("3 Percentage: " + ((s3 / rollAmount) * 100) + "%");
...
Console.Writeline("Done");

Related

How to make a game move continuously

I'm trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). I've got halfway through, however, when a player makes a move, the board will simply reset to normal for the next move. Any thoughts on how I can make another move to the board and it takes into account the previous move?
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static string firstMove;
static bool gameStatus = true;
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
PlayingGame();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n"+ reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void InitialBoardSetUp()
{
Console.WriteLine(underline + "This is how the board is formatted:\n" + reset);
Thread.Sleep(750);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
Console.Write("███ ");
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 8);
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 8);
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, CompStackSelection);
Thread.Sleep(1000);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == CompStackSelection && i <= CompRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.WriteLine();
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == PlayerStackSelection && i <= PlayerRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayingGame()
{
int gameNumber = 1;
while (gameStatus == true)
{
Console.WriteLine(underline + "Round " + gameNumber+ ":\n" + reset);
WhoGoesFirst();
if (firstMove == "Computer")
{
ComputerMove();
}
else
{
PlayerMove();
}
gameNumber += 1;
playAgain();
}
}
static void playAgain()
{
Console.Write("Do you wish to play again? (Y/N): ");
char playAgain = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
if (playAgain == 'Y')
{
gameStatus = true;
}
else if (playAgain == 'N')
{
gameStatus = false;
}
}
In PlayingGame() you need to create a game loop.
static void PlayingGame()
{
int turn = // randomly choose 0 or 1 (whose turn is it)
bool finished = false;
while(!finished)
{
if(turn==0)
{
ComputerMove();
} else {
PlayerMove();
}
finished = CheckForEndOfGame();
turn = 1 - turn;
}
}
I do strongly suggest to create a Game class that handles the logic of the game and separate the UI (like messages etc) from the game mechanics. This is C# after all, and object oriented approaches are strongly encouraged.
You need to keep track of that game board and whose turn it is and what has been played in this Game class and display on the screen things based on the values (the state) of the game.

breaks while loop when all die rolls the same number

using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}

C# - Keeping total number of correct guesses inside a variable

Beginner to programming & have been assigned a heads or tails coin flip project.
I've figured out how to make it randomly generate the number of requested flips and print out the answers. However, I'm supposed to have it add up how many times the user's input came up into the correctCount variable and I can't find anywhere how to do it. I've tried searching on here and different sites from searching throughout Google. I assume I need to take their string input and convert it somehow, like if result == string, then correctCount + 1 basically, but can't figure out how to make that happen since you can't do that with int & string. Any info or hints would be very helpful - thank you!
class Coin
{
static void Main(string[] args)
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");```
As PMF mentioned, you have to not only receive user choice, but also analyse it.
A simple comparison should be more that enough here, although you might want to add some validation to user input.
static void Main(string[] args)
// UserInput
{
int choice; //variable for parsed user choice
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
if(headsOrTailsGuess.ToLower().Trim() == "heads"){ //here you look if its heads
choice = 0;
}
else{ //we can write additional if here to avoid other options from counting as tails
choice = 1;
}
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
if(result == choice){ //comparing result to parsed choice and incrementing the counter
correctCount++;
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");
}
Here's another way to do it using Linq.
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine();
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
List<string> resultList = new List<string>();
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
resultList.Add(result == 1? "Heads!" : "Tails!");
}
var guessCount = resultList.Where(a=>a.ToUpper().Contains(headsOrTailsGuess.ToUpper())).Count();
resultList.ForEach( a=> Console.WriteLine(a));
Console.WriteLine("Your guess, " + headsOrTailsGuess + " came up " + guessCount + " time(s).");
Console.WriteLine(headsOrTailsGuess);
}
}
}
using System;
Console.WriteLine("Guess which will have more: heads or tails?");
var headsChosen = false;
var input = string.Empty;
do
{
input = Console.ReadLine();
headsChosen = input.ToLower() == "heads";
} while (input.ToLower() != "heads" && input.ToLower() != "tails");
Console.WriteLine("How many times shall we flip the coin?");
var flips = 0;
do
{
} while (!int.TryParse(Console.ReadLine(), out flips));
var rnd = new Random();
var heads = 0;
var tails = 0;
for (int i = 0; i < flips; i++)
{
if (rnd.Next(0, 2) == 0)
{
Console.WriteLine("Heads!");
heads++;
}
else
{
Console.WriteLine("Tails!");
tails++;
}
}
var userGuessed = (headsChosen && heads > tails) || (!headsChosen && tails > heads);
Console.WriteLine($"You {(userGuessed ? "guess" : "loose")}!");

Need help creating console app that outputs percent response for a rating on a survey 1-5 (whole number)

Working on an assignment where i need to accomplish the following: On a survey a question asks the surveyed person to rate something from 1-5 (whole number). The end user of your program iinputs the answers for that question on an unknown number of surveys. Write a program that allows this and outputs the percent response for each value (1, 2, 3, 4, and 5).
I did a previous Console app with a loop to collect an average and I am unsure how to collect a percent response on 5 different possible inputs.
Below is my previous code.
namespace WhileLoopsMean
public class MeanProgram
static void Main(string[] args)
{
long test, sum, loop, count;
double avg;
Console.Write("How many tests? ");
count = long.Parse(Console.ReadLine());
sum = 0;
loop = 1;
while (loop <= count)
{
Console.Write("enter score " + loop + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
loop = loop + 1;
}
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.WriteLine("\n\nenter a score of -100 to end\n");
count = 1;
sum = 0;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
while (test != -100)
{
count = count + 1;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
if (test != -100)
{
sum = sum + test;
}
else { }
}
count = count - 1;
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.ReadKey();
class Program {
static void Main(string[] args) {
string input = "";
List<List<int>> answers = new List<List<int>>();
int questionsCount = ReadInt32("The number of questions: ");
for (int i = 0; i < questionsCount; i++) {
answers.Add(new List<int>());
}
while (input == "" || input == "y") {
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
a.Add(ReadInt32($"Question [{i}]: "));
}
input = Read("Continue (y/n)? ").ToLower();
}
WriteLine("End of input!");
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
Write($"Average for question[{i}]: {a.Average()}\n");
}
ReadKey();
}
static string Read (string a) {
Write(a);
return ReadLine();
}
static int ReadInt32 (string a = "") {
Write(a);
return ToInt32(ReadLine());
}
}
Try this out. You can customize the questions. And note that to use Write() and WriteLine(), you should add
using static System.Console;
at the top, in the references of the project.

Console (Input string was not in correct format)

Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}

Categories