2013-10-23 9 views
1

그래서 내가 가지고있는 문제는 숫자를 더하려고 할 때 내 카운터가 계속 재설정되는 것입니다. 카운터 부분을 함수로 만드는 방법을 생각해 봤지만 숫자가 없습니다.가위 가위 반환 문제

winP1=0 
winP2=0 
tie=0 

ans = input('Would you like to play ROCK, PAPER, SCISSORS?: ') 

while ans == 'y': 
    p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice" 
    p2c = input('Player 2 enter either R,P, or S: ') 
    ans = input('Would you like to play again: ') 

def game(p1c,p2c): 
    if p1c == p2c:     #if its a tie we are going to add to the Tie variable 
     return 0 
    elif p1c == 'R' and p2c == 'P': #We will only set the Player 1 wins because 
     return 1     #player 2 wins can be set as else 
    elif p1c == 'P' and p2c == 'S': 
     return 1 
    elif p1c == 'S' and p2c == 'R': 
     return 1 
    else: 
     return -1 

result = game(p1c,p2c) 
if result == -1: 
    winP2 += 1 
if result == 0: 
    tie += 1 
else: 
    winP1 +=1 

print('Player 1 won {} times. \nPlayer 2 won {} times. \nThere were {} ties.'.format(winP1,winP2,tie)) 
+0

프로그램에서 while 루프가 영원히 계속됩니다. – aIKid

+0

@alKid 아니오, 사용자 입력에 따라 while 루프의 마지막 줄에서 'ans'가 변경됩니다. –

+0

오 예. 신경 쓰지 마. – aIKid

답변

3

StackOverflow 및 Python 프로그래밍에 오신 것을 환영합니다. 여기에 좋은 시간 보내길 바랍니다.

귀하의 카운터 유지하는 시스템으로, 당신은 하나 개의 게임을 재생하고, 때문에 재설정 :

while ans == 'y': 
    p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice" 
    p2c = input('Player 2 enter either R,P, or S: ') 
    ans = input('Would you like to play again: ') 

내가 당신에게 당신이 원하는 결과를 얻기 위해 코드에서 주변에 몇 가지를 이동하는거야을 편집 최소한, 그리고 희망적으로 그것은 당신에게 당신이해야 할 것을 보여줄 것입니다. 너는 바른 길을 가고있다!

state이라는 사전을 사용하여 게임 상태를 추적하고 전달합니다.

state = { 
    'winP1':0, 
    'winP2':0, 
    'tie':0 
} 

def game(p1c,p2c): 
    if p1c == p2c:     #if its a tie we are going to add to the Tie variable 
     return 0 
    elif p1c == 'R' and p2c == 'P': #We will only set the Player 1 wins because 
     return 1     #player 2 wins can be set as else 
    elif p1c == 'P' and p2c == 'S': 
     return 1 
    elif p1c == 'S' and p2c == 'R': 
     return 1 
    else: 
     return -1 

def process_game(p1c, p2c, state): # Move this into a function 
    result = game(p1c,p2c) 
    if result == -1: 
     state['winP2'] += 1 
    if result == 0: 
     state['tie'] += 1 
    else: 
     state['winP1'] +=1 

while ans == 'y': 
    p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice" 
    p2c = input('Player 2 enter either R,P, or S: ') 
    process_game(p1c, p2c, state) 
    ans = input('Would you like to play again: ') 

print('Player 1 won {} times. \nPlayer 2 won {} times. \nThere were {} ties.'.format(state['winP1'],state['winP2'],state['tie'])) 
+0

작업을 시도했지만 지금은 로컬 변수 'tie'에 문제가 있습니다. 과제 전에 참조 됨 – RDPython

+0

오른쪽! 저는 일반적으로 좋은 생각은 아니지만 일을 끝내는'global' 선언을했습니다. 정말로, 당신이 원하는 것은 게임 상태를 그 자체의 객체로 옮기고 그 객체를 전달하는 것입니다. –

+0

나는 싫지만 나는 글로벌 아이디어와 ID를 사용하지 않고 그것을 사용하지 않았다. 당신은 나를 통과하는 게임 상태를 보여줄 수 있습니까? – RDPython