python开发一款谜语闯关游戏程序,编写一个RiddleGame类
时间: 2024-03-23 16:40:18 浏览: 16
好的,我可以帮您编写一个RiddleGame类,以下是一个简单的实现:
```python
class RiddleGame:
def __init__(self, riddles):
self.riddles = riddles
self.current_index = 0
self.score = 0
def play(self):
while self.current_index < len(self.riddles):
riddle = self.riddles[self.current_index]
print(riddle["question"])
user_answer = input("Your answer: ")
if user_answer.lower() == riddle["answer"].lower():
print("Correct!")
self.score += 1
else:
print("Wrong answer!")
self.current_index += 1
print(f"Game over! Your final score is {self.score} out of {len(self.riddles)}.")
```
这个类有一个构造函数,接受一个包含谜语的列表,每个谜语包含一个问题和答案。类还有一个play方法,用于开始游戏。在每个回合中,它会打印出当前的问题,并等待玩家输入答案。如果答案正确,得分加一,否则答案被认为是错误的。游戏结束时,会打印出最终得分。
您可以使用以下代码来测试这个类:
```python
riddles = [
{"question": "What has a head and a tail, but no body?", "answer": "coin"},
{"question": "What has four legs in the morning, two legs in the afternoon, and three legs in the evening?", "answer": "human"},
{"question": "What is always in front of you but can’t be seen?", "answer": "future"},
]
game = RiddleGame(riddles)
game.play()
```
这将创建一个包含三个谜语的游戏,并开始游戏。