import random def 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}") f=open('scroe.txt',"w") f.write(str(player_score)) f.close() break else: print("输入错误,请检查你的输入") if name == 'main': m = input("开始游戏请输入:1\n结束游戏请输入:2\n") run(). 这个代码还存在一些问题,请你帮我改一下
时间: 2024-02-13 20:05:41 浏览: 61
剪刀石头布:剪刀石头布游戏
在你的代码中,存在以下问题:
1. `if name == 'main':` 这个判断条件可能不正确,应该是 `if __name__ == '__main__':`。
2. `run().` 这句代码不应该有括号,应该写成 `run()`。
3. 在游戏结束后,你将得分写入文件的代码没有必要放在 while 循环中。应该在游戏结束后将得分写入文件。
下面是修改后的代码:
```python
import random
def 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__':
m = input("开始游戏请输入:1\n结束游戏请输入:2\n")
run()
```
另外,你需要注意代码的缩进,因为 Python 是通过缩进来区分代码块的。我修改的代码中已经对缩进进行了修正。
阅读全文