Alex - 4 months ago 18

Python Question

i am making a game that will sort out the risk dice rolling but i can only get it to compare the last two numbers and tell me who has won but i want it to order the numbers then compare the top numbers from each set ( like in a normal risk game)

here is my code

`import random`

import time

from random import randrange

from random import randint

r = randint

min = 1

max = 6

def main():

print("Welcome to risk dice")

playing = input("Press Enter to Roll or Q to quit")

if playing == 'q':

print("Thanks for Playing")

time.sleep(2)

quit()

elif playing != 'q':

rolls = int(float(input('how many soliders are you attacking with:')))

for x in range(rolls):

print ('you got a...')

a = (r(min, max))

print(a)

rolls = int(float(input('how many soliders are you defending with:')))

for x in range(rolls):

print ('you got a...')

d = (r(min, max))

print(d)

if d >= a:

print('defence wins')

else:

print('attackers win')

main()

main()

any ideas are welcome im completely stuck (im using python 3.4.4)

Answer

```
attacker_dice = []
defender_dice = []
```

Initialize empty arrays to put the dice in as we roll them.

```
rolls = int(float(input('how many soliders are you attacking with:')))
for x in range(rolls):
print ('you got a...')
attacker_dice.append(r(min, max))
print(attacker_dice[-1])
```

Here we `append`

the new values to the arrays, which adds them to the end. Then, we print the number at index `[-1]`

which is the last item.

```
attacker_dice.sort(reverse=True)
defender_dice.sort(reverse=True)
```

Once we have the arrays, we sort (from high to low)

```
paired_dice = zip(attacker_dice, defender_dice)
```

Then, we pair the dice with zip. Zip by default drops any dice that can't be paired. This mirrors the Risk rules, that you drop the lowest unpaired dice.

```
attacker_wins = 0
defender_wins = 0
for pair in paired_dice:
attacker, defender = pair
```

Here we unpack the dice: `for pair in paired_dice`

loops between each pair. `attacker, defender = pair`

unpacks the pairs into their component dice.

```
if attacker > defender:
attacker_wins += 1
else:
defender_wins += 1
```

It's important to note for Risk, `attacker_wins`

is how many armies the **defender loses** and vice versa.

This example works on repl.it. Since the input in not constrained, I tested it to 50 on 50 and it works just fine.