石头,纸,剪刀Python代码。帮助简化

2024-04-24 00:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

Tags: youcpucomputerpaperprintscissorsrockchoice
3条回答

一些建议:

  1. 除数据输入错误外,所有有条件的情况都包含舍入变量递增,因此您可以将舍入+=1行带出上限,在其他情况下,只减除一次舍入变量

  2. 你有做同样工作的if案例,例如when'TIE!'是的,最好把这样的案子归类打领带案例可以在一个条件下分组choice==cpu_choice从而操作3个elif子句。在其他游戏案例中考虑同样的问题。

  3. 使用更好的代码格式,例如PEP-8标准建议的格式。

虽然stackoverflow并不是真正意义上的学习平台,但这里有一些建议:

  • 读取ZEN(在python控制台中键入import this)。
  • 在你的特殊情况下,很多条件通常是个坏主意。

至少,所有的连接条件都可以放在一起:

 if choice == cpu_choice:
    # TIE

输入一些语法:

names = ['rock', 'paper', 'scissors']
print("Computer chooses {}, you loose".format(names[cpu_choice]))

实际上,只有三个条件:

wins, losses = 0, 0

for round in range(10):

    # Your choice and CPU choice

    cpu_wins = (cpu_choice > choice or (choice == 3 and cpu_choice == 1))
    tie = (cpu_choice == choice)

    if cpu_wins:
        # You loose
        print("Computer chooses {}, you loose".format(names[cpu_choice]))
        losses += 1
    if not cpu_wins and tie:
        # tie
    else:
        # you win

而且,您甚至不使用上面定义的变量prs。。。。

您可以使用模运算确定玩家是否获胜:

player_result = ["tie", "win", "lose"]
player_choice = input('(1)rock, (2)paper, or (3)scissors? :')
cpu_choice= random.randint(1, 3)
result = player_result[(player_choice - cpu_choice) % 3]

print "You " + result
if result == "win":
    wins += 1
elif result == "lose":
    loses += 1

相关问题 更多 >