This is the seventh day of my participation in the First Challenge 2022. For details: First Challenge 2022.

We’ve already looked at the use of logical judgments and loops, and we’ve also talked about word games. Now let’s try to improve on the number games we talked about last time.

Let’s try to write down the logic behind buying size, a popular game in macau casinos. Buy hours, points are 3<= total <=10, large is 11<= total <=18.

First, we’ll build a function for rolling dice, roll_dice.

Import random def roll_dice(numbers=3,points=None): print(' start rolling dice! ') if points is None: points = [] while numbers > 0: Point = random. Randrange (1,7) points. Append (point) numbers = numbers -1 return pointsCopy the code

As you can see below, I used print instead of return at the end of the loop because return does not show the contents of points.

So now that we have three points, we have to figure out how big these three numbers add up to. We’ll use the if statement to define the size:


def roll_result(total):
    big = 11 <= total <= 18
    small = 3 <= total <= 10
    if big:
        return 'Big'
    elif small:
        return 'Small'
Copy the code

With size rules in place, you now need to design a function that starts the game, asks the user to guess the size, and outputs whether the guess is true or false. We store the user’s guesses in your_choices, call roll_dice, name the return value points, perform the summation, call roll_result, and set the victory condition.

Def game(): print(" guess size game start!" ) choices = ['Big','Small'] your_choices = input('Please enter Big or Small :') if your_choices in choices: points = roll_dice() total = sum(points) win = your_choices == roll_result(total) if win: print('you win',points) else: Print ('you lose',points) else: print('you lose',points)Copy the code

Let’s see what the full code execution looks like:

We used a mixture of loops and judgments to design this little game. And then there’s the sum function, which I won’t explain too much, which is a built-in python function that sums lists and returns the result. For example,

List = [1, 2, 3] print (sum (list))Copy the code

The following output is displayed: