猜数字进阶python代码
时间: 2024-05-20 16:08:59 浏览: 122
猜数字游戏的进阶版可以增加以下功能:
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()
```
阅读全文