How to avoid writing a lot of "IF"? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, September 21, 2023

How to avoid writing a lot of "IF"?

I have a Hearthstone (card game) deckbuilder, which works fine, but I want to add the "subtype" automatically, so users can make their decks even quicker.

Some cards have races or spell types and this can make the subtype. E.g.: If the deck has more than 5 Demon race typed cards, then it'll be the deck's subtype, but the deck can have more subtypes (after saving the deck, the user can change, if he doesn't like the subtype chosen by the code).

So, if the deck has 10 demons and 10 pirates, then I save the following into the subtype SQL column: "demon,pirate". It's all good, but the implementation isn't nice.

So let me share some code with you: I'm looping through all the cards in the deck...

if((strpos($card['race'], 'Demon') !== false))
{
   $demon++;
   if($demon >= 6)
   {
      $subtype[0] = 'Demon';
   }
}
if((strpos($card['race'], 'Pirate') !== false))
{
   $pirate++;
   if($pirate >= 6)
   {
      $subtype[1] = 'Pirate';
   }
}

Now I think you can see my problem. If we have 10 different races, then it's 10 "IF", if we have 100, then it's 100 "IF". What should I do?

I was thinking about an array. To do something like this in the loop:

$subtype = array();
if(!empty($card['race']))
{
   array_push($subtype,$card['race']);
}

After the loop goes through all the cards, I would do this:

sort($subtype); //just to look nice
$count = array_count_values($subtype);
print_r($count);

Then my knowledge stops here. How can I work with this? I get the result like this:

Array
(
    [Demon] => 6
    [Murloc] => 4
    [Pirate] => 8
)

I want to save to my subtype variable, if it's more than 5. How do I put "Demon" and "Pirate" into a variable? The end result would be:

$subtype = "Demon,Pirate"


source https://stackoverflow.com/questions/77145140/how-to-avoid-writing-a-lot-of-if

No comments:

Post a Comment