I recently started making a RPS game console app it worked and I decided to give myself more of a challenge and decided it will be cool if it had a win rate for both computer and player and for some reason it's not showing the win rates on the left side
EDIT: So I got it to show left but the percents remain at 0 any idea how to fix this?
abstract class Participant
{
public int wins;
int _winRate;
public int winRate
{
get
{
return _winRate;
}
set
{
if (value < 0 || value > 100)
{
throw new Exception("value cannot be less than 0 or greater than 100");
}
_winRate = value;
}
}
public abstract string Choice();
public abstract void PrintWinRate();
}
class Computer : Participant
{
string[] Rock_Paper_Scissor = {"rock","paper","scissor"};
Random rand = new Random();
public override string Choice()
{
string element = Rock_Paper_Scissor[rand.Next(3)];
return element;
}
public override void PrintWinRate()
{
winRate = (wins / Game_Logic.gamesPlayed) * 100;
string _winRate = "computer win rate: "+winRate.ToString()+"%".PadRight(10);
Console.WriteLine(_winRate);
}
}
class Player : Participant
{
public override string Choice()
{
string playerChoice = Console.ReadLine().Trim();
return playerChoice;
}
public override void PrintWinRate()
{
winRate = (wins / Game_Logic.gamesPlayed) * 100;
string _winRate = "player win rate: " + winRate.ToString()+"%".PadRight(10);
Console.WriteLine(_winRate);
}
}
class Game_Logic
{
public static int gamesPlayed;
static void Main()
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Computer comp = new Computer();
Player player = new Player();
string computerChoice;
string playerChoice;
ConsoleKeyInfo input;
bool playAgain;
int computerWins = comp.wins;
int playerWins = player.wins;
do
{
Console.Clear();
computerChoice = comp.Choice();
playerChoice = player.Choice();
Console.Clear();
while (playerChoice == computerChoice)
{
computerChoice = comp.Choice();
}
Console.WriteLine("Player: "+ playerChoice);
Console.WriteLine("\n"+"Computer: " + computerChoice);
if (playerChoice == "rock" && computerChoice == "scissor" || playerChoice == "paper" && computerChoice == "rock")
{
playerWins++;
Console.WriteLine("\n" + "You won!");
}
else if (playerChoice == "scissor" && computerChoice == "rock" || playerChoice == "rock" && computerChoice == "paper")
{
computerWins++;
Console.WriteLine("\n" + "Computer won!");
}
else if (playerChoice == "scissor" && computerChoice == "paper")
{
playerWins++;
Console.WriteLine("\n" + "You won!");
}
else if (playerChoice == "paper" && computerChoice == "scissor")
{
computerWins++;
Console.WriteLine("\n" + "Computer won!");
}
else
{
Console.WriteLine("\n" + "invalid value");
}
Game_Logic.gamesPlayed++;
Console.WriteLine("\n"+"Play again? <y/n>");
Console.WriteLine("\n");
comp.PrintWinRate();
player.PrintWinRate();
input = Console.ReadKey(true);
playAgain = input.KeyChar == 'y';
} while (playAgain);
}
}
First things first, I think there is a problem with the increment logic, not being able to increment the actual values of participant object. playerWins and computerWins are local variables of your main, and considered as new variable, not just as reference of your participant objects. Change the following lines:
playerWins++ to player.wins++ //Change the actual values of participant
computerWins++ to comp.wins++
Next, when you say left? What format specifically would you want? For now try the following lines:
string _winRate = string.Format("player win rate: {0}%", winRate);
Your game is displaying the scores but instantly clears the screen or exits.
Placing the 'PrintWinRate' calls before 'Console.ReadKey' should give you the desired behaviour!
Like this:
Console.WriteLine("\n" + "Play again? <y/n>");
Console.WriteLine("\n");
comp.PrintWinRate();
player.PrintWinRate();
input = Console.ReadKey(true);
Edit: There also seems to be a bug in the calculation for winRate.
You might want to change your value type for 'wins' from 'int' to 'float' so that it can store the fractional part of the calculation. As it is, when you expect a player to have 50% winRate it will show 0. This is because 'int' data types can not hold fractional values and will cut that part off, leaving the whole number - in this case 0.
This code should be closer to what you want:
winRate = (int)((wins / Game_Logic.gamesPlayed) * 100);
Remember to change 'wins' in your base class 'Participant' to be a float!
Related
I am trying to make a program to play a game of craps where the user enters a bet amount, then they roll 2 six sided dice. If the sum of the dice s 2,3 or 12 they lose. 7 or 11 they win. if any other number is rolled the player keeps rolling until they get the point number to win or 7 to lose. However for some reason if I select n to not play again it still loops the game a second time before quitting. I am not sure why
any help would be appreciated.
static void processCraps()
{
string gameStatus = null;
double betAmount =0;
double netWinning = 0;
int point;
do
{
try
{
Console.WriteLine("Enter the amount to bet");
betAmount = double.Parse(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Invaid input try again");
}
var diceRoll = RollDice();
if (diceRoll == 2 || diceRoll == 3 || diceRoll == 12)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (diceRoll == 7 || diceRoll == 11)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
else if (diceRoll != 2 || diceRoll != 3 || diceRoll != 12 || diceRoll != 7 || diceRoll != 11)
{
point = diceRoll;
Console.WriteLine($"Point is {point}");
for (int rollCount = 0; rollCount >= point; rollCount++)
{
var roll = RollDice();
if (roll == 7)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (roll == point)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
}
}
try
{
Console.WriteLine("Do you want to play again (y/n)");
gameStatus = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("answer must be a letter");
}
} while (gameStatus != "n") ;
Console.WriteLine($"Your net winning is {netWinning}");
}
You read input twice.
You may want to split the logic into two loops. 1. Read bet amount. 2. Play game.
do
{
Console.WriteLine("Enter the amount to bet, or 'q' to quit:");
var betStr = Console.ReadLine();
if( betStr == "q") return;
double.TryParse(betStr, out betAmount);
} while (betAmount != 0);
do
{
//Play
Console.WriteLine("Do you want to play again (n = quit)?");
gameStatus = Console.ReadLine();
} while (gameStatus != "n");
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.
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();
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;
}
}
//Gender Creation:
while (correct == 0)
{
do
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
Gender = Console.ReadLine().ToUpper();
if (Gender == "MALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "FEMALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "RANDOM")
{
correct = 2;
}
else
{
Console.WriteLine("ERROR, Please try again.");
Gender = Console.ReadLine().ToUpper();
}
} while (correct == 0);
//Random Gender Creation:
if (correct == 2)
{
do
{
if (randgender == 1)
{
Console.WriteLine("The gender: MALE was randomly chosen");
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "MALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
else if (randgender == 2)
{
Console.WriteLine("The gender: FEMALE was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "FEMALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
} while (correct == 2);
correct = 0;
}
break;
}
When correct = 2 then the gender is being randomly generated, if the user inputs no when being asked if they are happy with the gender the code will just loop the random gender generator over and over constantly saying that the random gender is the same every time as the random number is never changing however when correct = 0 the code will just proceed when no is inputted and when the gender is printed it is just printed as RANDOM as that is the option the user initially chose.
How can I make it go back to the first do while loop to ask the user what gender they want their character to be?
As theMayer suggested, you'll need to break down your app into smaller pieces. There are also a few concepts that you may need to tackle before you can write C#, as such.
This example might help you get a little further along, as it illustrates several ways of achieving better control flow:
static void Main(string[] args)
{
Console.Clear();
var choosenGender = "";
var wasChoiceConfirmed = false;
while (wasChoiceConfirmed == false)
{
choosenGender = PromptForGender();
switch (choosenGender)
{
case "RANDOM":
var randomGender = GenerateRandomGender();
wasChoiceConfirmed = PromptForGenderConfirmation(randomGender, true);
break;
case "MALE":
case "FEMALE":
wasChoiceConfirmed = PromptForGenderConfirmation(choosenGender);
break;
default:
Console.WriteLine("Error, please try again. \n");
break;
}
}
}
static string PromptForGender()
{
Console.Write(
"\nPlease choose a gender from the options below: \n" +
"Male|Female|Random \n" +
"Input:");
return Console.ReadLine().Trim().ToUpper();
}
static bool PromptForGenderConfirmation(string gender, bool wasRandom = false)
{
var randomVerbiage = wasRandom ? "randomly " : "";
Console.Write(
$"\nThe gender: {gender} was {randomVerbiage}chosen \n" +
"Is this the gender you wish your character to be? Enter Yes/No: \n" +
"Input: ");
var confirmed = Console.ReadLine().Trim().ToUpper();
return confirmed == "YES";
}
static string GenerateRandomGender()
{
var randomNumber = new Random();
return randomNumber.Next(0, 1) == 0 ? "FEMALE" : "MALE";
}
I refactored your code so it helps me understand it better. This gives you the result you want and you don't need all those nested loops.
public class Program
{
public static void AskFirstQuestion()
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
var gender = Console.ReadLine()?.ToUpper();
if (gender == "MALE" || gender == "FEMALE")
{
HandleGenderSelection(gender);
}
else if (gender == "RANDOM")
{
HandleRandom();
}
}
private static void HandleRandom()
{
var randomGender = GenerateRandomGender();
Console.WriteLine($"The gender: {randomGender} was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
switch (input)
{
case "YES":
Console.WriteLine("OK");
break;
case "NO":
AskFirstQuestion();
break;
}
}
private static string GenerateRandomGender()
{
//Have you logic to randomly create gender
return "MALE";
}
private static void HandleGenderSelection(string gender)
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
if (input == "YES")
{
Console.WriteLine("OK!");
}
else if (input == "NO")
{
AskFirstQuestion();
}
}
static void Main(string[] args)
{
AskFirstQuestion();
}
}