麻烦你再次帮我修改,让游戏最开始时除了1和2都是非法输入import randomdef run(): cpu_score = 0 player_score = 0 while True: choices = ["石头", "布", "剪刀"] computer = random.choice(choices) player = input("石头,剪刀或布?") if player == computer: print('电脑输出了:{}'.format(computer)) print("打平了!") elif player == "石头": if computer == "布": print('电脑输出了:{}'.format(computer)) print("你输了...") cpu_score += 1 else: print('电脑输出了:{}'.format(computer)) print("你赢了!") player_score += 1 elif player == "布": if computer == "剪刀": print('电脑输出了:{}'.format(computer)) print("你输了...") cpu_score += 1 else: print('电脑输出了:{}'.format(computer)) print("你赢了!") player_score += 1 elif player == "剪刀": if computer == "石头": print('电脑输出了:{}'.format(computer)) print("你输了...") cpu_score += 1 else: print('电脑输出了:{}'.format(computer)) print("你赢了!") player_score += 1 elif player == '2': print("最终得分:") print(f"电脑得分:{cpu_score}") print(f"你的得分:{player_score}") with open('score.txt', 'w') as f: f.write(str(player_score)) break else: print("输入错误,请检查你的输入")if name == 'main': with open('score.txt', 'r') as f: last_score = f.read() print(f"上次游戏得分:{last_score}") m = input("开始游戏请输入:1\n结束游戏请输入:2\n") run()
时间: 2024-02-13 21:05:54 浏览: 122
以下是修改后的代码,满足你的要求:
```
import random
def run():
cpu_score = 0
player_score = 0
while True:
choices = ["石头", "布", "剪刀"]
computer = random.choice(choices)
player = input("石头,剪刀或布?")
if player == '1' or player == '2':
if player == '2':
print("最终得分:")
print(f"电脑得分:{cpu_score}")
print(f"你的得分:{player_score}")
with open('score.txt', 'w') as f:
f.write(str(player_score))
break
else:
print("非法输入,请重新输入")
continue
elif player not in choices:
print("非法输入,请重新输入")
continue
print('电脑输出了:{}'.format(computer))
if player == computer:
print("打平了!")
elif player == "石头":
if computer == "布":
print("你输了...")
cpu_score += 1
else:
print("你赢了!")
player_score += 1
elif player == "布":
if computer == "剪刀":
print("你输了...")
cpu_score += 1
else:
print("你赢了!")
player_score += 1
elif player == "剪刀":
if computer == "石头":
print("你输了...")
cpu_score += 1
else:
print("你赢了!")
player_score += 1
if __name__ == 'main':
with open('score.txt', 'r') as f:
last_score = f.read()
print(f"上次游戏得分:{last_score}")
m = input("开始游戏请输入:1\n结束游戏请输入:2\n")
run()
```
修改的部分主要是在输入非法情况下的处理。当输入为1或2时,需要判断是否为合法输入,如果不是则要求重新输入,否则继续执行游戏。同时,当输入的不是石头、剪刀或布时,也要求重新输入。
阅读全文