How to loop this? - c#

Im having trouble learning how to loop, and Im stuck on how to do this. Basically I was asked to program that rolls a 6 sided die and it'll ask you how many times you want to roll it. Based on how many times you roll, it will out put a table of how many times it landed on each side. This is what I have so far.
using System;
namespace Dice
{
class Program
{
static void Main(string[] args)
{
bool continueRunning = true;
int sessionNumber = 1;
DisplayInstructions();
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
aDice.RollDice();
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}
}
public static bool getYorN(string question)
{
bool validInput = false;
while (!validInput)
{
Console.WriteLine("{0}", question);
Console.WriteLine("Enter 'yes' or 'no' to continue...");
string userResponse = Console.ReadLine().ToLower();
if (userResponse == "yes" || userResponse == "no")
{
validInput = true;
switch (userResponse)
{
case "yes":
return true;
case "no":
return false;
default:
return false;
}
}
else
{
Console.Clear();
Console.WriteLine("You've entered an invalid term");
}
}
return false;
}
public static void DisplayInstructions()
{
Console.WriteLine("Welcome to the Dice Game!!");
Console.WriteLine("\n\n\nThis program will simulate rolling a die and will track the frequency \neach value is rolled.");
Console.WriteLine("\n\n\nAfter rolling the die, the program will output a summary table for the session.");
Console.WriteLine("\n\n\nPlease press any key to continue.");
Console.ReadKey();
Console.Clear();
}
public static string getInfo(string what)
{
Console.WriteLine(what);
return Console.ReadLine();
}
}
}
The class I have in this is
using System;
namespace TripCalcApp
{
class Dice
{
private int side1 = 0, side2 = 0, side3 = 0, side4 = 0, side5 = 0, side6 = 0;
Random randNum = new Random();
public Dice()
{
}
public int Side1
{
get { return side1; }
set { side1 = value; }
}
public int Side2
{
get { return side2; }
set { side2 = value; }
}
public int Side3
{
get { return side3; }
set { side3 = value; }
}
public int Side4
{
get { return side4; }
set { side4 = value; }
}
public int Side5
{
get { return side5; }
set { side5 = value; }
}
public int Side6
{
get { return side6; }
set { side6 = value; }
}
public void RollDice()
//RollDice = randNum.Next(1, 7)
{
switch (randNum.Next(1, 7))
{
case 1: side1++;
break;
case 2: side2++;
break;
case 3: side3++;
break;
case 4: side4++;
break;
case 5: side5++;
break;
case 6: side6++;
break;
}
}
public override string ToString()
{
return " Freq. Rolls " +
"________________________________________" +
"\nSide 1 of Die rolled :" + side1 +
"\nSide 2 of Die rolled :" + side2 +
"\nSide 3 of Die rolled :" + side3 +
"\nSide 4 of Die rolled :" + side4 +
"\nSide 5 of Die rolled :" + side5 +
"\nSide 6 of Die rolled :" + side6 +
"\n";
}
}
}
I had an idea on how to do loop it but Im still unsure. I thought of something like this but it doesnt work and I was hoping you guys could help me!!
int howMany = int.Parse(getInfo("How many times would you like to roll the die?"));
do
{
Dice aDice = new Dice();
for (int counter = howMany; counter > 0; counter--)
{
aDice.RollDice();
}
while (howMany < 0)
{
Console.WriteLine(aDice);
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
playAgain = getYorN("Would you like to play again?");
sessionNumber++;
}

All you need to do is call aDice.RollDice method howMany times:
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
for(int i = 0; i < howMany; i++)
{
aDice.RollDice();
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}

Related

How to re-write menu using DRY

I'm doing a school project and I really feel that I can acomplish what I want in my code, however I feel like i -always- repeat my code.
I have tried to put the switch cases into methods but haven't had any success though to out of scope.
I am beginner so sorry for the eyesore code!
However, if anyone have any tips for using methods or something else so I can clean up my code a little better.
So here is a bit of my code, this is the beginning branch of my menu.
I have translated the code roughly to english.
So this is a sub menu in the main method.
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
switch (menuInput03)
{
/////WATER PLANT////
case 1:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
if (plant[0] < 21)
{
for (int i = plant[0]; i < 21; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
Console.WriteLine("\nWatering plant..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has been watered!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
else
{
break;
}
Console.Clear();
break;
case 2:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
if (plant[0] > 19)
{
for (int i = plant[0]; i < 51; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
i++;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
Console.WriteLine("\nRipping out weeds..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has gotten it's weed removed!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
Console.Clear();
break;`
I came up with the following; don't just copy-paste for school project without understanding what is going on. If some things are not clear do not hesitate to ask follow-up questions.
public record Action
{
public string Title { get; }
public int RequiredHealth { get; }
public string ActionMessage { get; }
public string CompletedMessage { get; }
private Action(string title, int requiredHealth, string actionMessage, string completedMessage)
{
Title = title;
RequiredHealth = requiredHealth;
ActionMessage = actionMessage;
CompletedMessage = completedMessage;
}
public static Action WaterPlant { get; } = new Action(
title: "Press SPACEBAR several times to water plant!",
requiredHealth: 20,
actionMessage: "Watering plant..",
completedMessage: "Your plant has been watered!");
public static Action RemoveWeed { get; } = new Action(
title: "Press SPACEBAR several times to remove weed!",
requiredHealth: 50,
actionMessage: "Ripping out weeds..",
completedMessage: "Your plant has gotten it's weed removed!");
}
static void Main()
{
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
for (var menuInput03 = 1; menuInput03 <= 2; menuInput03++)
{
var action = menuInput03 switch
{
1 => Action.WaterPlant,
2 => Action.RemoveWeed,
};
Console.Clear();
Console.WriteLine(action.Title);
while (plant[0] < action.RequiredHealth)
{
if (Console.ReadKey().Key != ConsoleKey.Spacebar)
{
Console.Write("\b \b");
continue;
}
plant[0]++;
Console.Clear();
Console.WriteLine(action.Title);
Console.WriteLine(action.ActionMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
}
Console.Clear();
Console.WriteLine(action.CompletedMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
Console.WriteLine("To continue press ENTER.");
while (Console.ReadKey().Key != ConsoleKey.Enter)
{
Console.Write("\b \b");
}
Console.Clear();
}
}

methods program not working of guessing a number

I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}

Dividing by Zero Exeption, knowing why it gets thrown, not knowing how to fix it

For better understanding I will first post my Program Class.
Program.cs
namespace BeginnersGuidToLifting
{
class Program
{
public static readonly int width = 85;
public static readonly int height = 35;
public static readonly User user = new User();
public static readonly Goal goal = new Goal();
public static Calories calories = new Calories();
public static Nutrition nutrition = new Nutrition();
public static Menu menu = new Menu();
static void InitUser()
{
Console.WriteLine("\n### About You ###\n");
user.Name = Question.AskString("Name: ");
user.Age = Question.AskInt("Age: ");
user.Gender = Question.AskString("Gender(m/f): ");
user.Height = Question.AskInt("Height(cm): ");
user.Weight = Question.AskInt("Weight(kg): ");
}
static void InitGoals()
{
Console.WriteLine("\n### What are your Goals ### \n");
goal.GainWeight();
goal.LoseWeight();
goal.GetStronger();
goal.GetLeaner();
goal.StayFit();
goal.Hypertrophy();
Console.Write("Answer: ");
var input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.D1:
goal.GoalStatusGainWeight = true;
goal.GoalMessage = "Your Goal is to Gain Weight";
break;
case ConsoleKey.D2:
goal.GoalStatusLoseWeight = true;
goal.GoalMessage = "Your Goal is to Lose weight";
break;
case ConsoleKey.D3:
goal.GoalStatusGetStronger = true;
goal.GoalMessage = "Your Goal is to get Stronger";
break;
case ConsoleKey.D4:
goal.GoalStatusGetLeaner = true;
goal.GoalMessage = "Your Goal is to get Leaner";
break;
case ConsoleKey.D5:
goal.GoalStatusStayFit = true;
goal.GoalMessage = "Your Goal is to Stay Fit";
break;
case ConsoleKey.D6:
goal.GoalStatusHypertrophy = true;
goal.GoalMessage = "Your Goal is Hypertrophy";
break;
default:
Console.WriteLine("Error");
break;
}
}
static void InitMenu()
{
menu.ShowMenu();
menu.Discalmer = false;
//menu.Disclamer();
}
static void BmiResult()
{
var bodyType = user.GetBodyType();
if (bodyType == User.BodyType.ReallyUnderweight)
{
Console.WriteLine("Really Underweigt");
}
else if (bodyType == User.BodyType.Underweight)
{
Console.WriteLine("Underweight");
}
else if (bodyType == User.BodyType.CloseToUnderwight)
{
Console.WriteLine("Close to Underweight");
}
else if (bodyType == User.BodyType.Healthy)
{
Console.WriteLine("at a Healthy Weight");
}
else if (bodyType == User.BodyType.Overweight)
{
Console.WriteLine("Overweight");
}
else if (bodyType == User.BodyType.Obese)
{
Console.WriteLine("Obese");
}
else if (bodyType == User.BodyType.SeverlyObese)
{
Console.WriteLine("Serverley Obese");
}
else if (bodyType == User.BodyType.MorbidlyObese)
{
Console.WriteLine("Morbidly Obese");
}
}
static void Main(string[] args)
{
Console.Title = "Beginers Guide To Lifting";
Console.SetWindowSize(width, height);
Console.SetBufferSize(width, height);
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
//Status So Far
Console.WriteLine("\n### Your Stats ### \n");
Console.WriteLine("Name: {0} \nAge: {1} \nHeight: {2} \nWeight: {3}", user.Name, user.Age, user.Height, user.Weight);
Console.WriteLine("Goal: {0}", goal.GoalMessage);
BmiResult();
Console.Write("\nContinue(y/n) to The Programm?: ");
if (Console.ReadLine() == "y")
{
Console.Clear();
}
//Gain Weight Goal
//Introduce 5x5
var exercise = new FiveByFive();
exercise.printIntroduction();
//Show Exercises
exercise.printWorkoutWeek1();
exercise.printWorkoutWeek2();
//Show Nutrition
if (goal.GoalStatusGainWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.GainCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.GainCaloriesFemale(user);
break;
}
}
//Lose Weight
if (goal.GoalStatusLoseWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.LoseCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.LoseCaloriesFemale(user);
break;
}
}
}
}
}
The Problem is in my Main Method.
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
When I press one, it should happen what it shows.
Init User and Init User Goals.
How ever when i press 2 it brings me to the User.cs class,
where i am doing the Math for the Users BMI.
I dont really understand why it would do that when pressing 2, because all i want to display is "Press 2" Or later to be added A disclamer.
The Exeption
System.DivideByZeroException: 'Attempted to divide by zero.'
Is thrown because it tries to divde 0 with 0 and that is because there is no input from the user yet. Because all i would like to do by pressing 2 is display another window with some text. And that is is.
I really dont understand why it jumps to the User class.
Here is User.cs for better understanding.
namespace BeginnersGuidToLifting
{
class User
{
public enum BodyType
{
ReallyUnderweight,
Underweight,
CloseToUnderwight,
Healthy,
Overweight,
Obese,
SeverlyObese,
MorbidlyObese
}
public string Name;
//private string _gender;
public string Gender;
private int _weight;
private int _height;
private int _age;
public int Age
{
get => _age;
set
{
if (value >= 0)
{
_age = value;
}
}
}
public int Weight
{
get => _weight;
set
{
if (value >= 0)
{
_weight = value;
}
}
}
public int Height
{
get => _height;
set
{
if (value >= 0)
{
_height = value;
}
}
}
//TODO
//public string Gender
//{
// get => _gender;
// set
// {
// if (value == "female" || value == "f" || value == "male" || value == "m" )
// _gender = value;
// else
// {
// Console.WriteLine("Value Wrong");
// }
// }
//}
public int GetBmi()
{
Console.WriteLine("Weight:"+Weight);
//var bmi = Math.Round((Weight / Math.Pow(Height, 2)) * 10000);
int bmi = Weight / (Height * Height) * 10000;
Console.WriteLine("Your Body Mass Index: " + bmi);
Console.Write("That Means That you are: ");
return bmi;
}
public BodyType GetBodyType()
{
int bmi = GetBmi();
if (bmi < 16)
return BodyType.ReallyUnderweight;
else if (bmi >= 16 && bmi <= 17)
return BodyType.Underweight;
else if (bmi >= 17 && bmi <= 18.5)
return BodyType.CloseToUnderwight;
else if (bmi >= 18.5 && bmi <= 25)
return BodyType.Healthy;
else if (bmi >= 25 && bmi <= 30)
return BodyType.Overweight;
else if (bmi >= 30 && bmi <= 35)
return BodyType.Obese;
else if (bmi >= 35 && bmi <= 40)
return BodyType.SeverlyObese;
return BodyType.MorbidlyObese;
}
}
}
Summary
A switch command calls 2 actions when number 1 and number 2 is
pressed on the keyboard.
When pressing 1 everything works fine and
does what it should.
When pressing 2 it tries to do the math for
something there is no input yet, Because input is only asked when
pressing 1.
Thank you in advance for taking the time to read this.
Any input is welcome. I hope everything is clear to understand.
After you press '2' and it exits the switch, it calls BmiResult(), which calls methods in the user class.
BmiResult() calls user.GetBodyType(), which calls GetBmi() on the user class. This is where your calculation happens, but since you didn't set any of the values on the user, every thing defaults to zero. Which means you are doing this:
int bmi = 0 / (0 * 0) * 10000;
Order of operations means it does this:
int bmi = (0 / 0) * 10000;
because division and multiplication are executed within parantheses first, then left to right.
However, multiplying zero by anything would still be zero, so you need to check if the divisor would be zero before doing the calculation, or wrap the code in a try/catch and handle it.

Get dice game to play again if user chooses to in c#

I've struggled through a uni assignment to create a dice game. I've finished it but of course forgot to add the option to replay the game if necessary and am so lost in code that I don't even know where to being to get the game to play again. I would really appreciate some help to be able to get users to play another game if they want to or escape the console app.
using System;
public class Player {
private int score;
private string name;
private bool isAI = false;
public void reset() {
this.score = 0;
}
public void addScore(int scoreToAdd) {
this.score = this.score + scoreToAdd;
}
public int getScore() {
return this.score;
}
public string getName() {
return this.name;
}
public void setName(string name) {
this.name = name;
}
/// Prompt the player to 'roll the dice'
public void prompt() {
if (isAI) { return; }
Console.WriteLine(getName() + ", please roll the dice (press enter):");
Console.ReadLine();
}
public void promptForName() {
Console.WriteLine("Please enter your name (Enter 'cpu' to play against the computer)");
string name = Console.ReadLine();
setName(name);
// special handling for computer players.
if (name == "cpu") { isAI = true; }
else { isAI = false; }
}
public void printScore() {
Console.WriteLine(name + " score: " + this.score);
}
public int playRound(Random rnd, Die d1, Die d2, Die d3) {
// Prompt the player so the dice don't roll immediately
this.prompt();
// Roll all the dice (pass the same rng for each one)
d1.roll(rnd);
d2.roll(rnd);
d3.roll(rnd);
// Work out which dice is highest, roll the smaller 2 again
if (d1.getValue() > d2.getValue() && d1.getValue() > d3.getValue()) {
d2.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d2.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d2.roll(rnd);
}
}
else if (d2.getValue() > d1.getValue() && d2.getValue() > d3.getValue()) {
d1.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d1.roll(rnd);
}
}
else {
d1.roll(rnd);
d2.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d2.getValue()) {
d2.roll(rnd);
}
else {
d1.roll(rnd);
}
}
// All dice are rolled, just calculate total
int total = d1.getValue() + d2.getValue() + d3.getValue();
return total;
}
}
public class Die
{
private int value;
public int getValue()
{
return this.value;
}
public void setValue(int value)
{
this.value = value;
}
public void roll(Random rnd)
{
this.value = rnd.Next(1, 7);
}
}
public class Game
{
public static string promptForPlayType()
{
Console.WriteLine("Please enter play type ('match' or 'score')");
string playType = null;
// Make sure the user enters a valid value
while (playType != "match" && playType != "score")
{
playType = Console.ReadLine();
if (playType != "match" && playType != "score")
{
Console.WriteLine("Please enter one of the two options");
}
}
return playType;
}
// Entry point
public static void Main()
{
// Prompt the user for the game play type they'd want (match or score)
string playType = promptForPlayType();
// Create rng, need this because otherwise the seed gets re-initialised to
// the same value each time
Random rnd = new Random();
// Create the players & prompt for their names
Player p1 = new Player();
Player p2 = new Player();
p1.promptForName();
p2.promptForName();
// Create the 3 dice we'll be using
Die d1 = new Die();
Die d2 = new Die();
Die d3 = new Die();
// The big 'game loop' where everything happens
for (int i = 0; i < 5; i = i + 1)
{
// Basically everything happens in these method calls
var p1Result = p1.playRound(rnd, d1, d2, d3);
var p2Result = p2.playRound(rnd, d1, d2, d3);
// Increment score based on result
if (playType == "match")
{
if (p1Result > p2Result)
{
Console.WriteLine(p1.getName() + " won a round");
p1.addScore(1);
}
else if (p2Result > p1Result)
{
Console.WriteLine(p2.getName() + " won a round");
p2.addScore(1);
}
else
{
Console.WriteLine("Game drawn");
}
}
else if (playType == "score")
{
p1.addScore(p1Result);
p2.addScore(p2Result);
}
// Print out running totals
Console.WriteLine("Player scores:");
Console.WriteLine(p1.getName() + ": " + p1.getScore());
Console.WriteLine(p2.getName() + ": " + p2.getScore());
}
Console.WriteLine("\n");
if (p1.getScore() > p2.getScore())
{
Console.WriteLine("Player 1 won");
}
else if (p2.getScore() > p1.getScore())
{
Console.WriteLine("Player 2 won");
}
else
{
Console.WriteLine("The game was a draw");
}
}
}
Enclose it in while loop until users exit from it.
public static void Main()
{
bool flag = true;
while(flag){
//your game here
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if(playAgain == "n")
flag = false;
}
}

C# How to get the player from the list so I can print out their score

I made a game where you first say how many players there are and then every player throws 3 darts and it loops until one player gets 301 points and now I want to get the player who got more than 301 points from the list of players and I want to get their score so I can print out their score and say that they won at the end of the game but I can't figure out how to do that. Thanks
class Program
{
public static void Main(string[] args)
{
Game My_game = new Game();
My_game.PlayGame();
}
}
public class Game
{
private List<Player> player_list = new List<Player>();
private List<int> total_list = new List<int>();
public void PlayGame()
{
Random random_number = new Random();
int throw1;
int throw2;
int throw3;
string more_players = "yes";
while (more_players == "yes")
{
Console.WriteLine("What is the players name?: ");
player_list.Add(new Player(Console.ReadLine()));
Console.WriteLine("Are there more players?");
more_players = Console.ReadLine();
}
Console.WriteLine("\n\n Welcome to the dartgame! \n" +
"\n Game Rules: Each player throws 3 darts at a time." +
"\n Every throw can be worth 0-20 points." +
"\n Whoever gets 301 points first is the winner!");
Console.WriteLine("\nPlayers:");
foreach (var players in player_list)
{
Console.WriteLine(players);
}
int total_points = 0;
while (!player_list.Any(x => x.calculate_points() >= 301))
{
foreach (var players in player_list)
{
Console.WriteLine("\n\n\n\n");
Console.WriteLine("\n first throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw1 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw1 + " points!");
Console.WriteLine("\n second throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw2 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw2 + " points!");
Console.WriteLine("\n third throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw3 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw3 + " points!");
total_points = throw1 + throw2 + throw3;
Console.WriteLine("\nPoints for this round: " + total_points);
total_list.Add(total_points);
total_points = total_list.Sum(x => Convert.ToInt32(x));
players.Add_turn(throw1, throw2, throw3);
}
foreach (var players in player_list)
{
players.print_turns();
}
}
}
}
class Player
{
private string name;
private List<Turns> turn_list = new List<Turns>();
public Player(string _name)
{
name = _name;
}
public void Add_turn(int turn1, int turn2, int turn3)
{
turn_list.Add(new Turns(turn1, turn2, turn3));
}
public int calculate_points()
{
int total = 0;
foreach (var turns in turn_list)
{
total = total + turns.Get_Score();
}
return total;
}
public void print_turns()
{
Console.WriteLine("\n\n\n\n----------------------------------------");
Console.WriteLine("Points for {0}", name);
foreach (var turns in turn_list)
{
Console.WriteLine(turns);
}
Console.WriteLine("\n Total points: {0}", calculate_points());
}
public override string ToString()
{
return string.Format(" {0} ", name);
}
}
class Turns
{
private int turn1;
private int turn2;
private int turn3;
public Turns(int _turn1, int _turn2, int _turn3)
{
turn1 = _turn1;
turn2 = _turn2;
turn3 = _turn3;
}
public int Get_Score()
{
int totalt;
totalt = turn1 + turn2 + turn3;
return totalt;
}
public override string ToString()
{
return string.Format("\n throw 1: {0} \n throw 2: {1} \n throw 3: {2}", turn1, turn2, turn3);
}
}
Well, this is how you already check if any players match the criteria:
player_list.Any(x => x.calculate_points() >= 301)
So as soon as one does match the criteria, you can get that single player:
player_list.Single(x => x.calculate_points() >= 301)
Or all matching players, if there's more than one:
player_list.Where(x => x.calculate_points() >= 301)
Or just the first matching player, if there's more than one but you only want one:
player_list.First(x => x.calculate_points() >= 301)
Or perhaps the player with the highest score (not accounting for a tie score):
player_list.OrderByDescending(x => x.calculate_points()).First();

Categories