2019-07-11 13:23:57

So I am trying to create a pig like game in python and I am trying to make a computer player I figured this code but can't seam to get it to make the rolls the number of times. So fore example I want to make it so if the computer rolls a 2 then I want it to roll again until the number of rolls gets to 10. I hope that made sense. So if the computer rolls a 6 then I want the computer to roll 3 times and add 1 until it gets to 10 and then pass back to you. Here is my code that I got so fare to test the AI.
import random
import sys
def bot():
    dice = random.randint(1,6)
    print("Computer rolled ")
    print(dice)
    rolls=dice+1
    if rolls == 10:
        sys.exit()
while 1:
    bot()
Do I need to have another random roll statement fore the rolls? The dice is supposed to be fore the score.

Bitcoin Address:
1MeNca7h6m8du4TV3psN4m4X666p6Y36u5m

2019-07-11 15:38:48 (edited by amerikranian 2019-07-11 15:40:09)

The reason why your code is not working as you expected to, is because you declare your roles inside the function.  This means that the variable roles is re-created every time the function gets called. To fix this, do one of the following:
One: after your import statements, set the variable rolls to zero.  In your function, type in this line:
global rolls
This basically tells the interpreter to not bother with creating a new variable.  Instead, the interpreter will try and find the variable called rolls outside of your function.
Two:  modify your while loop.  Stop calling the bot function over and over again. Instead, have your dice rolls simulated within that loop.  Since the function will stop executing after the loop is over, you can safely rely on roles created within the function to do its job. This is the approach that I would use.
I would also look up name space tutorials in python, they can save you a lot of headache.