How can I check to see if the user won? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to check to see if user won with a conditional?
int score1 = 0;
int score2 = 0;
int score3 = 0;
for (int i = 1; i < 11; i++)
{ //open for
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
This is the piece of code I am referring to.

So, to solve the problem, you need 3 variables to which we add the various scores at each lap, this variables are then compared before the end of the while loop. The code posted shows only the comparison for the first option. I'm sure you can figure out how to compare for the remaining options.
class Program
{
public static void Main(string[] args)
{ //open main method
string name1 = "Buck";
int endurance1 = 6;
int speed1 = 4;
string name2 = "Daisy";
int endurance2 = 4;
int speed2 = 6;
string name3 = "Leo";
int endurance3 = 7;
int speed3 = 3;
int balance = 100;
Console.WriteLine("Welcome to the racetrack!\nToday's races will include 10 laps for reach race. There will be 3 races today. \nYou have $100 you can choose to bet on one of our 3 horses.\n1. Bet on a horse. \n2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{ //open while1
Console.WriteLine("Would you like to bet on: \n1." + name1 + ": \nEndurance:" + endurance1 + "\nSpeed:" + speed1 + "\n2." + name2 + ": \nEndurance:" + endurance2 + "\nSpeed:" + speed2 + "\n3." + name3 + ":\nEndurance:" + endurance3 + "\nSpeed:" + speed3 + "\nPlease enter the name of the horse as it appears on the screen.");
string choice = Console.ReadLine();
if (choice == "Buck")
{
Console.WriteLine("You have chosen " + name1 + ".");
}
else if (choice == "Daisy")
{
Console.WriteLine("You have chosen " + name2 + ".");
}
else
{
Console.WriteLine("You have chosen " + name3 + ".");
}
Console.WriteLine("How much would you like to bet? Your current balance is $" + balance + ".");
string money = Console.ReadLine();
int bet = int.Parse(money);
Console.WriteLine("You are betting $" + bet + " on " + choice + ". Type \'start\' to start the race.");
string race = Console.ReadLine();
int totalScore1 = 0;
int totalScore2 = 0;
int totalScore3 = 0;
if (race == "start")
{ // open if
Console.WriteLine("Let the races begin!");
for (int i = 1; i < 11; i++)
{ //open for
System.Random r = new System.Random();
int score1 = speed1 + endurance1 + r.Next(1, 8);
int score2 = speed2 + endurance2 + r.Next(1, 8);
int score3 = speed3 + endurance3 + r.Next(1, 8);
totalScore1 += score1;
totalScore2 += score2;
totalScore3 += score3;
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
else
Console.WriteLine("Okay, take your time.");
if(totalScore1> totalScore2 && totalScore1 > totalScore3 && choice =="Buck")
{
Console.WriteLine("Buckl won the race");
}
} //close while
Console.WriteLine("Aw, too bad. Thanks for joining us!");
} //close main method
}
}

Instead of solving your exact issue, I'd like to show you the power of collections (arrays and Dictionary). They allow you not to manually type every single condition for a single horse (imagine if you had 15 horses)
Since you're a novice, you probably will have hard time understanding this code, but watch and learn!
using System;
using System.Collections.Generic;
struct Horse
{
public string name;
public int endurance;
public int speed;
};
class Program {
public static void Main(string[] args)
{
var horseByName = new Dictionary<string, Horse>
{
{"Buck", new Horse{ name = "Buck", endurance = 6, speed = 4 } },
{"Daisy", new Horse{ name = "Daisy", endurance = 6, speed = 4 } },
{"Leo", new Horse{ name = "Leo", endurance = 7, speed = 3 } },
{"Maya", new Horse{ name = "Maya", endurance = 5, speed = 4 } },
{"Richard", new Horse{ name = "Richard", endurance = 5, speed = 4 } },
};
int balance = 100;
int numberOfHorses = horseByName.Count;
Console.WriteLine("Welcome to the racetrack!");
Console.WriteLine("Today's races will include 10 laps for reach race. There will be 3 races today.");
Console.WriteLine("You have $100 you can choose to bet on one of our 3 horses.");
Console.WriteLine("1. Bet on a horse.");
Console.WriteLine("2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{
Console.WriteLine("Would you like to bet on:");
int horseNumber = 1;
foreach (var horse in horseByName.Values)
{
Console.WriteLine($"{horseNumber}. {horse.name}\nEndurance: {horse.endurance}\nSpeed: {horse.speed}");
++horseNumber;
}
string choice = Console.ReadLine();
while (!horseByName.ContainsKey(choice))
{
Console.WriteLine("We don't have such horse, try again:");
choice = Console.ReadLine();
}
Console.WriteLine($"You have chosen {choice}.");
Console.WriteLine($"How much would you like to bet? Your current balance is ${balance}.");
int bet = int.Parse(Console.ReadLine());
Console.WriteLine($"You are betting ${bet} on {choice}. Type \'start\' to start the race.");
string race = Console.ReadLine();
if (race == "start")
{
Console.WriteLine("Let the races begin!");
int[] scores = new int[numberOfHorses];
int maxScorePerLap = 0;
string maxScoredHorseName = "";
for (int lap = 1; lap < 11; lap++)
{
System.Random r = new System.Random();
int horseId = 0;
foreach (var horse in horseByName.Values)
{
scores[horseId] = horse.speed + horse.endurance + r.Next(1, 8);
if (scores[horseId] > maxScorePerLap)
{
maxScorePerLap = scores[horseId];
maxScoredHorseName = horse.name;
}
++horseId;
}
Console.WriteLine($"{maxScoredHorseName} takes the lead in lap {lap}!");
}
if (maxScoredHorseName == choice)
{
Console.WriteLine($"Hurray! {choice} won!");
balance += bet;
}
else
{
Console.WriteLine($"Unfortunately {maxScoredHorseName} won, but you had bet on {choice}...");
balance -= bet;
}
}
else
{
Console.WriteLine("Okay, take your time.");
}
}
Console.WriteLine("Aw, too bad. Thanks for joining us!");
}
}

Related

Is there a way to combine 2 or more arrays while also combing duplicate data?

For some context I'm currently doing an assignment for college where i need to create a tournament scoring system, and this is my code so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace pointsSystemTest
{
class Program
{
static void Main(string[] args)
{
string[] e1Teams;
int n = 4;
int i;
int pos1 = 20;
int pos2 = 18;
int pos3 = 15;
int pos4 = 10;
{
{
AssigningPointsE1:
e1Teams = new string[n];
Console.WriteLine("Enter the 4 teams in order of rank below");
for (i = 0; i < n; i++)
{
e1Teams[i] = Console.ReadLine();
}
if (e1Teams.Length != e1Teams.Distinct().Count())
{
Console.WriteLine("!CONTAINS DUPLICATES!");
Console.WriteLine("Please re-enter the teams for event 1 again");
Console.ReadLine();
goto AssigningPointsE1;
}
string e1p1 = e1Teams[0] + " - " + pos1 + "points";
string e1p2 = e1Teams[1] + " - " + pos2 + "points";
string e1p3 = e1Teams[2] + " - " + pos3 + "points";
string e1p4 = e1Teams[3] + " - " + pos4 + "points";
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("{0}", e1p1);
Console.WriteLine("{0}", e1p2);
Console.WriteLine("{0}", e1p3);
Console.WriteLine("{0}", e1p4);
Console.ReadLine();
}
string[] e2Teams;
{
AssigningPointsE2:
e2Teams = new string[n];
Console.WriteLine("Enter the 4 teams in order of rank below");
for (i = 0; i < n; i++)
{
e2Teams[i] = Console.ReadLine();
}
if (e2Teams.Length != e2Teams.Distinct().Count())
{
Console.WriteLine("!CONTAINS DUPLICATES!");
Console.WriteLine("Please re-enter the teams for event 1 again");
Console.ReadLine();
goto AssigningPointsE2;
}
string e2p1 = e2Teams[0] + " - " + pos1 + "points";
string e2p2 = e2Teams[1] + " - " + pos2 + "points";
string e2p3 = e2Teams[2] + " - " + pos3 + "points";
string e2p4 = e2Teams[3] + " - " + pos4 + "points";
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("{0}", e2p1);
Console.WriteLine("{0}", e2p2);
Console.WriteLine("{0}", e2p3);
Console.WriteLine("{0}", e2p4);
Console.ReadLine();
}
}
}
}
}
I basically would like to combine the 2 arrays into one array but I would also like to display the points each team has acquired during the tournament, the teams aren't entered in the same order so I'm struggling to combine the arrays and combine the points in one go.
I envisioned the final combination of points to look like:
team 1 - 40 points,
team 4 - ... points,
team 3 - ... points,
team 2 - ... points
Here is what I would do
var events = new List<string[]>() { e1Teams, e2Teams };
var scores = new Dictionary<String, int>();
var pointsTable = new int[] { 20, 18, 15, 10 };
foreach (var ev in events) {
for (int i = 0; i < 4; i++) {
var team = ev[i];
if (scores.ContainsKey(team)) {
scores[team] += pointsTable[i];
}
else
scores[team] = pointsTable[i];
}
}
foreach (var kv in scores) {
Console.WriteLine($"{kv.Key} - {kv.Value}");
}
Note you would be way better off with not having a separate array for each event, have a list of lists

How to refactor my code to OOP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Im starting to learn a c# language. Im create a short and easy console aplication which not doing much. Well you can check it. Its about a Footbal(Soccer) game. Im really would like to refactor that code to OOP using classes and method but Im not sure where to start. In my app you can choose one from two teams and then randomly check the results. But I wolud like to add option that you can choose from 1 to much more teams. Well to be honest for the beginning maybe just 4 teams. I know I need to use classes for that insetad of writing the same blocks of code. Its just still hard for me to understand OOP. And if someone can recaftor my code in the simplest way I hope I will get much more from that. Thanks
class Program
{
static void Main(string[] args)
{
int inputGames = 0;
string userInput;
while (true)
{
Console.Write("Please select your team: Type '1' for FC Barcelona or '2' for Real Madrid: ");
userInput = Console.ReadLine();
if (userInput == "1")
{
Console.Write("Your select FC Barcelona. How many games you want to play against Real Madrid?: ");
inputGames = int.Parse(Console.ReadLine());
break;
}
else if (userInput == "2")
{
Console.Write("Your select Real Madrid. How many games you want to play against FC Barcelona?: ");
inputGames = int.Parse(Console.ReadLine());
break;
}
else
{
Console.Write("Wrong input! Try Again.");
continue;
}
}
int game = 0;
//string clubA = "FC Barcelona";
//string clubB = "Real Madrid";
int teamAwins = 0;
int teamBwins = 0;
int teamAlose = 0;
int teamBlose = 0;
int teamAdraw = 0;
int teamBdraw = 0;
int teamApoints = 0;
int teamBpoints = 0;
int teamAgoles = 0;
int teamBgoles = 0;
while (game < inputGames )
{
int teamA = 0;
int teamB = 0;
int teamAresult = 0;
int teamBresult = 0;
int TeamADefense = 8;
int TeamAMidfield = 9;
int TeamAAttack = 10;
int TeamAMentality = 8;
int TeamBDefense = 9;
int TeamBMidfield = 8;
int TeamBAttack = 9;
int TeamBMentality = 9;
Random Num = new Random();
int RandomTADefense = Num.Next(TeamADefense - 5, TeamADefense + 1);
int RandomTAMidfield = Num.Next(TeamAMidfield - 5, TeamAMidfield + 1);
int RandomTAAttack = Num.Next(TeamAAttack - 5, TeamAAttack + 1);
int RandomTAMentality = Num.Next(TeamAMentality - 5, TeamAMentality + 1);
int RandomTBDefense = Num.Next(TeamBDefense - 5, TeamBDefense + 1);
int RandomTBMidfield = Num.Next(TeamBMidfield - 5, TeamBMidfield + 1);
int RandomTBAttack = Num.Next(TeamBAttack - 5, TeamBAttack + 1);
int RandomTBMentality = Num.Next(TeamBMentality - 5, TeamBMentality + 1);
//Console.WriteLine("FC Barcelona - Defense: {0}", RandomTADefense);
//Console.WriteLine("FC Barcelona - Midfield: {0}", RandomTAMidfield);
//Console.WriteLine("FC Barcelona - Attack: {0}", RandomTAAttack);
//Console.WriteLine("FC Barcelona - Mentality: {0}", RandomTAMentality);
//Console.WriteLine("Real Madrid - Defense: {0}", RandomTBDefense);
//Console.WriteLine("Real Madrid - Midfield: {0}", RandomTBMidfield);
//Console.WriteLine("Real Madrid - Attack: {0}", RandomTBAttack);
//Console.WriteLine("Real Madrid - Mentality: {0}", RandomTBMentality);
if (RandomTADefense > RandomTBDefense)
{
teamA++;
}
else
{
teamB++;
}
if (RandomTAMidfield > RandomTBMidfield)
{
teamA++;
}
else
{
teamB++;
}
if (RandomTAAttack > RandomTBAttack)
{
teamA++;
}
else
{
teamB++;
}
if (RandomTAMentality > RandomTBMentality)
{
teamA++;
}
else
{
teamB++;
}
Random result = new Random();
if(teamA > teamB)
{
teamAwins++;
teamBlose++;
teamApoints += 3;
if (teamA == 4)
{
int winner = result.Next(4, 7);
teamAresult = winner;
teamBresult = winner - result.Next(4, winner);
teamAgoles += winner;
teamBgoles += teamBresult;
}
else if (teamA == 3)
{
int winner = result.Next(3, 5);
teamAresult = winner;
teamBresult = winner - result.Next(2, winner);
teamAgoles += winner;
teamBgoles += teamBresult;
}
else if (teamA == 2)
{
int winner = result.Next(1, 3);
teamAresult = winner;
teamBresult = winner - result.Next(1, winner);
teamAgoles += winner;
teamBgoles += teamBresult;
}
}else if (teamB > teamA)
{
teamBwins++;
teamAlose++;
teamBpoints += 3;
if (teamB == 4)
{
int winner = result.Next(4, 7);
teamBresult = winner;
teamAresult = winner - result.Next(4, winner);
teamBgoles += winner;
teamAgoles += teamAresult;
}
else if (teamB == 3)
{
int winner = result.Next(3, 5);
teamBresult = winner;
teamAresult = winner - result.Next(2, winner);
teamBgoles += winner;
teamAgoles += teamAresult;
}
else if (teamB == 2)
{
int winner = result.Next(2, 3);
teamBresult = winner;
teamAresult = winner - result.Next(1, winner);
teamBgoles += winner;
teamAgoles += teamAresult;
}
}
else
{
teamAdraw++;
teamBdraw++;
teamApoints++;
teamBpoints++;
int winner = result.Next(2, 5);
teamAresult = winner - teamA;
teamBresult = winner - teamB;
teamAgoles += teamAresult;
teamBgoles += teamBresult;
}
game++;
// Console.WriteLine("\nFC Barcelona {0} - {1} Real Madrid", teamA, teamB);
Console.WriteLine("{0}. FC Barcelona {1} - {2} Real Madrid",game, teamAresult , teamBresult);
Console.ReadLine();
}
if (userInput == "1")
{
Console.WriteLine("FC Barcelona - Points: {0}, Wins: {1}, Draws: {2}, Losses: {3}, Goles: {4}", teamApoints, teamAwins, teamAdraw, teamAlose, teamAgoles);
}
else
{
Console.WriteLine("Real Madrid - Points: {0}, Wins: {1}, Draws: {2}, Losses: {3}, Goles: {4}", teamBpoints, teamBwins, teamBdraw, teamBlose, teamBgoles);
}
Console.ReadLine();
}
}
}
//I can't write complete code for you, but will try to give an overall structure which would be helping for you as it looks like you already know the coding but just looking for the initial help of structuring the code to follow OOPS.
//You can have an Enum for team types as
public enum TeamType
{
Barcelona, RealMadrid // This can be extended at any point of time
}
//You can create a class as
Class Team{
//Properties
public int ID{get; set;}
public string Name{get; set;}
public TeamType Type{get; set;}
public int InputGames{get; set;}
//Methods
//write your methods here
}
// You can write you program here to use these as
class Program
{
static void Main(string[] args)
{
//Program would be written here
//If one team is needed, you will create one object of Team class.
//Similarily you can create as many number of Team object as many
//teams you need
}
}

c# dice game implementation

I'm stuck on how I can implement the code so when it compiles to one counter it displays one counter not 'counters' as a plural for only one counter. I need help on how I can implement that piece of code in to my code that I have given below.
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 0)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
you could use the if shorthand statement ? valueIfTrue : valueIfFalse; to set the right string values. and put everything in a function like that
private static void printCounters(int counters,bool take) {
counters = Math.Abs(counters);
string msg1 = take ? "You take " : "You give ";
string msg2 = counters == 1 ? " counter." : " counters.";
Console.WriteLine( msg1 + counters + msg2);
}
this has the advantage that you can easily call printCounters(counters,true) if you take and printCounters(counters,give) if you give
You can just add additional if's to your block.
if (counters > 1) {
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Another "simpler" solution is to just output it as counter(s)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number");
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 1)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
}
Hello and welcome to StackOverflow Sam!
So when you write the counters to the screen, you want it to write singular if their is a single counter, and plural if there are more than 1? I also assume we want this to work no matter if the counter is positive or negative.
Instead of adding a couple more branches to your if statement, we could use string.Format() and an Inline If statement.
In this case, it would look something like this:
// Console.WriteLine("You take " + counters + " counters.");
Console.WriteLine(string.Format("You take {0} counter{1}.", counters, Math.Abs(counters) == 1 ? "" : "s"));
This is really just a way of writing multiple "else ifs", as you still have added a branching statement. My way, it is in-line instead of taking up more space vertically.
If you wanted to get even more fancy, you could use an IIF to set the "give" or "take" as well:
if (counters != 0)
{
Console.WriteLine(string.Format("You {0} {1} counter{2}.",
counters > 0 ? "take" : "give",
counters,
Math.Abs(counters) == 1 ? "" : "s"
));
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Read up on the links, see what works best for you!

C# How to make an open while loop that stops when user wants

I'm writing a small loop in C# that I want to stay open until the user specifies.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
while (goon == " ")
{
Console.WriteLine("Enter a score");
score += int.Parse(Console.ReadLine());
Console.WriteLine(score + " " + counter);
counter++;
}
}
I know this code is not correct.
One way would be to set goon to something other than " " if anything other than an integer is entered by the user.
The easiest way to check if an integer has been entered is by using the Int32.TryParse method.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
int userInput = 0;
bool isInt = true;
while (goon == " ")
{
Console.WriteLine("Enter a score");
isInt = Int32.TryParse(Console.ReadLine(), out userInput);
if(isInt)
{
score += userInput;
Console.WriteLine(score + " " + counter);
counter++;
}
else
{
goon = "exit";
}
}
}
public void ScoreCalc()
{
int counter = 1;
int score = 0;
String input;
while (true)
{
Console.WriteLine("Enter a score");
input=Console.ReadLine();
if(input != "end"){
score += int.Parse(input);
Console.WriteLine(score + " " + counter);
counter++;
}else{
break;
}
}
}
I've updated your method assuming "quit" text as an exit signal from the user to break the while loop. Hope this helps!
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
var userInput = string.Empty;
var inputNumber = 0;
const string exitValue = "quit";
while (goon == " ")
{
Console.WriteLine("Enter a score or type quit to exit.");
userInput = Console.ReadLine();
if (userInput.ToLower() == exitValue)
{
break;
}
score += int.TryParse(userInput, out inputNumber) ? inputNumber : 0;
Console.WriteLine(score + " " + counter);
counter++;
}
}

