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:
I'm thinking that the moves will need to be assigned numbers, or something like that? I don't know where to start...
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With