在这里,我为你修好了。
我试图模仿你的风格,并尽可能保持原状,以便让你看到 werde 做出了哪些改变。也就是说:通常不鼓励这种风格,请参阅 jadkik94 的答案以获得更好的风格。也许我稍后会在编辑中重写这个程序。如果我有时间。
import random
CpuChoices=['Rock','Paper','Scissors']
PlayerChoices = dict(zip("RPS", CpuChoices))
UserScore=0
CpuScore=0
Games=0
while Games<6:
UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)')
if UserChoice not in PlayerChoices: continue
CpuChoice = random.choice(CpuChoices)
if UserChoice=='S' and CpuChoice=='Paper':
UserScore+=1
elif UserChoice=='P' and CpuChoice=='Rock':
UserScore+=1
elif UserChoice=='R' and CpuChoice=='Scissors':
UserScore+=1
if UserChoice=='S' and CpuChoice=='Rock':
CpuScore+=1
elif UserChoice=='P' and CpuChoice=='Scissors':
CpuScore+=1
elif UserChoice=='R' and CpuChoice=='Paper':
CpuScore+=1
print("CPU chose %s against your %s" % (CpuChoice, PlayerChoices[UserChoice]))
print("User: %s - CPU: %s" % (UserScore, CpuScore))
Games += 1
if UserScore > CpuScore:
print('Well done, you won!')
if UserScore == CpuScore:
print('You tied!')
if UserScore < CpuScore:
print('Unlucky, you lost.')
print("the only winning move it not to play")
正如所承诺的,这是我编写它的代码(嗯,不是真的,但是......你明白了):
import random
class RSPHand(object):
names = ('Rock', 'Paper', 'Scissors')
beats = {
'Rock': 'Scissors',
'Scissors': 'Paper',
'Paper': 'Rock',
}
def __init__(self, name):
if name not in self.__class__.names:
try:
name = [n for n in self.__class__.names if n[0] == name.upper()][0]
except IndexError:
raise ValueError ("Name not valid")
self.name = name
self.shortname = self.name[0]
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self.name)
def __str__(self):
return self.name
def __gt__(self, other):
return other.name == self.__class__.beats[self.name]
def __lt__(self, other):
return self.name == self.__class__.beats[other.name]
choices=[]
for name in RSPHand.names:
choices.append(RSPHand(name))
playerscore = cpuscore = 0
while True:
rounds = input("Best out of how many rounds? ")
try:
rounds = int(rounds)
except ValueError:
continue
break
while rounds:
playerchoice = input("%s? (Type first letter, lowercase or not, or full name) " % [choice.name for choice in choices])
try:
playerchoice = RSPHand(playerchoice)
except ValueError:
continue
cpuchoice = random.choice(choices)
print ("CPU chose %s against your %s" % (cpuchoice, playerchoice))
if playerchoice < cpuchoice:
cpuscore += 1
print("too bad for you")
elif playerchoice > cpuchoice:
playerscore += 1
print("too bad for CPU")
else:
print("that's a tie for this round")
print ("CPU: %s - Player: %s" % (cpuscore, playerscore))
rounds -= 1
if playerscore > cpuscore:
print('Well done, you won!')
elif playerscore == cpuscore:
print('You tied!')
elif playerscore < cpuscore:
print('Unlucky, you lost.')