Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better alternative to lots of IF statements? Table of values

I have a table of moves that decide whether or not the player wins based on their selection against the AI. Think Rock, Paper, Scissors with a lot more moves. I'll be eventually coding it in Python, but before I begin, I want to know if there is a better way of doing this rather than LOTS and LOTS of IF statements?

The table looks like this:

enter image description here

I'm thinking that the moves will need to be assigned numbers, or something like that? I don't know where to start...

like image 666
Jason Avatar asked Aug 16 '16 11:08

Jason


People also ask

What can I use instead of multiple if statements?

To test multiple conditions and return different values based on the results of those tests, you can use the CHOOSE function instead of nested IFs. Build a reference table and a use VLOOKUP with approximate match as shown in this example: VLOOKUP instead of nested IF in Excel.

What can I use instead of multiple if statements in python?

Take Advantage of the Boolean Values. There's no need to have the if/else statements. Instead, we can use the boolean values. In Python, True is equal to one , and False is equal to zero .

How do you make an if statement more efficient?

Efficient if-else StatementsWhile in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.


1 Answers

You could use a dict? Something like this:

#dict of winning outcomes, the first layer represents the AI moves, and the inner 
#layer represent the player move and the outcome
ai = {
    'punch' : {
        'punch' : 'tie',
        'kick' : 'wins',
    },
    'stab' : {
        'punch' : 'loses',
        'kick' : 'loses'
    }
}

ai_move = 'punch'
player_move = 'kick'
print ai[ai_move][player_move] #output: wins


ai_move = 'stab'
player_move = 'punch'
print ai[ai_move][player_move] #output: loses

I didn't map out all the moves, but you get the gist

like image 134
dheiberg Avatar answered Nov 14 '22 23:11

dheiberg