首页 > 解决方案 > Python猜2个数字游戏

问题描述

问题是

编写一个程序,将两个随机生成的介于 1 和 100 之间的自然数(正整数)的和 (a+b) 和乘积 (a*b) 打印给用户。要赢得游戏,用户必须猜出这两个数字,猜测的顺序应该无关紧要。给用户三个猜测,如果在三个猜测之后他们是错误的,那么数字就会显示给他们。用户必须在单轮中正确猜测两个猜测,并且不会被告知前一轮中的一个数字是否正确。用户有 3 次尝试猜测这两个数字,如果用户猜对了数字,则游戏应该结束。

import random
a = random.randint(1,100)
b = random.randint(1,100)

print("Sum of two random number is",a + b)
print("Product of two random number is", a * b)
print("Try to guess the 2 numbers that make this sum and product, you have 3 tries, good luck!")

count = 0
win = 0

while count != 3:
    guess_a = int(input('Guess first number '))
    guess_b = int(input('Guess second number '))
    
    if count == 3:
        break
        
    if ((guess_a == a) or (guess_b == b)) and ((guess_b == a) or (guess_a == b)):
        win = 1
        break
        
    else:
        count = count + 1
        print('Incorrect!!!')

if win == 1:
    print('Congrats you won the game.')
    
else:
    print('You lost the game.')
    print('Number a was:',a)
    print('Number b was',b)

我试过这个它有点工作,但我不知道如何让猜测数字的顺序无关紧要。

标签: python

解决方案


一种方法是根本不使用布尔值。

由于在条件语句0中自动转换为,因此如果某个条件为真False,我们可以只创建一个等于的表达式。0

我想出的表达是:

is_guess_a_right = (a - guess_a) * (a - guess_b)
is_guess_b_right = (b - guess_a) * (b - guess_b)
are_both_right = is_guess_a_right + is_guess_b_right

如果最终表达式等于 0,那么两个表达式都是正确的,换句话说,guess_a 和guess_b 等于 a 和 b(因为a - guess_a如果它们相同,则等于零)。

最终代码:

import random

a = random.randint(1, 100)
b = random.randint(1, 100)

print("Sum of a and b is %s" % (a + b))
print("Product of a and b is %s" % (a * b))
print("You have three tries to guess the numbers")

count = 0

while count < 3:
    guess_a = int(input("Guess the first number: "))
    guess_b = int(input("Guess the second number: "))

    lose = (guess_a - a) * (guess_a - b) + (guess_b - a) * (guess_b - b)

    if lose:
        print("Try again")
        count += 1
    else:
        print("Congrats, you won the game")
        print("The two numbers were %s and %s" % (a, b))
        break


推荐阅读