2011-09-10 3 views
0

저는 현재 약간의 바위, 종이, 가위 게임을 파이썬으로 코딩하고 있습니다. 그러나 문제가있는 것으로 보입니다. 게임은 코드가 약간 어둡더라도 작동하지만 프로그램에서 오류를 만든 플레이어에게이를 알리려고했습니다. 테스트 한 결과 무작위로 플레이어에게 오류를 알립니다. 그들은 아직 ~하지 못했다. 여기 내 문제는 코드 블록입니다, 그것은 전체 게임이 아닙니다.파이썬의 바위, 종이 가위 게임에 문제가 있습니다.

def game(self): 

    print "This is rock, paper, scissors!" 

    rps = ('rock', 'paper', 'scissors') 

    comp1 = raw_input("Rock, paper or scissors?\n> ") 
    comp2 = random.choice(rps) 

    if comp1 == 'rock' and comp2 == 'scissors' or comp1 == 'scissors' and comp2 == 'paper' or comp1 == 'paper' and comp2 == 'rock': 
     print "You won! The computer chose %s" % comp2 
     return "game" 
    elif comp1 == 'rock' and comp2 == 'rock': 
     print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2 
     return "game" 
    elif comp1 == 'scissors' and comp2 == 'scissors': 
     print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2 
     return "game" 
    elif comp1 == 'paper' and comp2 == 'paper': 
     print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2 
     return "game" 
    elif comp1 != 'rock' or 'scissors' or 'paper': 
     print "Try choosing between rock, paper and scissors next time. It might help. 
     return "game" 
    else: 
     print "The computer %s. You have failed. Problem?" % comp2 
     return "game" 
+0

휴대 전화에서는 comp1을 소문자로 변환 해보세요. 교착 상태에 대해 comp1 == comp2로 논리를 단순화 할 수도 있습니다. – billinkc

+0

복사 한 항목에 유효하지 않은 문자열 리터럴이 있기 때문에 실제 코드를 복사하지 않았습니다. –

+0

왜 항상 "게임"이라는 문자열을 반환합니까, 그건 이상하게 보입니다 ... 아마 당신의 문제와 관련이 없습니다. –

답변

9

변경

elif comp1 != 'rock' or 'scissors' or 'paper': 

이전에 수행하는 것과이었다 있었다 무엇

elif comp1 not in rps: 

에 :

elif (comp1 != 'rock') or 'scissors' or 'paper': 

은 왜 조건이 항상 만났다?

or 'scissors' or 'paper' 부분을 자세히 살펴보십시오.

1) 파이썬에서 비어 있지 않은 문자열은 True로 처리되고 빈 문자열은 False로 처리됩니다. 이 대화 형 세션에서보세요 :

>>> bool('') 
False 
>>> bool('a') 
True 

2) 또한 파이썬에서, 비교 (예를 들어, if var1:)없이 if 문은 표현식이 True 인 경우 inexplicity 검사입니다. 당신은이 두 가지 아이디어를 결합 할 경우 그래서,

if var1: 

if var1 == True: 

과 동일합니다 :

위로 원래 if 문에
if 'rock': 
    # Always executed 
if '': 
    # Never executed 

:

elif comp1 != 'rock' or 'scissors' or 'paper': 

모두를 '가위'와 '종이'는 항상 True를 반환합니다. 그래서 포함 된 문장은 항상 평가됩니다.

그래서 "in"연산자는 무엇입니까?

comp1의 내용 (('rock', 'paper', 'scissors') 같다) 튜플 rps의 항목 인 경우 elif comp1 not in rps:in 운영자가 볼. 그 앞에있는 not은 그 내용을 무효화하여 comp1의 내용이 튜플 rps의 항목인지 확인합니다. 따라서 포함 된 명령문은 comp1에 저장된 사용자 입력이 유효하지 않은 경우에만 실행됩니다.

2

그것은

comp1 not in ['rock', 'scissors', 'paper'] 

'가위'와 '종이'항상 (그들 자신 또는 or의 경우) true로 평가 또한

comp1 != 'rock' or 'scissors' or 'paper' 

, comp1 == comp2를 사용해야합니다, 그것은 훨씬 더 간단합니다 .

+1

을 사용하면 훨씬 간단 해집니다. :피 –

1

여기 논리에 문제가 있습니다 elif comp1 != 'rock' or 'scissors' or 'paper':. 문자열 '가위'와 '종이'는 부울 값으로 평가되며, 이는 null이 아니기 때문에 참입니다. 당신이 원하는 무엇

elif comp1 != 'rock' and comp1 != 'scissors' and comp1 != 'paper': 또는 이미 rps 튜플에이 있기 때문에, 당신은 내가이 좀 더 정리 된 버전이라고 생각 elif comp1 not in rps:

0

하지 않지만 최선의 구현을 할 수 있습니다. 또한 계속 연주 할 수있는 옵션을 추가하고 사용자 입력이 대소 문자를 구분하지 않도록 변경했습니다.

def game(): 
    import random 
    import string 
    print "This is rock, paper, scissors!" 

    rps = ('rock', 'paper', 'scissors') 

    comp1 = raw_input("Rock, paper or scissors? ") 
    comp1 = comp1.lower() 
    comp2 = random.choice(rps) 

    if comp1 == 'rock' and comp2 == 'scissors' or comp1 == 'scissors' and comp2 == 'paper' or comp1 == 'paper' and comp2 == 'rock': 
     print "You won! The computer chose %s" % comp2 
    elif comp1 == comp2: 
     print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2 
    elif comp1 not in rps: 
     print "Try choosing between rock, paper and scissors next time. It might help." 
    else: 
     print "The computer chose %s. You have failed. Problem?" % comp2 
    new_game = raw_input('Would you like to play again? ') 
    new_game = new_game.lower() 
    if new_game == 'yes': 
     game() 
관련 문제