我是Python新手,只写过几个程序。这是我最近为一个“石头剪子”游戏编写的代码。我已经测试过了,效果很好。有什么方法可以简化它吗?谢谢!
import random
wins=0
losses=0
ties=0
rounds=0
r=1 #rock
p=2 #paper
s=3 #scissors
y = "The computer has made its choice, how about you?"
while rounds <= 10:
print y
x = input('(1)rock, (2)paper, or (3)scissors? :')
choice = x
cpu_choice= random.randint(1, 3)
if (choice, cpu_choice) == (1, 2):
rounds += 1
losses += 1
print 'computer chose paper, you lose'
elif (choice, cpu_choice) == (3, 2):
print 'you win'
rounds += 1
wins += 1
elif (choice, cpu_choice) == (2, 2):
print 'TIE!'
rounds += 1
ties += 1
elif (choice, cpu_choice) == (1, 3):
print 'you win'
rounds += 1
wins += 1
elif (choice, cpu_choice) == (3, 3):
print 'TIE!'
rounds += 1
ties += 1
elif (choice, cpu_choice) == (2, 3):
print 'computer chose scissors, you lose'
rounds += 1
losses += 1
elif (choice, cpu_choice) == (1, 1):
print 'TIE'
rounds += 1
ties += 1
elif (choice, cpu_choice) == (3, 1):
print 'computer chose rock, you lose'
rounds += 1
losses += 1
elif (choice, cpu_choice) == (2, 1):
print 'you win'
rounds += 1
wins += 1
else:
print 'Please choose 1, 2, or 3'
print 'Game Over'
if wins>losses:
print 'YOU WON'
print 'wins:' , wins
print 'losses' , losses
print 'ties' , ties
else:
print 'you lose'
print 'wins:' , wins
print 'losses:' , losses
print 'ties:' , ties
一些建议:
除数据输入错误外,所有有条件的情况都包含舍入变量递增,因此您可以将舍入+=1行带出上限,在其他情况下,只减除一次舍入变量
你有做同样工作的if案例,例如when'TIE!'是的,最好把这样的案子归类打领带案例可以在一个条件下分组choice==cpu_choice从而操作3个elif子句。在其他游戏案例中考虑同样的问题。
使用更好的代码格式,例如PEP-8标准建议的格式。
虽然stackoverflow并不是真正意义上的学习平台,但这里有一些建议:
import this
)。至少,所有的连接条件都可以放在一起:
输入一些语法:
实际上,只有三个条件:
而且,您甚至不使用上面定义的变量
p
、r
和s
。。。。您可以使用模运算确定玩家是否获胜:
相关问题 更多 >
编程相关推荐