How to access variables from a procedure outside of the procedure

{
static int[] location = { 0, 0 };
static int player = 0;
static void runGame()
{
int start = Convert.ToInt32(Console.ReadLine());
if (start == 1)
{
location1();
}
else if (start == 2)
{
location2();
}
else if (start == 3)
{
location3();
}
else if (start == 4)
{
location4();
}
}
static void swapPlayer()
{
if (player == 1)
{
player = 0;
}
else
{
player = 1;
}
}
static void location1()
{
Console.WriteLine(" Player " + (player + 1) + " , you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 2;
start = 2;
swapPlayer();
location2();
}
else if (input == 2) {
location[player] = 3;
start = 3;
swapPlayer();
location3();
}
}
static void location2()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the living room you can go to either \n1: Kitchen\n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2) {
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location3()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the bathroom you can go to either \n1: Kitchen \n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location4() {
Console.WriteLine(" Player " + (player + 1) + ", you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location2();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location3();
}
}
static void Main(string[] args)
{
Console.WriteLine("welcome , find the ghost and navigate through the house");
Console.Write("You are in the main hall way you can go to any of these rooms");
Console.Write(" kitchen, living room, bath room , bedroom");
Console.WriteLine("choose a room number 1 , 4 from the list ");
int start = Convert.ToInt32(Console.ReadLine());
bool play = true;
while (play== true)
{
runGame();
}
}
}
Here is the code behind a simple 2 player text adventure I am making , I was wondering where I have used the variable start in the runGame procedure how can i access that outside of the procedure , or is that not possible in which case do you have another solution on how I can get around this.
You can't, and that's the point of local variables: the world outside shouldn't care about their value (or even their existence)
If you want to access the vatiable from multiple methods, you'll have to elevate it to a (in this case static) class member:
static int[] location = { 0, 0 };
static int player = 0;
static int start;

Categories

Resources