How to access variables from a procedure outside of the procedure - c#

{
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;

Related

How can I check to see if the user won? [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 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!");
}
}

I'm not sure why the dealer isnt hitting

This is the card I'm working with and I'm very confused to why the dealer isn't hitting when instructed to. I've rearranged my code tried different methods but it still doesn't seem to be working. If someone can help me solve this C# script I'd be very thankful.
using System;
using System.Collections.Generic;
public class MainClass
{
public static int PlayerTotal;
public static int DealerTotal;
static Random random = new Random();
public static List<int> cards = new List<int>();
public static List<int> hand = new List<int>();
public static List<int> DealerHand = new List<int>();
public static bool GameOver = false;
public static void Main (string[] args)
{
// Players hand gets created
for (int i = 2; i <= 11; i++)
{
cards.Add(i);
}
for (int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
hand.Add(cards[index]);
}
foreach (int a in hand)
{
Console.WriteLine("{0}", a);
PlayerTotal = PlayerTotal + a;
if(PlayerTotal == 22 || PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
Console.WriteLine("Your hand total is " + PlayerTotal);
// Dealer hand being created
for(int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
DealerHand.Add(cards[index]);
}
foreach(int a in DealerHand)
{
Console.WriteLine("{0}", a);
DealerTotal = DealerTotal + a;
if(DealerTotal == 22 || DealerTotal == 21)
{
Console.WriteLine("The dealer won!");
GameOver = true;
}
}
Console.WriteLine("The dealer hand total is " + DealerTotal);
// Player choice to hit or stay
while (PlayerTotal < 21 && GameOver == false)
{
Console.WriteLine("Do you want to hit or stand? h/s");
string choice = Console.ReadLine();
if (choice == "h")
{
PlayerHit();
}
else if (choice == "s")
{
Console.WriteLine("You stood");
}
}
while (DealerTotal < 21 && GameOver == false )
{
if(DealerTotal <= 16)
{
DealerHit();
}
else
{
Console.WriteLine("The dealer stood");
}
}
}
public static void PlayerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int hitCard = cards[index];
hand.Add(hitCard);
PlayerTotal = PlayerTotal + hitCard;
Console.WriteLine("You got a " + hitCard);
Console.WriteLine("Your new total is " + PlayerTotal);
if(PlayerTotal > 21)
{
Console.WriteLine("You lost!");
GameOver = true;
}
else if (PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
}
public static void DealerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int DealerHitCard = cards[index];
DealerHand.Add(DealerHitCard);
DealerTotal = DealerTotal + DealerHitCard;
int DealerHitCardNew = DealerHitCard;
Console.WriteLine("The dealer got a " + DealerHitCardNew);
Console.WriteLine("The dealers total is now " + DealerTotal);
if (DealerTotal > 21)
{
Console.WriteLine("You Won!");
GameOver = true;
}
else if (DealerTotal == 21)
{
Console.WriteLine("You Lost!");
GameOver = true;
}
}
}
}
Any help would be very appreciated. My school has set us homework that we have to create a sort of application, and i thought this would be fun to make.
This line here:
while(PlayerTotal < 21 && GameOver == false) {
That will only be true if you bust or get 21. If you stand, you will never exit this loop. Add a break to the stand option:
} else if(choice == "s"){
Console.WriteLine("You stood");
break;
}
Unfortunately, you have the same issue in the following loop:
while(DealerTotal < 21 && GameOver == false ) {
Add a break to the correct block to exit the loop when the dealer stands. Finally, you will need to add winning/losing logic after both the player and the dealer have stood.

Talent show program in C# [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 3 years ago.
Improve this question
I need some help with this program I got from a programming website, I am still new to programming and this seems like too much for me right now. I don't even know where to begin with this program:
In one of the last problems, you created the most recent version of the GreenvilleRevenue program, which prompts the user for contestant data for this year’s Greenville Idol competition. Now, save all the entered data to a Greenville.ser file(this is provided by the website) that is closed when data entry is complete and then reopened and read in, allowing the user to view lists of contestants with requested talent types. The program should output the name of the contestant, the talent, and the fee.
using System;
using static System.Console;
class GreenvilleRevenue
{
static void Main()
{
const int MIN_CONTESTANTS = 0;
const int MAX_CONTESTANTS = 30;
int num;
int revenue = 0;
const char QUIT = 'Z';
char option = ' ';;
Contestant[] contestants = new Contestant[MAX_CONTESTANTS];
num = getContestantNumber(MIN_CONTESTANTS, MAX_CONTESTANTS);
revenue = getContestantData(num, contestants, revenue);
WriteLine("\n\nRevenue expected this year is {0}", revenue.ToString("C"));
while(option != QUIT)
option = getLists(num, contestants);
}
private static int getContestantNumber(int min, int max)
{
string entryString;
int num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
while(num < min || num > max)
{
if(!int.TryParse(entryString, out num))
{
WriteLine("Format invalid");
num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
}
else
{
try
{
if(num < min || num > max)
throw(new ArgumentException());
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("Number must be between {0} and {1}", min, max);
num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
}
}
}
return num;
}
private static int getContestantData(int num, Contestant[] contestants, int revenue)
{
const int ADULTAGE = 17;
const int TEENAGE = 12;
int x = 0;
string name;
char talent;
int age;
int pos;
while(x < num)
{
Write("Enter contestant name >> ");
name = ReadLine();
WriteLine("Talent codes are:");
for(int y = 0; y < Contestant.talentCodes.Length; ++y)
WriteLine(" {0} {1}", Contestant.talentCodes[y], Contestant.talentStrings[y]);
Write(" Enter talent code >> ");
char.TryParse(ReadLine(), out talent);
try
{
validateCode(talent, out pos);
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("{0} is not a valid code. Assigned as Invalid.", talent);
}
Write(" Enter contestant's age >> ");
int.TryParse(ReadLine(), out age);
if(age > ADULTAGE)
contestants[x] = new AdultContestant();
else
if(age > TEENAGE)
contestants[x] = new TeenContestant();
else
contestants[x] = new ChildContestant();
contestants[x].Name = name;
contestants[x].TalentCode = talent;
revenue += contestants[x].Fee;
++x;
}
return revenue;
}
private static char getLists(int num, Contestant[] contestants)
{
int x;
char QUIT = 'Z';
char option = ' ';
bool isValid;
int pos = 0;
bool found;
WriteLine("\nThe types of talent are:");
for(x = 0; x < Contestant.talentStrings.Length; ++x)
WriteLine("{0, -6}{1, -20}", Contestant.talentCodes[x], Contestant.talentStrings[x]);
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
isValid = false;
while(!isValid)
{
if(!char.TryParse(ReadLine(), out option))
{
isValid = false;
WriteLine("Invalid format - entry must be a single character");
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
}
else
{
if(option == QUIT)
isValid = true;
else
{
try
{
validateCode(option, out pos);
isValid = true;
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("{0} is not a valid code", option);
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
isValid = false;
}
}
if(isValid && option != QUIT)
{
WriteLine("\nContestants with talent {0} are:", Contestant.talentStrings[pos]);
found = false;
for(x = 0; x < num; ++x)
{
if(contestants[x].TalentCode == option)
{
WriteLine(contestants[x].ToString());
found = true;
}
}
if(!found)
{
WriteLine("No contestants had talent {0}", Contestant.talentStrings[pos]);
isValid = false;
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
}
}
}
}
return option;
}
public static void validateCode(char option, out int pos)
{
bool isValid = false;
pos = Contestant.talentCodes.Length - 1;
for(int z = 0; z < Contestant.talentCodes.Length; ++z)
{
if(option == Contestant.talentCodes[z])
{
isValid = true;
pos = z;
}
}
if(!isValid)
throw(new ArgumentException());
}
}
class Contestant
{
public static char[] talentCodes = {'S', 'D', 'M', 'O'};
public static string[] talentStrings = {"Singing", "Dancing",
"Musical instrument", "Other"};
public string Name {get; set;}
private char talentCode;
private string talent;
private int fee;
public char TalentCode
{
get
{
return talentCode;
}
set
{
int pos = talentCodes.Length;
for(int x = 0; x < talentCodes.Length; ++x)
if(value == talentCodes[x])
pos = x;
if(pos == talentCodes.Length)
{
talentCode = 'I';
talent = "Invalid";
}
else
{
talentCode = value;
talent = talentStrings[pos];
}
}
}
public string Talent
{
get
{
return talent;
}
}
public int Fee
{
get
{
return fee;
}
set
{
fee = value;
}
}
}
class AdultContestant : Contestant
{
public int ADULT_FEE = 30;
public AdultContestant()
{
Fee = ADULT_FEE;
}
public override string ToString()
{
return("Adult Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
class TeenContestant : Contestant
{
public int TEEN_FEE = 20;
public TeenContestant()
{
Fee = TEEN_FEE;
}
public override string ToString()
{
return("Teen Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
class ChildContestant : Contestant
{
public int CHILD_FEE = 15;
public ChildContestant()
{
Fee = CHILD_FEE;
}
public override string ToString()
{
return("Child Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
I agree with Mark's opinion, as well as the others who have up-voted his comment.
I wouldn't wait on someone to post a solution to your question so I'll go ahead and give you some things to get started on your own research and solution.
(Most of this is already in your problem statement, just broken down)
Start with the existing code you've pasted in
Read it line by line and google/textbook/stackoverflow ANYTHING you don't understand. Get a general understanding, and go deep if you have time.
Learn how to save data to a file in C#
Learn how to load data from a file in C#
Find a place in the code for the save data logic. (after data entry)
Run load data logic after save data logic
Display what was loaded
Edit: As you do research, you'll find lots of stackoverflow posts with good answers. Follow the format for those questions (prior research, attempted solutions, specific question, small code snippets) in order to ask more engaging questions yourself.

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!

Categories

Resources