public void Initialize(ulong id, Client client, Connection connection, Commander commander) { this.steamId = id; this.client = client; this.connection = connection; this.commander = commander; this.zoo = null; }
public ZooCont(Zoo zoo) { this.zoo = zoo; }
private void InitUC() { currentZoo = new Zoo(); currentZoo.Birth = DateTime.Now; this.zooAdmin.ucZoo.Zoo = currentZoo; }
/// <summary> /// Attaches delegates to the zoo. /// </summary> /// <param name="zoo">The zoo being changed.</param> public static void AttachDelegates(Zoo zoo) { zoo.OnBirthingRoomTemperatureChange += ConsoleHelper.HandleBirthingRoomTemperatureChange; }
/// <summary> /// Adds a new guest to the zoo. /// </summary> /// <param name="zoo">The current zoo.</param> private static void AddGuest(Zoo zoo) { bool success = false; Guest guest = new Guest(string.Empty, 0, 0m, WalletColor.Black, Gender.Female, new Account()); if (guest == null) { throw new NullReferenceException("Guest could not be found."); } while (!success) { try { string name = ConsoleUtil.ReadAlphabeticValue("Name"); guest.Name = ConsoleUtil.InitialUpper(name); success = true; } catch (ArgumentException e) { Console.WriteLine(e.Message); } } success = false; while (!success) { try { guest.Gender = ConsoleUtil.ReadGender(); success = true; } catch (Exception e) { Console.WriteLine(e.Message); } } success = false; while (!success) { try { int age = ConsoleUtil.ReadIntValue("Age"); guest.Age = age; success = true; } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } success = false; while (!success) { try { double moneyBalance = ConsoleUtil.ReadDoubleValue("Wallet money balance"); guest.Wallet.AddMoney((decimal)moneyBalance); success = true; } catch (Exception e) { Console.WriteLine(e.Message); } } success = false; while (!success) { try { guest.Wallet.Color = ConsoleUtil.ReadWalletColor(); success = true; } catch (Exception e) { Console.WriteLine(e.Message); } } success = false; while (!success) { try { double moneyBalance = ConsoleUtil.ReadDoubleValue("Checking account money balance"); guest.CheckingAccount.AddMoney((decimal)moneyBalance); success = true; } catch (Exception e) { Console.WriteLine(e.Message); } } Ticket ticket = zoo.SellTicket(guest); zoo.AddGuest(guest, ticket); ConsoleHelper.ShowGuest(zoo, guest.Name); }
/// <summary> /// Shows the children of the passed in animal. /// </summary> /// <param name="zoo">The zoo that houses the animals.</param> /// <param name="name">The name of the animal's children being shown.</param> private static void ShowChildren(Zoo zoo, string name) { Animal animal = zoo.FindAnimal(a => a.Name == name); ConsoleHelper.WalkTree(animal, ""); }
private void UpdateEntities() { if (zoo != null) { zoo.Tick(); } else if (client.Classes.Count > 0 && zoo == null) { this.zoo = new Zoo.Builder(client) .Associate<GameRules>( client.ClassesByName["CDOTAGamerulesProxy"], (i, c) => new GameRules(i, c)) .Associate<Player>( client.ClassesByName["CDOTAPlayer"], (i, c) => new Player(i, c)) .Associate<PlayerResource>( client.ClassesByName["CDOTA_PlayerResource"], (i, c) => new PlayerResource(i, c)) .Build(); zoo.Tick(); } }
private void AddAnimal(Type animalType) { Debug.WriteLine(animalType); Zoo.AddAnimal(animalType); }
public void TypeNameHandlingAuto() { var binder = new MyBinder(); var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Binder = binder }; Zoo zoo = new Zoo { Animals = new List<Animal> { new Dog("Dog!") } }; JsonSerializer serializer = JsonSerializer.Create(settings); MemoryStream ms = new MemoryStream(); BsonWriter bsonWriter = new BsonWriter(ms); serializer.Serialize(bsonWriter, zoo); ms.Seek(0, SeekOrigin.Begin); var deserialized = serializer.Deserialize<Zoo>(new BsonReader(ms)); Assert.AreEqual(1, deserialized.Animals.Count); Assert.AreEqual("Dog!", deserialized.Animals[0].Name); Assert.IsTrue(deserialized.Animals[0] is Dog); #if !(NET20 || NET35) Assert.IsTrue(binder.BindToNameCalled); #endif Assert.IsTrue(binder.BindToTypeCalled); }
/// <summary> /// The ZooConsole Main Function. /// </summary> /// <param name="args">The Zoo Console main arguments.</param> public static void Main(string[] args) { // Changes the window title. Console.Title = "Object-Oriented Programming 2: Zoo"; // Sets the opening/greeting line in the console. Console.WriteLine("Welcome to the Como Zoo!"); // Sets the zoo field to null; zoo = Zoo.NewZoo(); // Creates the command variable. string command; // Sets the exit variable. bool exit = false; // The while loop for the console commands. while (exit != true) { // Puts a bracket at the start of each line as a prompt to the user. Console.Write("] "); // Sets the command variable to make the console read the input from the user. command = Console.ReadLine(); // Converts all input to lower case, and gets rid of extra spacing, so that the switch commands work. command = command.ToLower().Trim(); // Creates the commandWords array. string[] commandWords = command.Split(); switch (commandWords[0]) { case "exit": exit = true; break; default: Console.WriteLine("Invalid command entered: " + command); break; case "help": if (commandWords.Length == 2) { ConsoleHelper.ShowHelpDetail(commandWords[1]); } else if (commandWords.Length == 1) { ConsoleHelper.ShowHelp(); } else { Console.WriteLine("Too many parameters were entered."); } break; case "restart": zoo = Zoo.NewZoo(); zoo.BirthingRoomTemperature = 77; Console.WriteLine("A new Como Zoo has been created."); break; case "save": ConsoleHelper.SaveFile(zoo, commandWords[1]); break; case "load": ConsoleHelper.LoadFile(commandWords[1]); break; case "temp": try { ConsoleHelper.SetTemperature(zoo, commandWords[1]); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("A number must be submitted as a parameter in order to change the temperature."); } catch (IndexOutOfRangeException) { Console.WriteLine("A parameter must be entered in order for the temperature command to work."); } break; case "show": try { switch (commandWords[1]) { case "animal": ConsoleHelper.ProcessShowCommand(zoo, commandWords[1], commandWords[2]); break; case "guest": ConsoleHelper.ProcessShowCommand(zoo, commandWords[1], commandWords[2]); break; case "cage": ConsoleHelper.ProcessShowCommand(zoo, commandWords[1], commandWords[2]); break; case "children": ConsoleHelper.ProcessShowCommand(zoo, commandWords[1], commandWords[2]); break; default: Console.WriteLine("Only animals and guests can be written to the console."); break; } } catch (IndexOutOfRangeException) { Console.WriteLine("A parameter must be entered in order for the show command to initiate."); } break; case "add": try { ConsoleHelper.ProcessAddCommand(zoo, commandWords[1]); } catch (IndexOutOfRangeException) { Console.WriteLine("A parameter must be entered in order for the add command to initiate."); } catch (NullReferenceException) { Console.WriteLine("The zoo may be out of tickets."); } break; case "remove": try { ConsoleHelper.ProcessRemoveCommand(zoo, commandWords[1], commandWords[2]); } catch (IndexOutOfRangeException) { Console.WriteLine("A parameter must be entered in order for the remove command to initiate."); } break; case "sort": try { SortResult sortResult = zoo.SortAnimals(commandWords[1], commandWords[2]); Console.WriteLine("SORT TYPE: " + commandWords[1].ToUpper()); Console.WriteLine("SORT BY: " + commandWords[2].ToUpper()); Console.WriteLine("SWAP COUNT: " + sortResult.SwapCount); Console.WriteLine("COMPARE COUNT: " + sortResult.CompareCount); Console.WriteLine("TIME: " + sortResult.ElapsedMilliseconds); foreach (Animal a in sortResult.Animals) { Console.WriteLine(a.ToString()); } } catch (Exception) { Console.WriteLine("Sort command must be entered as: sort [sort type] [sort by -- weight or name]."); } break; case "search": try { if (commandWords[1] == "binary") { int i = 0; string animalName = commandWords[2]; SortResult animals = zoo.SortAnimals("bubble", "name"); int minPosition = 0; int maxPosition = animals.Animals.Count - 1; while (minPosition <= maxPosition) { // get middle position by adding min and max and then dividing by 2 int midPosition = (minPosition + maxPosition) / 2; // increment loop counter i++; // use string.Compare to compare the animal name from the text box to the name of the animal at the middle position int compareResult = string.Compare(animalName, animals.Animals[midPosition].Name.ToLower()); // if the compare result is greater than zero if (compareResult > 0) { minPosition = midPosition + 1; } else if (compareResult < 0) { maxPosition = midPosition - 1; } else { Console.WriteLine($"{animalName} found. {i} loops complete."); break; } // then the animal is in the "upper" half of the list, so set the minPosition to one more than the middle position // else if the compare result is less than zero // then the animal is in the "lower" half of the list, so set the maxPosition to one less than the middle position // else // the middle animal is the animal we're looking for, so show a message box saying the animal was found and how many loops were completed and then break } } else if (commandWords[1] == "linear") { int i = 0; string animalName = commandWords[2]; foreach (Animal a in zoo.Animals) { i++; if (animalName == a.Name.ToLower()) { Console.WriteLine($"{animalName} found. {i} loops complete."); break; } } } } catch (Exception) { Console.WriteLine("Search command must be entered as: search [sort type] [animal name]."); } break; } } }
public IActionResult Cadastrado(Zoo zoo) { return(View(_context.Zoos.ToList())); }
public void InsertWithGeneratedId() { // Make sure the env supports bulk inserts with generated ids... IEntityPersister persister = sessions.GetEntityPersister(typeof (PettingZoo).FullName); IIdentifierGenerator generator = persister.IdentifierGenerator; if (!HqlSqlWalker.SupportsIdGenWithBulkInsertion(generator)) { return; } // create a Zoo var zoo = new Zoo {Name = "zoo"}; ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); s.Save(zoo); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); int count = s.CreateQuery("insert into PettingZoo (name) select name from Zoo").ExecuteUpdate(); t.Commit(); s.Close(); Assert.That(count, Is.EqualTo(1), "unexpected insertion count"); s = OpenSession(); t = s.BeginTransaction(); var pz = (PettingZoo) s.CreateQuery("from PettingZoo").UniqueResult(); t.Commit(); s.Close(); Assert.That(zoo.Name, Is.EqualTo(pz.Name)); Assert.That(zoo.Id != pz.Id); s = OpenSession(); t = s.BeginTransaction(); s.CreateQuery("delete Zoo").ExecuteUpdate(); t.Commit(); s.Close(); }
static void Main() { int minAnimals = 1, maxAnimals = 100; do { Console.Clear(); int n = InputVar <int>($"number of animals ({minAnimals} - {maxAnimals})", x => (x >= minAnimals) && (x <= maxAnimals)); List <Animal> animals = new List <Animal>(); for (int i = 0; i < n; ++i) { bool wasGenerated = false; while (!wasGenerated) { try { if (rnd.Next(2) == 0) { animals.Add(new Mammal(RandomName(rnd.Next(4, 11)), rnd.Next(10) < 4, rnd.Next(-10, 120))); animals.Last().onSound += delegate() { Console.WriteLine("я млекопитающее, би-би-би"); }; } else { animals.Add(new Bird(RandomName(rnd.Next(4, 11)), rnd.Next(10) < 4, rnd.Next(-10, 120))); animals.Last().onSound += delegate() { Console.WriteLine("я птичка, пип-пип-пип"); }; } wasGenerated = true; } catch (ArgumentException) { wasGenerated = false; } } } Zoo zoo = new Zoo(animals); foreach (var i in zoo) { Console.WriteLine(i); i.DoSound(); } XmlSerializer serializer = new XmlSerializer(typeof(Zoo), new Type[] { typeof(Mammal), typeof(Bird) }); using (var file = new FileStream("zooAnimal.ser", FileMode.Create)) { serializer.Serialize(file, zoo); } Zoo newZoo = new Zoo(); using (var file = new FileStream("zooAnimal.ser", FileMode.Open)) { newZoo = (Zoo)serializer.Deserialize(file); } Console.WriteLine("\nNew zoo:"); foreach (var i in newZoo) { Console.WriteLine(i); } var birdsNewZoo = new Zoo(newZoo.Animals.Where(x => (x.GetType() == typeof(Bird)) && x.IsTakenCare).ToList()); Console.WriteLine("\nBirds of the new zoo with IsTakenCare == True:"); foreach (var i in birdsNewZoo) { Console.WriteLine(i); } var mammalsNewZoo = new Zoo(newZoo.Animals.Where(x => (x.GetType() == typeof(Mammal)) && !x.IsTakenCare).ToList()); Console.WriteLine("\nMammals of the new zoo with IsTakenCare == False:"); foreach (var i in mammalsNewZoo) { Console.WriteLine(i); } Console.WriteLine("Press Esc to exit. Press any other key to continue."); } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
public CureAnimalCommand(Zoo zoo, string name) { this.zoo = zoo; this.name = name; }
static void Main(string[] args) { // create new Zoo with default enetered paramters var newZoo = new Zoo("Zoo #1", "Street 1", "Closed"); //create new Zoo Manager with preDefault parameters var newZooManager = new ZooManager("Kolya", 33, "Master degree"); //delcare list of animal for futher adding by manual or XML way. var loadedAminalsFromXml = new List <Animal>(); // manual generation var newFrog = new Frog("Frog #1", 10); loadedAminalsFromXml.Add(newFrog); var newHorse = new Horse("Horse #1", 30); loadedAminalsFromXml.Add(newHorse); var newTiger = new Tiger("Tiger #1", 12); loadedAminalsFromXml.Add(newTiger); var newCat = new Cat("Cat #1", 12); loadedAminalsFromXml.Add(newCat); //display list of manual generated Animals Console.WriteLine("Manual Initialized list of animals: "); foreach (var currentAnimal in loadedAminalsFromXml) { Console.WriteLine(" ----->>> " + currentAnimal.Name); } //Action for Zoo Manager = to Place Animals in Cages newZooManager.ToPlaceAnimalsOnCages(loadedAminalsFromXml, newZoo); //Display result newZoo.PrintListOfAnimalInCages(); //try to parse data from XML file var parsedXml = new XmlFileParser(); // parsing... loadedAminalsFromXml = parsedXml.TryToParseXml(); Console.WriteLine(""); // list of animals that should be added from extranal XML file Console.WriteLine("Want to add"); foreach (var currentAnimal in loadedAminalsFromXml) { Console.WriteLine(" ----->>> " + currentAnimal.Name); } //Action for Zoo Manager = to Place Animals in Cages newZooManager.ToPlaceAnimalsOnCages(loadedAminalsFromXml, newZoo); Console.WriteLine("...\nAdded successfully\n"); //Display result newZoo.PrintListOfAnimalInCages(); Console.ReadLine(); }
private void GenerateZoo() { _zoo = new Zoo("АО \"Наш новый зоопарк\"", "Россия, г.Н-ск, ул.Новая, 50"); var aviary1 = new Yard(YardType.Plain); System.Threading.Thread.Sleep(20); var aviary2 = new Cage(CageType.WithTrees); System.Threading.Thread.Sleep(20); var aviary3 = new Cage(CageType.WithRocks, 300.00, 3); System.Threading.Thread.Sleep(20); var aviary4 = new Pool(PoolType.Pond, 400, 10); System.Threading.Thread.Sleep(20); var aviary5 = new Aquarium(AquariumType.SeaWater, 5, 10); System.Threading.Thread.Sleep(20); var aviary6 = new GlassAviary(GlassAviaryType.WithWater); System.Threading.Thread.Sleep(20); aviary1.SettleAnimal(new Mammal(MammalDetachment.Artiodactyla, "Оленьи", "Олени", "Благородный олень")); System.Threading.Thread.Sleep(20); aviary1.SettleAnimal(new Mammal(MammalDetachment.Artiodactyla, "Оленьи", "Олени", "Пятнистый олень")); System.Threading.Thread.Sleep(20); aviary1.SettleAnimal(new Mammal(MammalDetachment.Artiodactyla, "Оленьи", "Олени", "Пятнистый олень")); System.Threading.Thread.Sleep(20); aviary2.SettleAnimal(new Mammal(MammalDetachment.Primates, "Гоминиды", "Орангутаны", "Суматранский орангутан")); System.Threading.Thread.Sleep(20); aviary3.SettleAnimal(new Mammal(MammalDetachment.Carnivora, "Кошачьи", "Пантеры", "Западноафриканский лев")); System.Threading.Thread.Sleep(20); aviary3.SettleAnimal(new Mammal(MammalDetachment.Carnivora, "Кошачьи", "Пантеры", "Западноафриканский лев")); System.Threading.Thread.Sleep(20); aviary4.SettleAnimal(new Bird(BirdDetachment.Anseriformes, "Утиные", "Лебеди", "Черный лебедь")); System.Threading.Thread.Sleep(20); aviary4.SettleAnimal(new Bird(BirdDetachment.Anseriformes, "Утиные", "Лебеди", "Лебедь-шипун")); System.Threading.Thread.Sleep(20); aviary4.SettleAnimal(new Bird(BirdDetachment.Anseriformes, "Утиные", "Лебеди", "Лебедь-трубач")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Fish(FishDetachment.Salmoniformes, "Лососёвые", "Лососи", "Лосось атлантический")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Fish(FishDetachment.Salmoniformes, "Лососёвые", "Лососи", "Лосось атлантический")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Fish(FishDetachment.Salmoniformes, "Лососёвые", "Лососи", "Лосось атлантический")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Fish(FishDetachment.Salmoniformes, "Лососёвые", "Лососи", "Кумжа")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Amphibian(AmphibianDetachment.Urodela, "Саламандровые", "Малые тритоны", "Обыкновенный тритон")); System.Threading.Thread.Sleep(20); aviary5.SettleAnimal(new Amphibian(AmphibianDetachment.Urodela, "Саламандровые", "Малые тритоны", "Обыкновенный тритон")); _zoo.AddAviary(aviary1); _zoo.AddAviary(aviary2); _zoo.AddAviary(aviary3); _zoo.AddAviary(aviary4); _zoo.AddAviary(aviary5); _zoo.AddAviary(aviary6); Console.Clear(); Console.WriteLine("------------------------------------------------"); Console.WriteLine("Сгенерирован зоопарк"); Console.WriteLine("С названием:{0} и \nадресом:{1}", _zoo.Name, _zoo.Address); Console.WriteLine("------------------------------------------------"); Console.WriteLine("Нажмите любую клавишу для возврата в меню..."); Console.ReadKey(); }
public ShowAllAnimalsCommand(Zoo zoo) { this.zoo = zoo; }
public IActionResult Cadastrar(Zoo zoo) { TempData["msg"] = "Zoologico cadastrado com sucesso!"; _Lista.Add(zoo); return(RedirectToAction("Listar")); }
public Menu() { _zoo = new Zoo(); StartMenu(); }
public AnimalCommon() { db = new Zoo(); }
public void visit(Zoo zoo) { this.extzoo = zoo; }
/// <summary> /// The main program for creating the zoo. /// </summary> /// <param name="args"> The arguments for the program.</param> public static void Main(string[] args) { Console.Title = "Object-Oriented Programming 2: Zoo"; Console.WriteLine("Welcome to the Como Zoo!"); bool exit = false; string command; zoo = Zoo.NewZoo(); while (!exit) { Console.Write("]"); command = Console.ReadLine(); // Create a string array variable called commandwords and set it to the result of splitting the command. string[] commandWords = command.Split(); // Lowers the letters and trims any extra whitespace. command = command.ToLower().Trim(); switch (commandWords[0]) { // If you write "exit", then it will exit the program. case "exit": exit = true; break; // If you write anything besides exit then you will get this warning. default: Console.WriteLine("Warning, the command you wrote is not valid."); break; // If you write "new" then you will create a new zoo. case "restart": zoo.BirthingRoomTemperature = 77; Console.WriteLine("A new Como Zoo has been created"); break; // If you write "help" then you will see the following... case "help": Console.WriteLine("Known commands:"); Console.WriteLine("HELP: Shows a list of known commands."); Console.WriteLine("EXIT: Exits the application."); Console.WriteLine("RESTART: Creates a new Zoo."); Console.WriteLine("TEMP: Sets the birthing room temperature."); Console.WriteLine("SHOW ANIMAL [animal name]: Displays information for specified animal."); Console.WriteLine("GUEST [guest name]: Displays information for specified guest."); break; // If you write "temp" you will see the folowing... case "temperature": ConsoleHelper.SetTemperature(zoo, commandWords[1]); break; // If you write show. case "show": try { ConsoleHelper.ProcessShowCommand(zoo, commandWords[1], commandWords[2]); } // Catch the exceptions. catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("Must be lower case letters."); } catch (IndexOutOfRangeException) { Console.WriteLine("Statement must say animal."); } break; } } }
static void Main(string[] args) { Zoo zoo = new Zoo(); ScreenDrawer drawer = new ScreenDrawer(zoo.Animals); string lastCommandResult = String.Empty; zoo.Animals.RepositoryChanged += drawer.DrawEventMessage; zoo.ZooClosing += OnZooClosing; while (true) { drawer.CleanLine(Console.WindowHeight - 2); Console.SetCursorPosition(0, Console.CursorTop - 1); drawer.CommandMessage = lastCommandResult; drawer.Draw(); string commandString = drawer.ReadLineWithControl(); string[] command = commandString.Split(' '); try { switch (command[0]) { case "help": drawer.ShowHelp(); break; case "add": zoo.AddAnimal(command[1], command[2]); lastCommandResult = $"New {command[2]} {command[1]} in zoo!"; break; case "remove": lastCommandResult = zoo.RemoveAnimal(command[1]) ? $"Bye {command[1]}(" : "Hey, it\'s alive, actually!"; break; case "feed": zoo.FeedAnimal(command[1]); break; case "heal": zoo.HealAnimal(command[1]); break; case "quit": Environment.Exit(0); break; case "all": drawer.SetDataSource(zoo.Animals.GetAll()); break; case "GetByType": drawer.SetDataSource(zoo.Animals.GetByType(command[1])); break; case "GetByState": drawer.SetDataSource(zoo.Animals.GetByState(command[1])); break; case "GetSickTigers": drawer.SetDataSource(zoo.Animals.GetSickTigers()); break; case "GetElephantByName": drawer.SetDataSource(new List <Animal>() { zoo.Animals.GetElephantByName(command[1]) }); break; case "GetHungryNames": lastCommandResult = String.Empty; foreach (var a in zoo.Animals.GetHungryNames()) { lastCommandResult += $"{a}, "; } lastCommandResult.Remove(lastCommandResult.Count() - 1, 1); break; case "GetMostHelthy": drawer.SetDataSource(zoo.Animals.GetMostHelthy()); break; case "GetDeadCountPerType": lastCommandResult = String.Empty; foreach (var t in zoo.Animals.GetDeadCountPerType()) { lastCommandResult += $"{t.Item1}: {t.Item2}\n"; } break; case "GetWolfsAndBearsByHealth": drawer.SetDataSource(zoo.Animals.GetWolfsAndBearsByHealth(3)); break; case "GetMinAndMaxHealthy": drawer.SetDataSource(zoo.Animals.GetMinAndMaxHealthy()); break; case "GetHealthAverage": lastCommandResult = zoo.Animals.GetHealthAverage().ToString(); break; default: lastCommandResult = "Unknown command"; break; } } catch (AnimalNotFoundException ex) { lastCommandResult = $"Animal named {ex.Message} is not exist"; } catch (NameAlreadyUsedException ex) { lastCommandResult = $"Name {ex.Message} already in use"; } catch (SpeciesNotFoundException ex) { lastCommandResult = $"Unknown species named {ex.Message}"; } catch (Exception ex) { lastCommandResult = $"Error: {ex.Message}"; } } }
protected CommandBase(Zoo zoo) { Zoo = zoo; }
public void Execute(Zoo zoo) { Thread thread = new Thread(KeyPress); Random random = new Random(); int time = 0; thread.Start(); while (zoo.ListAliveAnimals.Count > 0) { if (_keyPress) { thread.Abort(); break; } if (time == 1) { zoo.ListAliveAnimals[random.Next(0, zoo.ListAliveAnimals.Count)]?.ChangeState(); zoo.ListDeadAnimals.AddRange(zoo.ListAliveAnimals.Where(item => item.State.Equals(AnimalState.Dead))); zoo.ListAliveAnimals.RemoveAll(item => item.State.Equals(AnimalState.Dead)); time = 0; } Console.Clear(); Console.Write("Имя"); Console.SetCursorPosition(25, 0); Console.Write("Вид"); Console.SetCursorPosition(50, 0); Console.Write("Состояние"); Console.SetCursorPosition(75, 0); Console.WriteLine("Здоровье"); int size = 1; foreach (var item in zoo.ListAliveAnimals) { Console.Write(item.Name); Console.SetCursorPosition(25, size); Console.Write(item); Console.SetCursorPosition(50, size); Console.Write(item.State); Console.SetCursorPosition(75, size); Console.WriteLine(item.CurrentHealth); size++; } Console.SetCursorPosition(0, size); size++; Console.WriteLine(DateTimeOffset.Now.ToString("T")); Console.SetCursorPosition(0, size); size++; Console.WriteLine("\nСписок мёртвых животных"); Console.SetCursorPosition(0, size); size++; foreach (var item in zoo.ListDeadAnimals) { Console.SetCursorPosition(0, size); Console.Write(item.Name); Console.SetCursorPosition(25, size); Console.Write(item); Console.SetCursorPosition(50, size); Console.Write(item.State); Console.SetCursorPosition(75, size); Console.WriteLine(item.CurrentHealth); size++; } Console.SetCursorPosition(0, size); Console.Write("Введите любой символ для выхода: "); time++; Thread.Sleep(1000); } if (zoo.ListAliveAnimals.Count == 0) { Console.Clear(); Console.Write("Все животные мертвы!"); Console.Write("\nВведите любой символ для продолжения: "); if (Console.ReadKey().Key != ConsoleKey.Enter) { new MenuAnimal().Execute(zoo); } } else { new MenuAnimal().Execute(zoo); } }
public EventCommon() { db = new Zoo(); }
protected NotificationCommandBase(Zoo zoo, INotificationService notificationService) : base(zoo) { NotificationService = notificationService; }
private void FeedAnimals(Type animalType) { Debug.WriteLine(animalType); Zoo.FeedAnimals(animalType); }
public static void Main(string[] args) { Zoo zoo = new Zoo(); Console.WriteLine("===========Cadastro do ZooLogico=================="); zoo.Cadastro(); do { Console.Clear(); Console.WriteLine($"============ZooLogico {zoo.Nome} ================="); Console.WriteLine("1 - Cadastrar Animal"); Console.WriteLine("2 - Cadastrar Tratador"); Console.WriteLine("3 - Exibir dados Zoologico"); Console.WriteLine("4 - Exibir dados Animais"); Console.WriteLine("5 - Exibir Tratador"); Console.WriteLine("9 - Sair"); Console.WriteLine("Escolha uma opção"); int.TryParse(Console.ReadLine(), out int opcao); switch (opcao) { case 1: Animal animal = new Animal(zoo.Tratadores); animal.Cadastro(); if (!string.IsNullOrWhiteSpace(animal.Nome)) //Só vai adicionar na lista quando um animal estiver com nome { zoo.CadastraAnimail(animal); } break; case 2: Tratador tratador = new Tratador(); tratador.Cadastro(); zoo.Tratadores.Add(tratador); break; case 3: Console.WriteLine(zoo); Console.WriteLine("Aperte enter para voltar para o menu"); Console.ReadKey(); break; case 4: break; case 5: break; case 9: Console.WriteLine("Volte sempre"); Console.ReadKey(); Environment.Exit(0); break; default: break; } } while (true); }
public override void Execute() { //Лучше использовать ?. _fileWriter.WriteToFile(Zoo.Info()); }
/// <summary> /// The main program for creating the zoo. /// </summary> /// <param name="args"> The arguments for the program.</param> public static void Main(string[] args) { Console.Title = "Object-Oriented Programming 2: Zoo"; Console.WriteLine("Welcome to the Como Zoo!"); bool exit = false; string command; zoo = Zoo.NewZoo(); while (!exit) { Console.Write("]"); command = Console.ReadLine(); // Create a string array variable called commandwords and set it to the result of splitting the command. string[] commandWords = command.Split(); // Lowers the letters and trims any extra whitespace. command = command.ToLower().Trim(); switch (commandWords[0]) { // If you write "exit", then it will exit the program. case "exit": exit = true; break; // If you write anything besides exit then you will get this warning. default: Console.WriteLine("Warning, the command you wrote is not valid."); break; // If you write "new" then you will create a new zoo. case "restart": zoo.BirthingRoomTemperature = 77; Console.WriteLine("A new Como Zoo has been created"); break; // If you write "help" then you will see the following... case "help": Console.WriteLine("Known commands:"); Console.WriteLine("HELP: Shows a list of known commands."); Console.WriteLine("EXIT: Exits the application."); Console.WriteLine("RESTART: Creates a new Zoo."); Console.WriteLine("TEMP: Sets the birthing room temperature."); Console.WriteLine("SHOW ANIMAL [animal name]: Displays information for specified animal."); Console.WriteLine("GUEST [guest name]: Displays information for specified guest."); break; // If you write "temp" you will see the folowing... case "temperature": // Try this code. try { // temperature is the zoo's birthing room temperature. double temperature = zoo.BirthingRoomTemperature; // Set the birthing rooms temperature to the value of the second item in the commandWords array. // Parse the string as a double. zoo.BirthingRoomTemperature = Double.Parse(commandWords[1]); // If the zoo's temperature is between the max and min temp then... if (zoo.BirthingRoomTemperature <= BirthingRoom.MaxTemperature && zoo.BirthingRoomTemperature >= BirthingRoom.MinTemperature) { // Show the previous temperature of the birthing room. Console.WriteLine($"Previous Temperature : {temperature}"); // The new temperature. double newTemperature = zoo.BirthingRoomTemperature; // Show the new temperature of the birthing room. Console.WriteLine($"New Temperature : {newTemperature}"); } else { // Warning message. Console.WriteLine("The birthing room temperature must be between 35 and 95 degrees."); } break; } // Catch the exceptions. catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("A number must be submitted in order to change the temperature."); } catch (IndexOutOfRangeException) { Console.WriteLine("Please enter a number to change the temperature"); } break; // If you write show. case "show": try { switch (commandWords[1]) { // If you write guest. case "guest": try { { // Captializes the first letter of the string. string guestName = InitialUpper(commandWords[2]); // Finds the animal by name. Guest guestFound = zoo.FindGuest(guestName); if (guestFound != null) { Console.WriteLine("The following guest was found: " + (guestFound)); } else { Console.WriteLine("The guest could not be found."); } break; } } // Catch the exceptions. catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("Must be letters."); } catch (IndexOutOfRangeException) { Console.WriteLine("Must be the name of a guest in the list of guests.."); } break; // If you write animal. case "animal": { try { // Captializes the first letter of the string. string animalName = InitialUpper(commandWords[2]); // Finds the animal by name. Animal animalFound = zoo.FindAnimal(animalName); if (animalFound != null) { Console.WriteLine("The following animal was found: " + (animalFound)); } else { Console.WriteLine("The animal could not be found."); } break; } // Catch the exceptions. catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("Must be letters."); } catch (IndexOutOfRangeException) { Console.WriteLine("Must be the name of an animal in the zoo."); } break; } } } // Catch the exceptions. catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (FormatException) { Console.WriteLine("Must be lower case letters."); } catch (IndexOutOfRangeException) { Console.WriteLine("Statement must say animal."); } break; } } }
public FileWriteCommand(Zoo zoo, IFileWriter fileWriter) : base(zoo) { _fileWriter = fileWriter; }
public void Prepare() { ISession s = tc.OpenNewSession(); ITransaction txn = s.BeginTransaction(); Polliwog = new Animal {BodyWeight = 12, Description = "Polliwog"}; Catepillar = new Animal {BodyWeight = 10, Description = "Catepillar"}; Frog = new Animal {BodyWeight = 34, Description = "Frog"}; Polliwog.Father = Frog; Frog.AddOffspring(Polliwog); Butterfly = new Animal {BodyWeight = 9, Description = "Butterfly"}; Catepillar.Mother = Butterfly; Butterfly.AddOffspring(Catepillar); s.Save(Frog); s.Save(Polliwog); s.Save(Butterfly); s.Save(Catepillar); var dog = new Dog {BodyWeight = 200, Description = "dog"}; s.Save(dog); var cat = new Cat {BodyWeight = 100, Description = "cat"}; s.Save(cat); Zoo = new Zoo {Name = "Zoo"}; var add = new Address {City = "MEL", Country = "AU", Street = "Main st", PostalCode = "3000"}; Zoo.Address = add; PettingZoo = new PettingZoo {Name = "Petting Zoo"}; var addr = new Address {City = "Sydney", Country = "AU", Street = "High st", PostalCode = "2000"}; PettingZoo.Address = addr; s.Save(Zoo); s.Save(PettingZoo); var joiner = new Joiner {JoinedName = "joined-name", Name = "name"}; s.Save(joiner); var car = new Car {Vin = "123c", Owner = "Kirsten"}; s.Save(car); var truck = new Truck {Vin = "123t", Owner = "Steve"}; s.Save(truck); var suv = new SUV {Vin = "123s", Owner = "Joe"}; s.Save(suv); var pickup = new Pickup {Vin = "123p", Owner = "Cecelia"}; s.Save(pickup); var b = new BooleanLiteralEntity(); s.Save(b); txn.Commit(); s.Close(); }
public PrintAllAnimalsInfoCommand(Zoo zoo, INotificationService notificationService) : base(zoo, notificationService) { }
static void Main(string[] args) { zoo = new Zoo(); menuService = new ConsoleMenuService(zoo); menuService.PerformAction(); }
public PrintAnimalInfoCommand(Zoo zoo, INotificationService notificationService, IReaderService readerService) : base(zoo, notificationService, readerService) { }