I am currently implementing a text-based version of the game Monopoly for a programming assignment.
I've read loads of times that deeply nesting code is detrimental both to the readability of code and to the whole program's changeability. But when playing Monopoly, there are so many checks that need to be made!
For example, this (incomplete) function displays the title deeds (the card with price, rent and stuff) and allows the player to build houses on a property.
void propertiesSeeBuild(){
//Check whether the player owns any properties by populating a vector
vector<Property*> propertiesOwned;
for(unsigned int i = 0; i < sizeof(board)/sizeof(board[0]); i++){
if(board[i]->getType()=='p'){
Property* p = (Property*)board[i];
if(p->getOwner() == players[currentPlayer])
propertiesOwned.push_back(p);
}
}
//if he (or she) does
if(!propertiesOwned.empty()){
cout << "You own the following properties: " << endl;
for(unsigned int i = 1; i <= propertiesOwned.size(); i++)
cout << i << ". " << propertiesOwned[i-1] << endl;
cout << endl;
cout << "Choose a building to view/upgrade (1-" << propertiesOwned.size()-1 << "): ";
int choice = getIntInput(propertiesOwned.size());
//show the title deeds of the property
propertiesOwned[choice-1]->titleDeeds();
int currentColour = propertiesOwned[choice-1]->getColour();
cout << endl;
cout << "Remember that you can only build houses if you own all the properties in a colour group." << endl;
//and if he/she owns all the properties of that colour group
if(players[currentPlayer].getPropertiesOfColour(currentColour) == propertiesOfColour[currentColour]){
cout << "You currently own all the properties of that colour group, and "
<< propertiesOwned[choice-1]-> getName() << " currently has " << propertiesOwned[choice-1]-> getHouses() << " houses." << endl << endl;
cout << "Do you want to build on this property?" << endl;
//if he/she does
if(takeYesNo() == 'Y'){
//if the number of houses is < 4
if(propertiesOwned[choice-1]-> getHouses() < 4){
cout << "Enter the amount of houses you want to build: ";
int noOfHouses = getIntInput(4 - propertiesOwned[choice-1]-> getHouses()); //this guarantees that there is always less than 4 houses
//if he/she has enough money
if(players[currentPlayer].getBalance() >= noOfHouses * propertiesOwned[choice-1]->getNewHousePrice()){
}
}
}
}
}
}
There's a point where the code is 6 nests deep. Is this bad form? Is there anything I can do to make the code more readable?
Aucun commentaire:
Enregistrer un commentaire