用 python 写一个控制台游戏
时间: 2023-12-22 16:05:05 浏览: 28
好的,我可以给你一个控制台猜数字游戏的代码示例:
```python
import random
secret_number = random.randint(1, 100)
guesses = 0
max_guesses = 10
print("I'm thinking of a number between 1 and 100. Can you guess what it is?")
while guesses < max_guesses:
guess = input("Enter your guess: ")
guesses += 1
try:
guess = int(guess)
except ValueError:
print("Invalid input. Please enter a number.")
continue
if guess < secret_number:
print("Too low.")
elif guess > secret_number:
print("Too high.")
else:
print("Congratulations! You guessed the number in", guesses, "guesses.")
break
if guesses == max_guesses:
print("Sorry, you ran out of guesses. The number was", secret_number)
```
这个游戏会随机生成一个 1 到 100 之间的数字,然后让玩家在 10 次机会内猜出这个数字。每次玩家猜完后,程序会告诉他猜的数字是太高还是太低,直到猜中为止。如果玩家用完了 10 次机会仍然没有猜中,游戏就结束,显示正确的数字。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)