猜数字python代码
时间: 2024-11-05 10:08:43 浏览: 8
猜数字游戏是一个常见的Python练习项目,通常通过随机生成一个数字让用户尝试猜测。以下是一个简单的猜数字游戏的Python代码示例:
```python
import random
def guess_number():
number_to_guess = random.randint(1, 100) # 随机选择一个1到100之间的整数
attempts = 0 # 初始化尝试次数
while True:
print(f"欢迎来到猜数字游戏!我想了一个1到100的数字,请你猜一猜是多少?")
user_guess = int(input("请输入你的猜测: "))
attempts += 1
if user_guess < number_to_guess:
print("太小了!再试一次。")
elif user_guess > number_to_guess:
print("太大了!再试试。")
else:
print(f"恭喜你,猜对了!你在第{attempts}次就猜到了.")
break
guess_number()
```
在这个游戏中,用户会不断输入他们猜测的数字,直到猜对为止。每个猜测都会得到提示是“太小了”、“太大了”,直到用户猜对数字。
相关问题
猜数字游戏python代码
好的,下面是一个简单的猜数字游戏的Python代码:
```python
import random
# 生成随机数
number = random.randint(1, 100)
# 定义猜数字的函数
def guess_number():
guess = int(input("请输入一个1到100之间的整数:"))
if guess == number:
print("恭喜你,猜对了!")
elif guess < number:
print("猜的数字太小了,再试一次吧。")
guess_number()
else:
print("猜的数字太大了,再试一次吧。")
guess_number()
# 调用猜数字的函数
guess_number()
```
这个代码中,我们使用了`random`模块生成了一个1到100之间的随机整数,然后定义了一个猜数字的函数`guess_number()`。在函数中,我们通过`input()`函数获取用户输入的数字,然后与生成的随机数进行比较,如果相等则输出“恭喜你,猜对了!”;如果猜的数字太小,则递归调用`guess_number()`函数并提示“猜的数字太小了,再试一次吧。”;如果猜的数字太大,则同样递归调用`guess_number()`函数并提示“猜的数字太大了,再试一次吧。”。最后,在程序的最后一行调用`guess_number()`函数,开始游戏。
猜数字进阶python代码
猜数字游戏的进阶版可以增加以下功能:
1. 增加难度级别,例如:easy, medium, hard,分别对应不同的数字范围和猜测次数。
2. 增加计时功能,限制猜测时间。
3. 增加记录功能,记录玩家最好成绩,可以保存在文件中。
4. 增加提示功能,例如:提示数字范围、提示剩余猜测次数等。
下面是一个简单的猜数字进阶版Python代码:
```
import random
import time
class GuessNumber:
def __init__(self):
self.name = ''
self.number = 0
self.guesses = 0
self.time_limit = 0
def set_difficulty(self):
print('Please select a difficulty level:')
print('1. Easy (1-10, 5 guesses)')
print('2. Medium (1-50, 10 guesses)')
print('3. Hard (1-100, 15 guesses)')
level = input('Enter your choice (1, 2, or 3): ')
if level == '1':
self.number = random.randint(1, 10)
self.guesses = 5
self.time_limit = 10
elif level == '2':
self.number = random.randint(1, 50)
self.guesses = 10
self.time_limit = 20
elif level == '3':
self.number = random.randint(1, 100)
self.guesses = 15
self.time_limit = 30
def get_name(self):
self.name = input('Please enter your name: ')
def play(self):
print(f'Welcome, {self.name}! You have {self.guesses} guesses to guess the number.')
start_time = time.time()
for i in range(self.guesses):
guess = int(input('Enter your guess: '))
if guess < self.number:
print('Too low!')
elif guess > self.number:
print('Too high!')
else:
end_time = time.time()
print(f'Congratulations, {self.name}! You guessed the number in {i+1} guesses and {end_time-start_time:.2f} seconds.')
return True
print(f'Sorry, {self.name}, you ran out of guesses. The number was {self.number}.')
return False
def save_record(self, record_file):
with open(record_file, 'a') as f:
f.write(f'{self.name}, {self.guesses-self.remaining_guesses}, {time.time()-self.start_time:.2f}\n')
def show_record(self, record_file):
with open(record_file, 'r') as f:
records = f.readlines()
records = [r.strip().split(', ') for r in records]
records.sort(key=lambda x: float(x))
print('--- Best Records ---')
for r in records[:5]:
print(f'{r}: {r} guesses in {r} seconds')
def start(self):
record_file = 'guess_number_records.txt'
self.get_name()
while True:
self.set_difficulty()
result = self.play()
if result:
self.save_record(record_file)
command = input('Enter "q" to quit or "r" to show records: ')
if command == 'q':
break
elif command == 'r':
self.show_record(record_file)
if __name__ == '__main__':
game = GuessNumber()
game.start()
```
阅读全文