简单地增加计数器就足够了:
class Sparring():
def __init__(self, mywins = 0, hiswins = 0):
self.mywins = mywins
self.hiswins = hiswins
def my_score(self):
self.mywins += 1
def his_score(self):
self.hiswins += 1
@property
def best (self):
return max ( [self.mywins, self.hiswins] )
您需要检查“fight1!= 2”的功能“最佳”,现在应该是红色的“fight1.best!= 2”。您的程序可以读取:
def fight_match():
print "Okay you're in the ring, ready to go three rounds with this dude"
print "He throws a left hook, which way will you dodge?"
dodge = raw_input()
fight1 = Sparring()
while fight1.best != 2:
if 'right' in dodge:
print "Nice job, you knocked him out!"
fight1.my_score()
else:
print 'Oh no he knocked you out'
fight1.his_score()
另一件事是,您可能希望将输入移动到 while 循环中:
fight1 = Sparring()
while fight1.best != 2:
dodge = raw_input()
if 'right' in dodge:
print "Nice job, you knocked him out!"
fight1.my_score()
else:
print 'Oh no he knocked you out'
fight1.his_score()
为了回答您的评论,我将提供整个战斗的示例实现:
import random
class Fight:
def __init__ (self): self.scores = [0, 0]
def heScores (self): self.scores [1] += 1
def youScore (self): self.scores [0] += 1
@property
def best (self): return max (self.scores)
@property
def winner (self): return 'You win.' if self.scores [0] > self.scores [1] else 'He wins.'
fight = Fight ()
print ('Fight begins.')
question, answer = 'left', 'right'
while fight.best != 2:
if random.randint (0, 1): question, answer = answer, question
if answer in input ('He throws a {} hook, which way will you dodge? '.format (question) ):
print ('Nice job, you knocked him out.')
fight.youScore ()
else:
print ('Oh no, he knocked you out.')
fight.heScores ()
print (fight.winner)
只是为了完整起见并为了做一些代码打高尔夫球,这是一个做同样事情的单线:
_ = [print ('Fight!'), print ('You won.' if (lambda a, b: (lambda a, *b: a (a, *b) ) ( (lambda a, b, c, d, e: e if max (e) == 2 else a (a, b, c, c (b), [print ('Nice job, you knocked him out.'), (1 + e [0], 0 + e [1] )] [1] if d [1] in input ('He throws a {} hook, which way will you dodge? '.format (d [0] ) ) else [print ('Oh no, he knocked you out.'), (0 + e [0], 1 + e [1] )] [1] ) ), b, a, a (b), (0, 0) ) ) ( (lambda a: ('left', 'right') if a.randint (0, 1) else ('right', 'left') ), __import__ ('random') ) [0] == 2 else 'He won.') ]