请你用python写一份有关是石头剪刀布代码,用文件读写记录最佳成绩
时间: 2024-02-13 10:02:21 浏览: 62
python石头剪刀布
好的,以下是一个简单的石头剪刀布游戏代码,同时会将最佳成绩保存在文件中:
```python
import random
# 定义游戏规则
rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
# 读取最佳成绩
try:
with open('best_score.txt', 'r') as f:
best_score = int(f.read())
except:
best_score = 0
# 游戏开始
print('Welcome to the game of rock-paper-scissors!')
print(f'Your best score is {best_score}.\n')
while True:
# 玩家出拳
player_choice = input('Please input your choice (rock/scissors/paper): ')
while player_choice not in rules.keys():
player_choice = input('Invalid input, please input again: ')
# 电脑出拳
computer_choice = random.choice(list(rules.keys()))
# 判断胜负
if rules[player_choice] == computer_choice:
print(f'You win! The computer chose {computer_choice}.')
best_score = max(best_score, 1)
elif rules[computer_choice] == player_choice:
print(f'You lose! The computer chose {computer_choice}.')
else:
print(f'It is a tie! The computer also chose {computer_choice}.')
# 询问是否继续游戏
play_again = input('Do you want to play again? (y/n): ')
while play_again.lower() not in ['y', 'n']:
play_again = input('Invalid input, please input again: ')
if play_again.lower() == 'n':
break
# 保存最佳成绩
with open('best_score.txt', 'w') as f:
f.write(str(best_score))
```
这个代码实现了一个简单的石头剪刀布游戏,并且会将最佳成绩保存在文件`best_score.txt`中。每次游戏开始前会从文件中读取最佳成绩,游戏结束后如果本次得分超过最佳成绩,则会更新最佳成绩并保存到文件中。
阅读全文