jeudi 3 août 2017

Is there any way to reduce the amount of if/else sentences and make my code more efficient?

I'm currently making a small game in Java, where you start by being a simple stickfigure (that i drew in photoshop), and you can purchase items for coins.

Right now there's 3 items you can purchase: a sword, armor, and a helmet.

If you click the checkbox with a sword and press the purchase button, the Image in the ImageView will basically change to a another image (where i just made a new layer on the original stickman in Photoshop, with him holding a sword).

I realised that the more items I'd add to the game, the more endless the posibilities of item combinations would get and I'd end up with too many if/else statements. In pseudocode it'd look something like this, if i keep on doing what I've been doing so far:

    private void loadOwnedItems(){
   String itemsInDB = readFromDB.getItems(SingletonDataValues.getInstance().getId());

   if(itemsInDB.equals("Sword, ")) {
       //insert pic of guy with sword
   }
   else if(itemsInDB.equals("Sword, armor, ")){
       //insert pic of guy with sword and armor
   }
   else if(itemsInDB.equals("Sword, armor, helmet, ")) {
       //pics of guy w/ sword, armor, helmet
   }
   else if(itemsInDB.equals("Armor, ")) {
       //insert pic of armor
   }
   else if(itemsInDB.equals("Armor, helmet, ")) {
       //armor + helmet
   }//and so on...

there is a possibility that the user will buy a sword + helmet, or just a helmet + armor, armor + sword, and so the posibilities becomes too many if i add more items to the game.

Is there a better way to do this, and how would I do it? Any help is greatly appericiated, as I been stuck with this for some days now

Aucun commentaire:

Enregistrer un commentaire