ここで、私はあなたのためにそれを修正しました。
ヴェルデがどのような変更を加えたかを確認できるように、私はあなたのスタイルを模倣し、できる限りのことを維持しようとしました。とはいえ、そのスタイルは一般的に推奨されていません。より良いスタイルについては、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.')