public bool LoadGame() { var fileReader = new FileReader(); var banker = fileReader.ReadBankerFromBin(); // Set the banker to be the banker loaded from the bin file. // We need to set the banker before loading the board because // we set the banker to be the owner of properties from the board // when loading the properties that the banker owned originally Banker.SetBankerFromLoadedBanker(banker); var board = fileReader.ReadBoardFromBin(); // The board will be null if the file doesn't exist so we need to cover that case // and we need to make sure the board has players otherwise it's an empty board if (board != null && board.GetPlayerCount() >= 2) { // Set the board to be the the board instance loaded from the bin file Board.Access().SetBoardFromLoadedBoard(board); Console.WriteLine("Game Loaded!"); return(true); } Console.WriteLine("No game to load!"); return(false); }
public void SetLocation(int newLocation) { var boardSize = Board.Access().GetSquares(); if (newLocation > boardSize) { // Because the properties arraylist is zero based index, // we have to add one to the board size to get the correct location _location = newLocation - (boardSize + 1); if (PlayerPassGo != null) { PlayerPassGo(this, new EventArgs()); Receive(200); } return; } if (newLocation == boardSize) { // The last index is 39 (0-39 = 40) therefore // if the new location is 40, as in the last // square, we must substract 1 from the new location // of square 40 to place the player at index 39. _location = newLocation - 1; return; } _location = newLocation; }
private void HandleLanding(Property propertyLandedOn, Player player) { // If it's a residential property we need to parse it so we can get the colour and display it to the user // otherwise they won't be aware of colour the property is at any point. var propertyAsRes = propertyLandedOn.GetType() == typeof(Residential) ? (Residential)propertyLandedOn : null; // When landing on chance or community chest we need the behavour to be // slightly different, i.e. get a card and display what the card is if (propertyLandedOn.GetName().Contains("Chance") && (Board.Access().GetChanceCards().Count > 0)) { Console.WriteLine(Board.Access().GetChanceCard().LandOn(ref player)); } else if (propertyLandedOn.GetName().Contains("Community Chest") && (Board.Access().GetCommunityChestCards().Count > 0)) { Console.WriteLine(Board.Access().GetCommunityChestCard().LandOn(ref player)); } else { // Landon property and output to console // In the case that they've landed on a chance or community chest but there // aren't any cards left we must make them aware of this. var isChance = propertyLandedOn.GetName().Contains("Chance"); var isCommunityChest = propertyLandedOn.GetName().Contains("Community Chest"); Console.WriteLine("{0}{1}{2}", propertyLandedOn.LandOn(ref player), /*{0}*/ isChance ? " No more Chance cards." : isCommunityChest ? " No more Community Chest cards." : "", /*{1}*/ propertyAsRes != null ? " (Colour: " + propertyAsRes.GetHouseColour() + ")" : ""); /*{2}*/ } }
public bool OwnsAllPropertiesOfColour(string houseColour) { // Get all properties of the supplied colour var propertiesOfColour = Board.Access().GetAllPropertiesOfColour(houseColour); // Return whether or not this player is the owner of every one of those properties return(propertiesOfColour.All(x => x.GetOwner() == this)); }
public override bool EndOfGame() { //display message Console.WriteLine("The game is now over. Please press enter to exit."); Console.ReadLine(); //exit the program Board.Access().SetGameOver(true); return(true); }
public void SaveGame() { var fileWriter = new FileWriter(); // Save the current state of the board fileWriter.SaveGame(Board.Access()); Console.WriteLine("Game Saved!"); }
public void SellHouse() { // Owner receives half the house cost from banker var halfHouseCost = HouseCost / 2; Owner.Receive(halfHouseCost); Banker.Access().Pay(halfHouseCost); // Board gets house back Board.Access().Houses++; // Property loses the house HouseCount--; }
public void CreateProperties() { var resFactory = new ResidentialFactory(); var transFactory = new TransportFactory(); var utilFactory = new UtilityFactory(); var genericFactory = new PropertyFactory(); var luckFactory = new LuckFactory(); try { var propertyDetails = _fileReader.ReadPropertyDetailsFromCSV(); // Add the properties to the board foreach (var propertyDetail in propertyDetails) { switch (propertyDetail.Type.ToLower()) { case "luck": Board.Access() .AddProperty(luckFactory.create(propertyDetail.Name, propertyDetail.IsPenalty, propertyDetail.Amount)); break; case "residential": Board.Access() .AddProperty(resFactory.create(propertyDetail.Name, propertyDetail.Price, propertyDetail.Rent, propertyDetail.HouseCost, propertyDetail.HouseColour)); break; case "transport": Board.Access().AddProperty(transFactory.create(propertyDetail.Name)); break; case "utility": Board.Access().AddProperty(utilFactory.create(propertyDetail.Name)); break; case "generic": Board.Access().AddProperty(genericFactory.Create(propertyDetail.Name)); break; } } Console.WriteLine("Properties have been setup"); } catch (Exception ex) { Console.WriteLine("Oops, something went wrong setting up the properties: {0}", ex.Message); } }
public ArrayList GetPropertiesOwnedFromBoard() { var propertiesOwned = new ArrayList(); for (var i = 0; i < Board.Access().GetProperties().Count; i++) { if (Board.Access().GetProperty(i).GetOwner() == this) { propertiesOwned.Add(Board.Access().GetProperty(i)); } } return(propertiesOwned); }
public void PlayGame() { while (Board.Access().GetPlayerCount() >= 2 && !Board.Access().GetGameOver()) { for (int i = 0; i < Board.Access().GetPlayerCount(); i++) { // If the game is over don't make them play if (Board.Access().GetGameOver()) { break; } MakePlay(i); } } }
public bool IsCriminal() { const int goToJailLocation = 30; var goToJailProperty = Board.Access().GetProperty(goToJailLocation); var currentLocation = Board.Access().GetProperty(_location); var isCriminal = currentLocation.Equals(goToJailProperty) || (RolledDoublesCount > 2); if (isCriminal) { GoToJail(); } // If they are on go to jail, they are a criminal return(isCriminal); }
public override void PrintWinner() { Player winner = null; //get winner who is last active player foreach (Player p in Board.Access().GetPlayers()) { //if player is active if (p.IsActive()) { winner = p; } } //display winner Console.WriteLine("\n\n{0} has won the game!\n\n", winner.GetName()); //end the game this.EndOfGame(); }
public void AddHouse() { GetOwner().Pay(HouseCost); HouseCount++; Board.Access().Houses--; if (HouseCount > 4) { HasHotel = true; // Take a hotel from the board Board.Access().Hotels--; // Give the houses back to the board now that // this property has a hotel Board.Access().Houses += HouseCount; // This property should now have no houses HouseCount = 0; } }
public bool CanDevelopPropertyFurther(Residential propertyToBuyHouseFor) { var propertiesOfColour = Board.Access().GetAllPropertiesOfColour(propertyToBuyHouseFor.GetHouseColour()); var propertiesExcludingDevelopee = propertiesOfColour.Where(property => property != propertyToBuyHouseFor); /*** * In order to build a house on a property, the player must build houses * uniformly across the properties of a colour. That means the player can't * build a second house on a property of a colour until all properties of * that colour have one house. * So each property (excluding the one in question) should have the same amount * of houses as the one in question. Minus one for the case where a property in the * colour group might have 1 house and the one in question has 0, they aren't equal * so we need to minus 1 from the property that has a house. * */ return(propertiesExcludingDevelopee .All(property => property.GetHouseCount() == (propertyToBuyHouseFor.GetHouseCount()) || property.GetHouseCount() - 1 == (propertyToBuyHouseFor.GetHouseCount()))); }
public void PurchaseProperty(Player player, bool?testAnswer = null) { if (player.IsInJail) { Console.WriteLine("You are in Jail and can not purchase property."); } //if property available give option to purchase else so not available else if (Board.Access().GetProperty(player.GetLocation()).AvailableForPurchase()) { TradeableProperty propertyLocatedOn = (TradeableProperty)Board.Access().GetProperty(player.GetLocation()); bool?respYN = testAnswer ?? GetInputYn(player, string.Format("'{0}' is available to purchase for ${1}. Are you sure you want to purchase it?", propertyLocatedOn.GetName(), propertyLocatedOn.GetPrice())); if ((bool)respYN) { propertyLocatedOn.Purchase(ref player);//purchase property Console.WriteLine("{0}You have successfully purchased {1}.", PlayerPrompt(player), propertyLocatedOn.GetName()); } } else { Console.WriteLine("{0}{1} is not available for purchase.", PlayerPrompt(player), Board.Access().GetProperty(player.GetLocation()).GetName()); } }
public override decimal GetRent() { // Mortgaged properties cannot have rent collected on them if (IsMortgaged) { return(0); } // This is the rent value for a property with a hotel if (HasHotel) { return(Rent + (Rent * 5)); } // The rent is double if the owner owns all the properties of this colour and the property is undeveloped (exclude the banker) if ((Board.Access().GetAllPropertiesOfColour(HouseColour).All(x => x.Owner == Owner && Owner != Banker.Access())) && (HouseCount == 0)) { return(Rent * 2); } // The rent multiplier is dependent on if the property // is at the hotel stage or not yet return(Rent + (Rent * HouseCount)); }
/// <summary> /// Sets up players for the new game of Monopoly /// </summary> /// <param name="testInput">Required so we can test this method without relying on console input, shouldn't be used outside of tests</param> /// <param name="testName">Required so we can test this method without relying on console input, shouldn't be used outside of tests</param> public void SetUpPlayers(int?testInput = null, string testName = null) { //Add players to the board Console.WriteLine("How many players are playing?"); Console.Write("(2-8)>"); var playerCount = testInput ?? InputInteger(); //if it is out of range then display msg and redo this method if ((playerCount < 2) || (playerCount > 8)) { Console.WriteLine("That is an invalid amount. Please try again."); // Don't recall if it's a test if (testInput == null) { SetUpPlayers(); } } //Ask for players names for (int i = 0; i < playerCount; i++) { Console.WriteLine("Please enter the name for Player {0}:", i + 1); Console.Write(">"); string sPlayerName = testName ?? Console.ReadLine(); Player player = new Player(sPlayerName); //subscribe to events player.PlayerBankrupt += playerBankruptHandler; player.PlayerPassGo += playerPassGoHandler; //add player Board.Access().AddPlayer(player); Console.WriteLine("{0} has been added to the game.", Board.Access().GetPlayer(i).GetName()); } Console.WriteLine("Players have been setup"); }
public void CreateCards() { try { var cards = _fileReader.ReadCardDetailsFromCSV(); foreach (var card in cards) { if (card.GetName().Contains("Chance")) { Board.Access().AddChanceCard(card); } if (card.GetName().Contains("Community Chest")) { Board.Access().AddCommunityChestCard(card); } } } catch (Exception ex) { Console.WriteLine("Oops, something went wrong setting up the cards: {0}", ex.Message); } }
public override void MakePlay(int iPlayerIndex) { while (true) { //make variable for player Player player = Board.Access().GetPlayer(iPlayerIndex); //Change the colour for the player Console.ForegroundColor = this._colors[iPlayerIndex]; //if inactive skip turn if (!player.IsActive()) { Console.WriteLine("\n{0} is inactive.\n", player.GetName()); //check players to continue //check that there are still two players to continue int activePlayerCount = 0; foreach (Player p in Board.Access().GetPlayers()) { //if player is active if (p.IsActive()) { //increment activePlayerCount activePlayerCount++; } } //if less than two active players display winner if (activePlayerCount < 2) { this.PrintWinner(); } return; } //prompt player to make move Console.WriteLine("{0}Your turn. Press Enter to make move", PlayerPrompt(iPlayerIndex)); Console.ReadLine(); //move player player.Move(); if (player.IsInJail && player.RolledDoubles && (player.RollDoublesFailureCount < 3)) { player.SetFreeFromJail(); Console.WriteLine("You rolled doubles! You are out of Jail."); } if (player.IsInJail && player.RollDoublesFailureCount == 3) { Console.WriteLine("You've failed to roll doubles three times while in Jail and must now settle it."); GetOutOfJail(player, true); } //Display making move Console.WriteLine("*****Move for {0}:*****", player.GetName()); //Display rolling Console.WriteLine("{0}{1}\n", PlayerPrompt(iPlayerIndex), player.DiceRollingToString()); Property propertyLandedOn = Board.Access().GetProperty(player.GetLocation()); HandleLanding(propertyLandedOn, player); //Display player details Console.WriteLine("\n{0}{1}", PlayerPrompt(iPlayerIndex), player.BriefDetailToString()); if (player.IsCriminal()) { Console.WriteLine("You are a criminal, go to Jail and lose your turn."); // Need to reset this here so when they come to get out of jail they aren't seen as a ciminal again // Thrice in a row means jail! if (player.RolledDoublesCount > 2) { Console.WriteLine("This is because you rolled doubles thrice in a row."); } // Reset the count as they've been sent to jail player.RolledDoublesCount = 0; return; } //display player choice menu DisplayPlayerChoiceMenu(player); // Player's get another turn when they roll doubles if (player.RolledDoubles && !player.IsInJail) { Console.WriteLine("You rolled doubles and get another turn"); continue; } // When turn ends reset their rolled doubles count player.RolledDoublesCount = 0; break; } }
public string FullDetailToString() { return(String.Format("Player:{0}.\nBalance: ${1}\nLocation: {2} (Square {3}) \nProperties Owned:\n{4}", GetName(), GetBalance(), Board.Access().GetProperty(GetLocation()), GetLocation(), PropertiesOwnedToString())); }
public string BriefDetailToString() { return(String.Format("You are on {0}.\tYou have ${1}.", Board.Access().GetProperty(GetLocation()).GetName(), GetBalance())); }
public string PlayerPrompt(int playerIndex) { return(string.Format("{0}:\t", Board.Access().GetPlayer(playerIndex).GetName())); }
public void BuyHouse(Player player, Property testProperty = null, bool?testAnswer = null) { if (Board.Access().Houses < 1) { Console.WriteLine("Sorry, the bank doesn't have any houses left."); return; } if (player.IsInJail) { Console.WriteLine("Sorry, you are in jail."); return; } //create prompt var sPrompt = String.Format("{0}Please select a property to buy a house for:", PlayerPrompt(player)); //create variable for propertyToBuy Residential propertyToBuyFor = null; if (player.GetPropertiesOwnedFromBoard().Count == 0) { //write message Console.WriteLine("{0}You do not own any properties.", PlayerPrompt(player)); //return from method return; } //get the property to buy house for var property = testProperty ?? DisplayPropertyChooser(player.GetPropertiesOwnedFromBoard(), sPrompt); //if dont own any properties //check that it is a residential if (property.GetType() == (new Residential().GetType())) { //cast to residential property propertyToBuyFor = (Residential)property; } else //else display msg { Console.WriteLine("{0}A house can not be bought for {1} because it is not a Residential Property.", this.PlayerPrompt(player), property.GetName()); return; } if (propertyToBuyFor.IsMortgaged) { Console.WriteLine("{0}A house can not be bought for {1} because it is currently mortgaged.", PlayerPrompt(player), property.GetName()); return; } // Player must own all the propeties in the colour group if (!player.OwnsAllPropertiesOfColour(propertyToBuyFor.GetHouseColour())) { Console.WriteLine( "You must own all the properties within this colour group ({0}) to buy houses for this property.", propertyToBuyFor.GetHouseColour()); return; } // We've checked if they own the properties of the colour, now // check if each property is equally developed if (!player.CanDevelopPropertyFurther(propertyToBuyFor)) { Console.WriteLine("Each property in this colour group needs to have houses uniformly added"); } else if (propertyToBuyFor.HasHotel)// If it has a hotel they can't add more houses. { Console.WriteLine("This property has a hotel and can not be developed further."); } else { // Can't buy a fifth house if there are not hotels left if (propertyToBuyFor.GetHouseCount() == 4 && Board.Access().Hotels < 1) { Console.WriteLine("You can't buy another house as this would result in a hotel and there aren't any hotels left."); return; } //confirm var doBuyHouse = testAnswer ?? GetInputYn(player, string.Format("You chose to buy a house for {0}. Are you sure you want to purchase a house for ${1}?", propertyToBuyFor.GetName(), propertyToBuyFor.GetHouseCost())); //if confirmed if (doBuyHouse) { //buy the house propertyToBuyFor.AddHouse(); Console.WriteLine("{0}A new house for {1} has been bought successfully", PlayerPrompt(player), propertyToBuyFor.GetName()); } } }
public void TradeProperty(Player player) { //create prompt string sPropPrompt = String.Format("{0}Please select a property to trade:", this.PlayerPrompt(player)); //create prompt string sPlayerPrompt = String.Format("{0}Please select a player to trade with:", this.PlayerPrompt(player)); //get the property to trade TradeableProperty propertyToTrade = (TradeableProperty)this.DisplayPropertyChooser(player.GetPropertiesOwnedFromBoard(), sPropPrompt); //if dont own any properties if (propertyToTrade == null) { //write message Console.WriteLine("{0}You do not own any properties.", PlayerPrompt(player)); //return from method return; } //get the player wishing to trade with Player playerToTradeWith = this.DisplayPlayerChooser(Board.Access().GetPlayers(), player, sPlayerPrompt); //get the amount wanted string inputAmtMsg = string.Format("{0}How much do you want for this property?", PlayerPrompt(player)); decimal amountWanted = InputDecimal(inputAmtMsg); //confirm with playerToTradeWith //set console color ConsoleColor origColor = Console.ForegroundColor; int i = Board.Access().GetPlayers().IndexOf(playerToTradeWith); Console.ForegroundColor = this._colors[i]; bool agreesToTrade; var mortgageInterest = Decimal.Zero; //get player response /*We need to do this to check and find if the property is mortgaged * and in the case that it is, notify the buyer that the price * of the property includes the original owner's mortgage interest*/ if (propertyToTrade.GetType() == typeof(Residential)) { var residentialPropertyToTrade = (Residential)propertyToTrade; if (residentialPropertyToTrade.IsMortgaged) { mortgageInterest = residentialPropertyToTrade.GetMortgageValue() * 10 / 100; agreesToTrade = GetInputYn(playerToTradeWith, string.Format( "{0} wants to trade '{1}' with you for ${2} (including seller's mortgage interest for this property). Do you agree to pay {2} for '{1}'", player.GetName(), /*{0}*/ propertyToTrade.GetName(), /*{1}*/ amountWanted + mortgageInterest)); /*{2}*/ } else // If it's not mortgaged do the normal trading behaviour { agreesToTrade = GetInputYn(playerToTradeWith, string.Format("{0} wants to trade '{1}' with you for ${2}. Do you agree to pay {2} for '{1}'", player.GetName(), propertyToTrade.GetName(), amountWanted)); } } else { agreesToTrade = GetInputYn(playerToTradeWith, string.Format("{0} wants to trade '{1}' with you for ${2}. Do you agree to pay {2} for '{1}'", player.GetName(), propertyToTrade.GetName(), amountWanted)); } //resent console color Console.ForegroundColor = origColor; if (agreesToTrade) { Player playerFromBoard = Board.Access().GetPlayer(playerToTradeWith.GetName()); //player trades property player.TradeProperty(ref propertyToTrade, ref playerFromBoard, amountWanted, mortgageInterest); Console.WriteLine("{0} has been traded successfully. {0} is now owned by {1}", propertyToTrade.GetName(), playerFromBoard.GetName()); } else { //display rejection message Console.WriteLine("{0}{1} does not agree to trade {2} for ${3}", PlayerPrompt(player), playerToTradeWith.GetName(), propertyToTrade.GetName(), amountWanted); } }