用python写一份代码,内容为“石头剪刀布”的游戏,要求用户注册功能,加个文件读写,把用户的信息和猜数次数,成功失败次数都记录下来,还能给个榜单,搞个准确率排行榜
时间: 2023-11-21 08:06:19 浏览: 59
python基础教程之实现石头剪刀布游戏示例-电脑资料.pdf
好的,我可以帮你实现这个游戏,以下是代码:
```python
import random
class Game:
def __init__(self):
self.user_data = {} # 创建用户数据字典
self.load_data() # 加载已有数据
def load_data(self):
try:
with open('user_data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
user, wins, loses, draws, guesses = line.strip().split(',')
self.user_data[user] = {'wins': int(wins), 'loses': int(loses), 'draws': int(draws), 'guesses': int(guesses)}
except:
pass
def save_data(self):
with open('user_data.txt', 'w') as f:
for user, data in self.user_data.items():
f.write(f"{user},{data['wins']},{data['loses']},{data['draws']},{data['guesses']}\n")
def register(self):
while True:
user = input('请输入用户名: ')
if user in self.user_data:
print('该用户已存在,请重新输入')
else:
self.user_data[user] = {'wins': 0, 'loses': 0, 'draws': 0, 'guesses': 0}
print(f"用户 {user} 注册成功")
break
def play(self):
while True:
user = input('请输入用户名: ')
if user not in self.user_data:
print('该用户不存在,请注册后再进行游戏')
continue
guess = input('请输入你的选择(石头/剪刀/布): ')
if guess not in ['石头', '剪刀', '布']:
print('输入有误,请重新输入')
continue
computer_guess = random.choice(['石头', '剪刀', '布'])
print(f"电脑出招: {computer_guess}")
if guess == computer_guess:
print('平局')
self.user_data[user]['draws'] += 1
elif (guess == '石头' and computer_guess == '剪刀') or (guess == '剪刀' and computer_guess == '布') or (guess == '布' and computer_guess == '石头'):
print('你赢了')
self.user_data[user]['wins'] += 1
else:
print('你输了')
self.user_data[user]['loses'] += 1
self.user_data[user]['guesses'] += 1
self.save_data()
play_again = input('是否继续游戏(y/n): ')
if play_again.lower() == 'n':
break
def leaderboard(self):
sorted_data = sorted(self.user_data.items(), key=lambda x: x[1]['wins']/(x[1]['wins']+x[1]['loses']), reverse=True)
print('排行榜:')
for i, (user, data) in enumerate(sorted_data):
print(f"{i+1}. 用户名: {user}, 准确率: {data['wins']/(data['wins']+data['loses']):.2f}")
if __name__ == '__main__':
game = Game()
while True:
choice = input('请选择功能(1.注册,2.游戏,3.排行榜,4.退出): ')
if choice == '1':
game.register()
elif choice == '2':
game.play()
elif choice == '3':
game.leaderboard()
elif choice == '4':
break
else:
print('输入有误,请重新输入')
```
这个游戏包含注册、猜拳、保存数据、排行榜等功能。用户数据保存在 `user_data.txt` 文件中,每个用户对应一行,格式为 `用户名,胜利次数,失败次数,平局次数,猜数次数`。排行榜按照准确率(胜利次数/总次数)从高到低排序。
阅读全文