猜数游戏是一个简单的交互式游戏,在该游戏中,计算机随机选择一个数字,然后玩家必须猜测这个数字。如果玩家的猜测大于计算机选择的数字,计算机会提示玩家猜测更小的数字;如果玩家的猜测小于计算机选择的数字,计算机会提示玩家猜测更大的数字。总共有6次猜测机会。
解决思路:
一、定义3个数
玩家猜的数:guess
随机生成数:secret
玩家猜次数:tries二、游戏中(当没有猜中及次数<=6):
输入:guess=int(input())
处理:猜的数与随机生成数比较
输出:当猜的数大于随机生成数,提示……;当猜的数小于随机生成数,提示……
继续游戏
三、游戏结束:
当猜中时,游戏结束。
当次数用完时,游戏结束。
代码示例:
import random
secret = random.randint(1, 99) # 选一个秘密数
tries = 0
guess = 0
print("""
AHOY! I'm the Dread Pirate Roberts,and I hava a secret!
It is a number from 1 to 99. I'll give you 6 tries.
""")
while guess != secret and tries < 6: # 0~5,最多允许猜6次
guess = int(input("what's your guess?")) # 得到玩家猜的数
if guess < secret:
print("Too low,you scurvy dog!")
elif guess > secret:
print("Too high,landlubber!")
tries += 1 # 用掉一次机会
# 游戏结束时打印信息
if guess == secret:
print("Avast! you got it! Found my secret,you did")
else:
print("No more guesses! Better luck next time, matey!")
print("The secret number was", secret)