I am trying to make each player display "Each Players Wins and loose at every count, so they can see the ones they won and lost
some thing like:
Player A
Games: Status of Game
1 : Win
2 : Win
3 : Win
4 : Lost
5 : Lost
6 : Win
Player B
Games: Status
1 : Lost
2 : Lost
3 : Lost
4 : Win
5 : Win
6 : Lost
Please help me out with this
class Guess
{
public int GuessedNumber { get; set; }
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
int countA = 0;
int countB = 0;
int count = 0;
public void Guu()
{
Random rand = new Random();
GuessedNumber = rand.Next(1,7);
}
public int input { get; set; }
public void FirstDisplay(string Active_Player)
{
Console.WriteLine($"{Active_Player}: Guess the number that i am thinking about");
input = Convert.ToInt32(Console.ReadLine());
count++;
}
public void CompareNumbers(List<int> PlayerA, List<int> PlayerB, ref string Active_Player)
{
if (Active_Player == "A")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} my turn");
PlayerA.Add(1);
PlayerB.Add(0);
countA++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(1);
PlayerA.Add(0);
countB++;
}
}
else if (Active_Player == "B")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} try again");
PlayerA.Add(0);
PlayerB.Add(1);
countB++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(0);
PlayerA.Add(1);
countA++;
}
}
}
public void Display()
{
Console.WriteLine("This is the result of the game");
Console.WriteLine($"Number of Game Played is: {count++}");
if (countA > countB)
{
Console.WriteLine("Winner: A");
}
else if (countA < countB)
{
Console.WriteLine("Winner: B");
}
else
{
Console.WriteLine("Draw");
}
Console.WriteLine($"Player A has {countA++} point");
Console.WriteLine($"Player B has {countB++} point ");
}
}
class Program
{
static void Main(string[] args)
{
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
string Active_Player = "A";
int count = 0;
Guess guess = new Guess();
string choice;
do
{
guess.Guu();
guess.FirstDisplay(Active_Player);
guess.CompareNumbers( PlayerA, PlayerB, ref Active_Player);
count++;
Console.WriteLine("Do you want to continue, Yes or No?");
choice = Console.ReadLine().ToLower();
}
while(choice == "yes");
guess.Display();
}
}
}
Can't you use List<int> PlayerA and List<int> PlayerB ?
Console.WriteLine("PlayerA Games Status");
for ( int i = 0; i < PlayerA.Count; ++i )
{
Console.Write( $"{i}: " );
if ( PlayerA[i] == 0) Console.WriteLine( "Loss" );
else Console.WriteLine( "Win" );
}
Do the same for PlayerB.
Related
The main idea is to each member on team1 attack a random enemy on team2. The damage dealt is based on a spell casted at random from a Grimoire book.
My Code:
using System;
namespace simple_test
{
class Program
{
public class IceLance : Hechizo //hechizo == spell
{
public IceLance(uint d) : base(20)
{
danio = d; // danio == damage
return;
}
public override void Castear() // castear == cast
{
Console.WriteLine("Ice Lance");
}
protected uint danio = 5; // danio == damage
}
public abstract class Hechizo
{
protected Hechizo(uint c)
{
costo = c; // costo == cost
}
public abstract void Castear();
protected uint costo = 1;
public uint Costo
{
get { return costo; }
}
}
public class Personaje // personaje == character
{
public Personaje()
{ }
public Personaje(uint s)
{
salud = s;
}
public void RecibirDanio(uint d) // RecibirDanio == RecieveDamage
{
salud -= d; // salud = salud - d // salud == Health
}
public virtual void Ataque() // Ataque == Attack
{
Console.WriteLine("Ataque melee");
return;
}
public bool IsVivo() // IsVivo == IsAlive
{
return salud > 0;
}
protected uint salud = 100;
}
public class Humano : Personaje // Humano == Human
{
public Humano() : base()
{ }
public Humano(uint s, uint m) : base(s)
{
mana = m;
}
public void CastearGrimorio(int idx)
{
if ((grimorio == null) ||
(idx >= grimorio.Length) || (grimorio[idx] == null))
return;
uint c = grimorio[idx].Costo;
if (mana >= c)
{
mana -= c;
grimorio[idx].Castear();
}
}
public void AprenderHechizo(Hechizo h) // AprenderHechizo == LearnSpell
{
if (grimorio == null)
{
grimorio = new Hechizo[1];
}
else
{
Hechizo[] nuevoGrimorio = new Hechizo[grimorio.Length + 1];
for (uint i = 0; i < grimorio.Length; ++i)
{
nuevoGrimorio[i] = grimorio[i];
}
grimorio = nuevoGrimorio;
}
grimorio[grimorio.Length - 1] = h;
}
public override void Ataque()
{
if (grimorio == null)
Console.WriteLine("Sin mana :(");
else
CastearGrimorio(rnd.Next(0, grimorio.Length));//con esto lanza hechizos al azar
return;
}
private uint mana = 10;
private Hechizo[] grimorio;
private Random rnd = new Random();
}
static public bool TodosMuertos(Personaje[] team) // TodosMuertos == AllDead
{
for (int i = 0; i < team.Length; ++i)
{
if (team[i].IsVivo())
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
Personaje[] team1 = new Personaje[41];
for (int i = 0; i < 3; ++i)
{
Humano mage = new Humano(80, 100);
mage.AprenderHechizo(new IceLance(20));
mage.AprenderHechizo(new IceLance(10));
mage.AprenderHechizo(new IceLance(0));
team1[i] = mage;
}
Personaje[] team2 = new Personaje[41];
for (int i = 0; i < 3; ++i)
{
Humano mage = new Humano(80, 100);
mage.AprenderHechizo(new IceLance(20));
mage.AprenderHechizo(new IceLance(10));
mage.AprenderHechizo(new IceLance(0));
team2[i] = mage;
}
while (!TodosMuertos(team1) && !TodosMuertos(team2)) // turnos
{
Console.WriteLine("team1");
for (int i = 0; i < team1.Length; ++i)
{
if (team1[i].IsVivo())
{
team1[i].Ataque();
// Here should go the RecieveDamage funtion
}
Console.ReadKey();
}
}
}
}
}
This one is a simplified version of the code, i.e. it only has one class and one spell.
I'm not sure how to write the part of how to select a member of the opposite team and in base of the spell casted receiveDamage according to its damage.
PS: I added some references to the spanish language used in the code
You can use the Random class to get a random number between 0 and the number of alive mages on the other team, and use that number to attack. Modify your attack function to take a target mage as a parameter and get them to take damage from there.
using System.Linq; // Add to top of page to use linq functions - .Where()
....
public class Humano : Personaje // Humano == Human
{
...
public override void Ataque(Personaje personaje)
{
if (grimorio == null)
Console.WriteLine("Sin mana :(");
else
{
// Modify CastearGrimoiro to return spell damage. Use person parameter to inflict damage on that person
uint damage = CastearGrimorio(rnd.Next(0, grimorio.Length));//con esto lanza hechizos al azar
personaje.RecibirDanio(damage);
}
}
...
static Random _random = new Random();
static void TakeTeamTurn(Personaje[] team, Personaje[] enemyTeam)
{
var aliveMages = team.Where(m => m.IsVivo()).ToList();
foreach(var mage in aliveMages)
{
// Get team to attack
var attackableMages = enemyTeam.Where(m => m.IsVivo()).ToList(); // Get a list of alive mages on the other team
var mageAttackIndex = _random.Next(attackableMages.Count); // Get a random number between 0 and the number of attackable mages
// (Not written here) Modify your Ataque method to take a mage parameter.
// In the Ataque method or some other method you can use this parameter to do damage to the target mage
var mageToAttack = attackableMages[mageAttackIndex];
mage.Ataque(mageToAttack);
}
}
static void Main(string[] args)
{
...
while (!TodosMuertos(team1) && !TodosMuertos(team2)) // turnos
{
Console.WriteLine("team1");
TakeTeamTurn(team1, team2);
Console.WriteLine("team2");
TakeTeamTurn(team2, team1);
Console.ReadKey();
}
....
Working example here - https://pastebin.com/kSregt24
I try to write a simple console application with Hanoi towers. But I am stuck at one point.
In my program I ask a person to write from to which tower wants to put the disk, but: I have 3 lists as towers, I'll ask for a number from gamer and now how I can build a "compare method"? Because I don't want to copy the same piece of code 6 times...
class Towers : Disks
{
//public Towers(int Value, int WhereItIs) : base(Value, WhereItIs) { }
public List<Disks> Tower1 = new List<Disks>();
public List<Disks> Tower2 = new List<Disks>();
public List<Disks> Tower3 = new List<Disks>();
public void Compare(int dyskFrom, int dyskWhere) {
}
public void Display() {
foreach(var i in Tower1){
Console.WriteLine("Where: {0} | Value: {1}", i.WhereItIs, i.Value);
}
}
public void Build(int TowerHigh) {
for (int i = TowerHigh; i > 0; i--) {
Tower1.Add(new Disks {Value = i, WhereItIs = 1 });
}
}
}
class Disks
{
public int Value; //wartosc krazka
public int WhereItIs; //na ktorej wiezy sie on znajduje
}
class Program
{
static void Main(string[] args)
{
Towers Tower = new Towers();
int TowerHigh;
Console.Write("Podaj wysokość wieży: ");
TowerHigh = int.Parse(Console.ReadLine());
Tower.Build(TowerHigh);
Tower.Display();
Tower.Compare(1, 2);
}
}
It's easier to create an array of Stack<Disk>(). This way you can select a tower by index.
I would use a Stack, because thats typically the functionality you need.
Something like: PSEUDO (typed in browser, no syntax checked)
class Disk
{
public int Size {get; set;}
}
static void Main(string[] args)
{
// create the Stack<Disk> array
Stack<Disk>[] towers = new Stack<Disk>[3];
// create each tower
for(int i=0;i<towers.Length;i++)
{
towers[i] = new Stack<Disk>();
// fill the towers.
for(int j=3;j>0;j--)
towers[i].Enqueue(new Disk { Size = j });
}
bool isHoldingDisk = false;
while(true)
{
DisplayTowers(towers);
if(isHoldingDisk)
Console.WriteLine("On what tower do you want to place it?");
else
Console.WriteLine("Choose a tower to pick a disk");
var key = Console.ReadKey(true);
var chosenTowerIndex = 0;
switch(key)
{
case(Key.Escape):
break;
case(Key.D1):
chosenTowerIndex = 0;
break;
case(Key.D1):
chosenTowerIndex = 1;
break;
case(Key.D1):
chosenTowerIndex = 2;
break;
// etc...
}
if((chosenTowerIndex < 1) || (chosenTowerIndex >= towers.Length))
continue;
// check here if you are holding a disk
if(isHoldingDisk)
{
// logic for testing if you can place the disk here...
// using towers[chosenTowerIndex]
// check if it is completed...
if(completed)
break;
isHoldingDisk = false;
}
else
{
// check if you can pickup a disk....(if there is any)
isHoldingDisk = true;
}
}
// final display...
DisplayTowers(towers);
Console.WriteLine("Thanks for playing");
}
static void DisplayTowers(Stack<Disk>[] towers)
{
// draw some fancy asc-ii art...
}
I'm developing an application in ASP.NET with C# and I'm trying to figure out the best way to implement a logic statement that will stop the system from allowing another reservation to be taken if the trailer for canoes and kayaks is full. The issue is the trailer will hold canoes and kayaks, but there's a lot of different combinations.
There are 5 "rows" on the trailer that count upwards vertically, and 2 "columns" that dissect the 5 rows in the middle. I will draw you a diagram to show you what it looks like, and what boats can go where. "C" will stand for Canoe and "K" will stand for Kayak. The trailer looks like this:
C only|C only }
______|______ } BOAT TRAILER
1C\2K|1C\2K }
______|______ }
1C\2K|1C\2K }
______|______ }
1C\2K|1C\2K }
______|______ }
C only| C only }
______|______ }
So my question is, what's the best option as far as coding and logic is concerned to not take any more "reservations" when the trailer is full? This application will be a .aspx form that will do an insert command to SQL server taking customer information.
public enum BoatType : int
{
Kayak = 1,
Canoe = 2
}
public class BoatReservation
{
public int ReservationID { get; set; }
public BoatType ReservationBoatType { get; set; }
}
public class BoatTrailer
{
public List<BoatReservation> CanoeSlots = new List<BoatReservation>();
public List<BoatReservation> RegularSlots = new List<BoatReservation>();
public BoatTrailer()
{
}
public bool AddBoat(BoatReservation b)
{
bool boatAdded = false;
switch (b.ReservationBoatType)
{
case BoatType.Canoe:
if (CanoeSlots.Count() < 4)
{
CanoeSlots.Add(b);
boatAdded = true;
}
else
{
var reg = RegularSlots.Sum(x => Convert.ToInt16(x.ReservationBoatType));
if (reg <= 10)
{
RegularSlots.Add(b);
boatAdded = true;
}
}
break;
case BoatType.Kayak:
{
var reg = RegularSlots.Sum(x => Convert.ToInt16(x.ReservationBoatType));
if (reg <= 11)
{
RegularSlots.Add(b);
boatAdded = true;
}
}
break;
}
return boatAdded;
}
public void RemoveBoat(BoatReservation b)
{
switch (b.ReservationBoatType)
{
case BoatType.Kayak:
if (RegularSlots.Contains(b))
{
RegularSlots.Remove(b);
}
break;
case BoatType.Canoe:
if (RegularSlots.Contains(b))
{
RegularSlots.Remove(b);
}
else
{
if (CanoeSlots.Contains(b))
{
CanoeSlots.Remove(b);
if (RegularSlots.Where(fb => fb.ReservationBoatType == BoatType.Canoe).Count() > 0)
{
//Move Reservation From Regular to Canoe Only With Opening
BoatReservation mv = RegularSlots.FindLast(fb => fb.ReservationBoatType == BoatType.Canoe);
RegularSlots.Remove(mv);
CanoeSlots.Add(mv);
}
}
}
break;
}
}
public string AvailableSlots()
{
string Output = string.Empty;
int AvailableCanoeCnt = (4 - CanoeSlots.Count()) + ((12 - RegularSlots.Count()) / 2);
int AvailableKayakCnt = (12 - RegularSlots.Count());
Output = string.Format("Canoe Slots Left: {0} Kayak Slots Left {1} ", AvailableCanoeCnt, AvailableKayakCnt);
return Output;
}
}
Quick class that handles reservations (both adding and deleting) of canoes/kayaks to fit a trailer.
Not the best question for this site but I will provide a pseudo structure for this.
Trailer Object
JustCanoes int
CanoeKayakBlend int
When reserving...
If the reservation is for a canoe, and the JustCanoes value is < 4, then increase JustCanoes by 1
If JustCanoes is >= 4
If CanoeKayakBlend <= 10
increase CanoeKayakBlend by 2
else
Sorry no reservation available
If the reservation is for a kayak
If CanoeKayakBlend <= 11
increase CanoeKayakBlend by 1
else
Sorry no reservation available
A very quick and simplistic implementation: Here's the Compartment class
class Compartment
{
private readonly int _maxCanoe;
private readonly int _maxKayak;
private int _currentCanoe;
private int _currentKayak;
private readonly int _id;
private bool _fullCanoe;
private bool _fullKayak;
public Compartment(int id, int maxC, int maxK)
{
_id = id;
_maxCanoe = maxC;
_maxKayak = maxK;
_currentCanoe = _currentKayak = 0;
UpdateCapacityStatus();
}
private void UpdateCapacityStatus()
{
_fullCanoe = _maxCanoe == _currentCanoe;
_fullKayak = _maxKayak == _currentKayak;
}
private string Status
{
get { return IsFull() ? "FULL" : "Space available"; }
}
public bool IsFull()
{
return _fullKayak && _fullCanoe;
}
public void AddCanoe()
{
_fullKayak = true; // disable adding kayak
_currentCanoe = _currentCanoe + 1;
_fullCanoe = _maxCanoe == _currentCanoe; //update canoe status
}
public void AddKayak()
{
_fullCanoe = true; //disable adding canoe
_currentKayak = _currentKayak + 1;
_fullKayak = _maxKayak == _currentKayak; //update kayak status
}
public override string ToString()
{
return string.Format("Id: {5}, Status: {0}, with {1} of {2} canoes or {3} of {4} kayaks", Status, _currentCanoe, _maxCanoe, _currentKayak, _maxKayak, _id);
}
public bool CanAddCanoe()
{
return !_fullCanoe;
}
public bool CanAddKayak()
{
return !_fullKayak;
}
}
And here's the driver console app to test, to use it you should refactor it of course.
`class Program
{
static void Main(string[] args)
{
var trailer = new List
{
new Compartment(1, 1, 0),
new Compartment(2, 1, 0),
new Compartment(3, 1, 2),
new Compartment(4, 1, 2),
new Compartment(5, 1, 2),
new Compartment(6, 1, 2),
new Compartment(7, 1, 2),
new Compartment(8, 1, 2),
};
foreach (var compartment in trailer)
{
Console.WriteLine(compartment.ToString());
}
Console.WriteLine("Press c for canoe or k for kayak");
var keepGoing = true;
while (keepGoing)
{
var input = Console.Read();
if (input == 99 || input == 107) //99 c, 107 k
{
if (trailer.All(c => c.IsFull()))
{
keepGoing = false;
}
else
{
if (input == 99)
{
if(!trailer.Any(t=>t.CanAddCanoe()))
{
Console.WriteLine("Cannot add a canoe!!!!");
}
else
{
var firstAvailable = trailer.First(c => c.CanAddCanoe());
firstAvailable.AddCanoe();
}
}
else if (input == 107)
{
if (!trailer.Any(t => t.CanAddKayak()))
{
Console.WriteLine("Cannot add a kayak!!!!");
}
else
{
var firstAvailable = trailer.First(c => c.CanAddKayak());
firstAvailable.AddKayak();
}
}
else
{
Console.WriteLine("Press c for canoe or k for kayak");
}
}
foreach (var compartment in trailer)
{
Console.WriteLine(compartment.ToString());
}
}
}
Console.ReadKey();
}
}`
When I attempt to run my code I get the error message 'No overload for method 'talk' takes 0 arguments', could someone help me call the talk() method please. Sorry for the long amount of code but I honestly don't understand were I'm going wrong.
class Program
{
public void Main(string[] args)
{
Critter newcritter = new Critter();
Console.WriteLine("Enter critter name: ");
var newname = Convert.ToString(Console.ReadLine());
newcritter.Name = newname;
Console.WriteLine("Say Hello to your new critter, {0}!", newcritter.Name);
var option = Convert.ToString(Console.ReadLine());
while (option != "0")
{
Console.WriteLine(#"
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
");
if (option == "0")
{
Console.WriteLine("Good-bye.");
}
if (option == "1")
{
newcritter.talk();
}
class Critter
{
public string Name { get; set; }
public int Hunger = 0;
public int Boredom = 0;
public void PassTime()
{
Hunger += 1;
Boredom += 1;
}
public void mood()
{
var unhappiness = Hunger + Boredom;
string m = "";
if (unhappiness < 5)
{
m = "Happy";
}
if (unhappiness <= 5 &&
unhappiness <= 10)
{
m = "Okay";
}
if (unhappiness <= 11 &&
unhappiness <= 15)
{
m = "Frustrated";
}
if (unhappiness <= 16)
{
m = "Mad";
}
}
public void talk(string m)
{
Console.WriteLine("I'm", Name, "and I feel", m, "now.\n");
PassTime();
}
You're calling newcritter.talk(); (without arguments), whereas your method requires one argument public void talk(string m).
So you need to pass an argument (string) to the talk method:
newcritter.talk("GOOD");
The talk method expects a string parameter, so you need to provide one:
newcritter.talk("fine");
Also, the way you're calling Console.WriteLine here is wrong. Try this instead:
public void talk(string m)
{
Console.WriteLine("I'm {0} and I feel {1} now.", Name, m);
PassTime();
}
Here's a line of code calling talk:
if (option == "1")
{
newcritter.talk();
}
Here's your defintion of talk:
public void talk(string m)
I think the error is pretty obvious.
Error Describes it more clearly:
there is no method talk with 0 arguments:
i think this :
if (option == "1")
{
newcritter.talk();//error here as there no zero argument talk() method
}
Should be:
if (option == "1")
{
newcritter.talk("somestring");
}
You have missed some thing in this code. You haven't specify the what you need to do.
As i understood your while in Program class should be.
while (option != "0")
{
Console.WriteLine(#"
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
");
if (option == "0")
{
Console.WriteLine("Good-bye.");
}
if (option == "1")
{
newcritter.talk();
}
if (option == "2")
{
newcritter.PassTime();
}
if (option == "3")
{
newcritter.mood();
}
}
And your Crtter class should be
class Critter
{
public string Name { get; set; }
public int Hunger = 0;
public int Boredom = 0;
public string m = "Happy";
// No Change in PassTime() method and mood() method
//
public void talk()
{
Console.WriteLine("I'm", Name, "and I feel", m, "now.\n");
PassTime();
}
Coming from a procedural background, I'm running into a conceptual block while designing a menu-based console application and user input validation. My goal is to display a menu that launches other processes. I want to limit user input to 1, 2, or 3 at the menu.
In a procedural language, I would do something like this pseudocode:
10 print "Make a choice"
20 choice = [dataFromKeyboard]
30 if choice < 4 && choice > 0
40 then 10
50 else 60
60 process valid choices
and no matter what I try, I can't get that out of my head while designing an OO program. Consider (simplified to include only 3 menu items):
class Menu
{
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
int menuChoice = thisdm.displayMenu();
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
}
}
class DisplayMenu
{
public int displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
return intChoice;
}
}
class ProcessMenu
{
public void processMenu(int choice)
{
switch(choice)
{
case 1:
foo1();
break;
case 2:
foo2();
break;
case 3:
foo3();;
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
}
So here's where I'm stuck. I just can't wrap my head around a simple and elegant way validate my user input that's from an OO rather than procedural standpoint.
Assuming I do the validation in the DisplayMenu, I would be validating after the input is read. But if it turns out to be invalid, how do I re-ask for valid input, since I've already called displayMenu method from Main?
I've been playing with while loops for about an hour, something like this:
intChoice = 0;
[print the menu]
while ((intChoice<1) || (intChoice>3))
Console.WriteLine("Please make a valid choice from the menu");
choice = Console.ReadLine();
etc.
but can't seem to find the sweet spot where I can control user input.
I suspect it's because I'm thinking to procedurally, and not object-oriented enough. Anyone have any tips or input to help me wrap my head around this?
Expanding on #AlexeiLevenkov's suggestion of "turning your classes 90 degrees", I went a step further and created this example of a "Modular" console Application:
class Program
{
static void Main(string[] args)
{
//Retrieve all Module types in the current Assembly.
var moduletypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(typeof(ConsoleModule)));
//Create an instance of each module
var modules = moduletypes.Select(Activator.CreateInstance)
.OfType<ConsoleModule>()
.OrderBy(x => x.Id)
.ToList();
int SelectedOption = -1;
while (SelectedOption != 0)
{
//Show Main Menu
Console.Clear();
Console.WriteLine("Please Select An Option:\n");
modules.ForEach(x => Console.WriteLine(string.Format("{0} - {1}", x.Id, x.DisplayName)));
Console.WriteLine("0 - Exit\n");
int.TryParse(Console.ReadLine(), out SelectedOption);
//Find Module by Id based on user input
var module = modules.FirstOrDefault(x => x.Id == SelectedOption);
if (module != null)
{
//Execute Module
Console.Clear();
module.Execute();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
}
}
ConsoleModule class:
public abstract class ConsoleModule
{
public int Id { get; set; }
public string DisplayName { get; set; }
public abstract void Execute();
}
Some sample Modules:
public class EnterUserNameModule : ConsoleModule
{
public EnterUserNameModule()
{
Id = 2;
DisplayName = "User Name";
}
public static string UserName { get; set; }
public override void Execute()
{
Console.WriteLine("Please Enter Your Name: ");
UserName = Console.ReadLine();
}
}
public class HelloWorldModule: ConsoleModule
{
public HelloWorldModule()
{
Id = 1;
DisplayName = "Hello, World!";
}
public override void Execute()
{
Console.WriteLine("Hello, " + (EnterUserNameModule.UserName ?? "World") + "!");
}
}
public class SumModule: ConsoleModule
{
public SumModule()
{
Id = 3;
DisplayName = "Sum";
}
public override void Execute()
{
int number = 0;
Console.Write("Enter A Number: ");
if (int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Your number plus 10 is: " + (number + 10));
else
Console.WriteLine("Could not read your number.");
}
}
Result:
It uses a little bit of reflexion to find all types deriving from ConsoleModule in the current assembly, then shows a menu with all these options (which are actually properties in this class), and calls the Execute() method when an appropiate option is selected. Much more towards OO way of thinking.
Make your processMenu function return some kind of indicator. You could use exceptions for this instead, but that's overkill.
public bool processMenu(int choice)
{
....
}
If the choice was acceptable, then return true, otherwise return false. Then:
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
ProcessMenu thispm = new ProcessMenu();
int menuChoice;
do {
menuChoice = thisdm.displayMenu();
} while( !thispm.processMenu(menuChoice) );
}
The way you are doing should be changed. Anyhow, for the same as your question, this works out:
DisplayMenu thisdm = new DisplayMenu();
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 3)
{
Console.WriteLine("enter valid choice");
menuChoice = thisdm.displayMenu();
}
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
the code like:
class Program
{
static void Main(string[] args)
{
DisplayMenu thisdm = new DisplayMenu();
ProcessMenu thispm = new ProcessMenu();
thisdm.displayMenu();
int menuChoice = thispm.GetChoice();
thispm.processMenu(menuChoice);
Console.Read();
}
}
class DisplayMenu
{
public void displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
}
}
class ProcessMenu
{
public int GetChoice()
{
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
while (!Validate(intChoice))
{
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
choice = Console.ReadLine();
intChoice = Convert.ToInt32(choice);
}
return intChoice;
}
public void processMenu(int choice)
{
switch (choice)
{
case 1:
//foo1();
break;
case 2:
//foo2();
break;
case 3:
//foo3(); ;
break;
default:
//Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
private int[] forChoices=new int[]{1,2,3};
private bool Validate(int choice)
{
if(forChoices.Contains(choice))
{
return true;
}
return false;
}
}