给我代码实现,具体需求:1.猜的数字在1到100之间并且在60秒内要猜出来;2.能够生成玩家玩游戏的记录,包括:日期、时间、成绩等信息;3.记录游戏玩家各方的历史成绩、当前成绩、最好成绩
时间: 2024-02-07 13:01:58 浏览: 68
java实现的简单猜数字游戏代码
好的,以下是实现上述需求的 Python 猜数字游戏代码:
```python
import random
import datetime
class GuessNumber:
def __init__(self):
self.secret_number = random.randint(1, 100)
self.start_time = datetime.datetime.now()
self.end_time = None
self.attempts = 0
self.records = []
def check_number(self, guess):
self.attempts += 1
if guess == self.secret_number:
self.end_time = datetime.datetime.now()
time_taken = (self.end_time - self.start_time).total_seconds()
self.records.append((self.start_time, self.end_time, time_taken, self.attempts))
return True
elif guess < self.secret_number:
print("Too low!")
else:
print("Too high!")
return False
def print_records(self):
print("Game Records:")
for record in self.records:
print("-" * 20)
print(f"Start Time: {record[0]}")
print(f"End Time: {record[1]}")
print(f"Time Taken: {record[2]:.2f} seconds")
print(f"Attempts: {record[3]}")
def print_stats(self):
print("Game Stats:")
print(f"Current Score: {self.attempts}")
if self.records:
best_score = min(record[3] for record in self.records)
print(f"Best Score: {best_score}")
last_score = self.records[-1][3]
print(f"Last Score: {last_score}")
else:
print("No records yet.")
game = GuessNumber()
print("Welcome to the Guess Number game!")
print("You have 60 seconds to guess the number between 1 and 100.")
print("Enter 'exit' to quit the game.")
while True:
guess = input("Enter your guess: ")
if guess == 'exit':
print("Thanks for playing!")
break
elif not guess.isnumeric():
print("Invalid input!")
continue
guess = int(guess)
if game.check_number(guess):
print(f"Congratulations! You guessed the number in {game.attempts} attempts!")
game.print_stats()
game.print_records()
break
else:
if (datetime.datetime.now() - game.start_time).total_seconds() >= 60:
print("Time's up! Game over.")
game.print_stats()
game.print_records()
break
```
解释:
- `GuessNumber` 类是游戏的主要逻辑,包括生成随机数字、检查猜测、记录成绩等方法。
- `check_number` 方法检查玩家猜的数字是否正确,并记录尝试次数和时间。
- `print_records` 方法打印游戏记录。
- `print_stats` 方法打印游戏玩家的历史成绩、当前成绩、最好成绩。
- 游戏主程序使用 `while` 循环,实现玩家可以多次尝试猜数字的功能,同时也会在时间到期或者玩家退出游戏时结束程序。
阅读全文