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
}
}
Related
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!");
}
}
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.
I have a List of type CardSlot, each of these CardSlot objects will contain different cards , say , Card1, Card2, Card3 (The number may differ).
Each CardSlot object has maximum quantity of Card1, Card2 and Card3 pre-set. Now, user inputs the amount of Cards required and should get a combination of CardSlot that fulfill the criteria.
For Eg:
List<CardSlot> listCardSlot = new List<CardSlot>();
CardSlot cardSlot1 = new CardSlot();
cardSlot1.Name = "cardSlot1";
cardSlot1.Price = 900;
cardSlot1.Card1 = 2;
cardSlot1.Card2 = 3;
cardSlot1.Card3 = 4;
listCardSlot.Add(cardSlot1);
CardSlot cardSlot2 = new CardSlot();
cardSlot2.Name = "cardSlot2";
cardSlot2.Price = 850;
cardSlot2.Card1 = 3;
cardSlot2.Card2 = 2;
cardSlot2.Card3 = 4;
listCardSlot.Add(cardSlot2);
CardSlot cardSlot3 = new CardSlot();
cardSlot3.Name = "cardSlot3";
cardSlot3.Price = 950;
cardSlot3.Card1 = 4;
cardSlot3.Card2 = 3;
cardSlot3.Card3 = 2;
listCardSlot.Add(cardSlot3);
Now, if user inputs Card1 = 4, Card2 = 5 and Card3 = 4, the end result should be the combination of CardSlot objects with the least possible price.
Can someone please give me a nudge in the right direction?Kindly tell me if something is unclear and I'll try and improve it.
Edit
I have tried finding all the possible combinations that can be in the list using following function:
public static List<List<T>> ItemCombinations<T>(List<T> inputList, int minimumItems = 1)
{
int nonEmptyCombinations = (int)Math.Pow(2, inputList.Count) - 1;
List<List<T>> listOfCombinations = new List<List<T>>(nonEmptyCombinations + 1);
if (minimumItems == 0)
listOfCombinations.Add(new List<T>());
for (int i = 1; i <= nonEmptyCombinations; i++)
{
List<T> thisCombination = new List<T>(inputList.Count);
for (int j = 0; j < inputList.Count; j++)
{
if ((i >> j) % 2 != 0)
thisCombination.Add(inputList[j]);
}
if (thisCombination.Count >= minimumItems)
listOfCombinations.Add(thisCombination);
}
return listOfCombinations;
}
This successfully returns all the possible combinations. However, it still does not take care of the situations where repeated occurance of the same card slot may be the correct choice. For e.g in the above mentioned scenario the correct choice would be 1 X CardSlot1 + 1 X CardSlot2
Edit 2
I reached an intermediate solution and have posted it as an answer, It still does not give me required answer in case of mix and match combinations. Could anyone take a look and suggest something towards that end ?
So i have made a solution for this, must say it's a headburn for me, but have tried something.
CardSlot Class I made:
public class CardSlot
{
public string Name { get; set; } = "";
public double Price { get; set; } = 0;
public int Card1 { get; set; } = 0;
public int Card2 { get; set; } = 0;
public int Card3 { get; set; } = 0;
}
and then the rest follows as:
//your code
//as above
//in the question
listCardSlot.Add(cardSlot3); //your code
ValueChecker(1);
double lowestamount = mycards.Any() ? mycards.Min(item => item.Price) : 0;
MessageBox.Show("You need " + multiplier.ToString() + " " +
ReturnLowestCardSlot(lowestamount).Name);
}
int a = 4, b = 5, c = 4; //User entered values
int multiplier = 0;
List<CardSlot> mycards = new List<CardSlot>();
CardSlot ReturnLowestCardSlot(double lowestPrice)
{
CardSlot cardslot = null;
foreach (var item in mycards)
{
if (item.Price == lowestPrice)
{
cardslot = item;
break;
}
}
return cardslot;
}
void ValueChecker(int increment)
{
multiplier += increment;
foreach (CardSlot item in listCardSlot)
{
if (((multiplier * item.Card1) >= a) &&
((multiplier * item.Card2) >= b) &&
((multiplier * item.Card3) >= c))
{
if (!(mycards.Contains(item)))
mycards.Add(item);
}
}
if (mycards.Count == 0)
ValueChecker(1);
}
The Output I'm getting is:
You need 2 cardSlot1
Hope you could tweak this one somehow to fit your need
EDIT
I see that you want output as 2 cardslot2 which has :
cardSlot2.Card1 = 3;
cardSlot2.Card2 = 2;
cardSlot2.Card3 = 4;
2 x CardSlot2 will give:
cardSlot2.Card1 = 6;
cardSlot2.Card2 = 4;
cardSlot2.Card3 = 8;
But the user's requirement is usercard1 = 4 , usercard1 = 5 & usercard1 = 4.
Here Card2 = 4 is still lesser than usercard2 = 5
I don't see how it fulfils the requirement.
EDIT 2
your comment is right, I didn't though of that. now this will give you the result:
//codes same
//as your question
ValueChecker(1);
double lowestamount = mycards.Any() ? mycards.Min(item => item.Price) : 0;
CardSlot leastcard = ReturnLowestCardSlot(lowestamount, mycards);
double lowestamount2 = listCardSlot.Any() ? listCardSlot.Min(item => item.Price) : 0;
CardSlot lowestcard = ReturnLowestCardSlot(lowestamount2, listCardSlot);
if ((leastcard.Price + lowestcard.Price) > (multiplier * leastcard.Price))
MessageBox.Show("You need " + multiplier.ToString() + " " + leastcard.Name);
else
MessageBox.Show("You need 1 " + leastcard.Name + " and 1 " + lowestcard.Name);
}
And modified ReturnLowestCardSlot
CardSlot ReturnLowestCardSlot(double lowestPrice, List<CardSlot> list)
{
CardSlot cardslot = null;
foreach (var item in list)
{
if (item.Price == lowestPrice)
{
cardslot = item;
break;
}
}
return cardslot;
}
Output:
You need 1 cardSlot1 and 1 cardSlot2
Thanks to Nobody (this sure sounds rude :D ), here is an intermediate (albeit not very optimal) solution I reached. This gives a combination (List of CardSlots) that will be the cheapest.
It does not however provide an answer when the answer should be a heterogenous solution (say 5 X CardSlot1, 3 X CardSlot2, 1 X CardSlot3). Any help towards this will be much appreciated.
static void Main(string[] args)
{
//Some Code
// Get user input card1, card2, card3
List<List<CardSlot>> validCombination = GetAllCombinations(card1, card2, card3, listCardSlot);
List<CardSlot> CheapestCombo = GetLeastPricedCombination(validCombination);
//Here I get the cheapest homogenous combination
}
private static List<List<CardSlot>> GetAllCombinations(int card1, int card2, int card3, List<CardSlot> listCardSlot)
{
var listOfCombinations = ItemCombinations(listCardSlot, 1);
List<List<CardSlot>> validCombination = new List<List<CardSlot>>();
int multiplier;
foreach (List<CardSlot> combination in listOfCombinations)
{
multiplier = 1;
if (CheckMaterialSum(combination, card1, card2, card3, ref multiplier))
{
validCombination.Add(combination);
}
else
{
GetMultiplierCombination(combination, card1, card2, card3, ref validCombination, ref multiplier);
}
}
return validCombination;
}
private static bool CheckMaterialSum(List<CardSlot> combination, int card1, int card2, int card3, ref int multiplier)
{
int sumcard1 = multiplier * (combination.Sum(comb => comb.Card1));
int sumcard2 = multiplier * (combination.Sum(comb => comb.Card2));
int sumcard3 = multiplier * (combination.Sum(comb => comb.Card3));
if (sumcard1 >= card1 && sumcard2 >= card2 && sumcard3 >= card3)
{
return true;
}
return false;
}
private static void GetMultiplierCombination(List<CardSlot> combination, int card1, int card2, int card3, ref List<List<CardSlot>> validCombination, ref int multiplier)
{
while (!CheckMaterialSum(combination, card1, card2, card3, ref multiplier))
{
multiplier += 1;
}
List<CardSlot> interMediateCombo = new List<CardSlot>();
for (int i = 0; i < multiplier; i++)
{
interMediateCombo.AddRange(combination);
}
validCombination.Add(interMediateCombo);
}
private static List<CardSlot> GetLeastPricedCombination(List<List<CardSlot>> validCombination)
{
List<CardSlot> cheapestCombo = new List<CardSlot>();
int leastPrice = int.MaxValue;
int priceTotal;
//Find better way for finding least priced combination
foreach (List<CardSlot> combination in validCombination)
{
priceTotal = combination.Sum(combo => combo.Price);
if (priceTotal < leastPrice)
{
leastPrice = priceTotal;
}
}
foreach (List<CardSlot> combination in validCombination)
{
priceTotal = combination.Sum(combo => combo.Price);
if(priceTotal == leastPrice)
{
cheapestCombo.AddRange(combination);
break;
}
}
return cheapestCombo;
}
{
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;
In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)