将猜数字游戏封装为函数GuessSecret(maxtimes),将允许猜数字的最大次数maxtimes作为参数。在调用GuessSecret时允许用户自己设置maxtimes。
时间: 2023-12-10 22:38:20 浏览: 52
好的,下面是将猜数字游戏封装为函数GuessSecret(maxtimes)的代码:
```python
import random
def GuessSecret(maxtimes):
secret = random.randint(1,100)
print("Welcome to Guess the Secret Number Game!")
print("You have", maxtimes, "tries to guess the number.")
for i in range(maxtimes):
guess = int(input("Enter your guess (1-100): "))
if guess == secret:
print("Congratulations! You guessed the secret number in", i+1, "tries.")
return
elif guess < secret:
print("Your guess is too low.")
else:
print("Your guess is too high.")
print("Sorry, you failed to guess the secret number in", maxtimes, "tries. The secret number was", secret)
```
在这个函数中,我们使用了Python内置的`random`模块来生成一个1-100之间的随机数作为秘密数字。然后,我们打印欢迎信息和提示用户他们有多少次猜测的机会。接下来,我们使用一个`for`循环来让用户猜数字,直到他们猜对了或猜了最大次数。如果用户猜对了,我们打印一条祝贺信息并结束函数。如果用户没有猜对,我们根据他们的猜测告诉他们秘密数字是太高还是太低,然后继续循环。如果用户用完了所有的猜测机会,我们打印一条失败消息并结束函数。
现在,你可以调用这个函数并传入一个最大猜测次数:
```python
GuessSecret(5) # 这里设置最大猜测次数为5次
```
输出:
```
Welcome to Guess the Secret Number Game!
You have 5 tries to guess the number.
Enter your guess (1-100): 50
Your guess is too high.
Enter your guess (1-100): 25
Your guess is too low.
Enter your guess (1-100): 37
Your guess is too high.
Enter your guess (1-100): 31
Your guess is too high.
Enter your guess (1-100): 28
Congratulations! You guessed the secret number in 5 tries.
```