2013-07-26 2 views
1

처음으로 코드에서 클래스를 구현하면 권투 경기의 점수를 유지하는 간단한 클래스를 만들려고합니다. 수업에 대해 빠뜨린 근본적인 것이 있습니까?클래스를 사용하여 파이썬에서 점수 유지

class Sparring(): 
    def __init__(self, mywins, hiswins): 
     self.mywins = mywins 
     self.hiswins = hiswins 

    def my_score(self, mywins): 
     self.mywins = mywins =+ 1 
     return self.mywins 
    def his_score(self, hiswins): 
     self.hiswins = hiswins =+ 1 
     return self.hiswins 

여기, 그것을 사용하는 모든 종류의 조합을 반환을 사용하지 시도했습니다 I 클래스 전화 사용 된 기능입니다 :

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(0,0) 

    while fight1 != 2: 
     if 'right' in dodge: 
      print "Nice job, you knocked him out!" 
      fight1 = Sparring(1,0) 
      fight1.my_score(1) 
     else: 
      print 'Oh no he knocked you out' 
      fight1 = Sparring(0, 1) 
      fight1.his_score(1) 
+4

'self.mywins = mywins = + 1' : self.mywins 및 mywins에 1의 값을 할당하고 있습니다. 실제로 그 작업을 수행하려고합니다. ;-) – Gryphius

+2

레프트 훅을 던지고 오른쪽으로 피하는 경우 주먹에 피하고 있지 않습니까? – user2357112

답변

1

단순히 카운터를 증가하기에 충분하다 : '! fight1 = 2' '! fight1.best = 2'당신은 당신의 확인을위한 "최고", 빨간색으로해야하는 기능을 필요

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]) 

. 여러분의 프로그램은 읽을 수 :

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() 

귀하의 코멘트에 대답하기 위해, 내가 샘플 implementatio를 제공합니다 전체 싸움의 : 그냥 완성도를 위해서 몇 가지 코드 골프을하기 위해

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.') ] 
+0

@Hyperboreous 대단합니다! 그러나 나는 3에서 최선의 경기를하고 싶다고 설명하는 것을 잊었다. 그래서 'mywins'또는 'hiswins'가 2에 도달했는지 확인하는 방법이 필요하다. – Amon

+0

while 루프는 실제로 두 개의 히트를 기록한 후 멈출 것입니다. – Hyperboreus

+0

승자가 누구인지 알고 싶으면 다음을 추가하십시오.'def winner (self) : 자기 자신의 경우 'me'를 반환하십시오. self.hiswins else 'him'' – Hyperboreus

1

당신은 때마다 클래스를 다시 초기화하고는 전화 해.

이 코드에서
class Sparring(): 
    def __init__(self, mywins, hiswins): 
     self.mywins = mywins 
     self.hiswins = hiswins 

    def i_win(self): 
     self.mywins += 1 

    def he_wins(self): 
     self.hiswins += 1 

    def __repr__(self): 
     return "My wins: {}; his wins: {}".format(self.mywins,self.hiswins) 

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?" 

    fight = Sparring(0,0) 

    dodge = raw_input() 
    if 'right' in dodge: 
     print "Nice job, you knocked him out!" 
     fight.i_win() 
    else: 
     print 'Oh no he knocked you out' 
     fight.he_wins(1) 

    print fight 

fight_match() 

, Sparring() 두 가지 기능, he_wins()i_win()있는 클래스 : 여기 청소기 버전입니다. 그가 이기면 he_wins(); 이기면 i_win()을 실행하십시오.

fight_match()에서, 당신은 우리가 모든 방법과 Sparring 클래스 (기억의 변수가 있다는 것을 의미 Sparring 객체 — 인 fight을 만드는 것을 볼 수 있습니다, 당신은 —에게 직접 클래스를 상호 작용하지 않습니다 그 클래스의 오브젝트과 상호 작용합니다. 그래서 우리는 raw_input(), dodge을받습니다. 이 입력이 "오른쪽"인 경우 (i_win()을 사용하여)에 대해 하나의 승리를 반영하도록 경기 개체를 업데이트합니다. 그렇지 않다면 그는 승리합니다. 그래서 fight.he_wins()fight 객체를 업데이트하여 자신이 얻은 것을 반영합니다.

관련 문제