2013-10-23 71 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不,它不會:根據用戶輸入,'ans'在while循環的最後一行發生變化。 –

+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

我試過的工作是但現在我遇到的問題 局部變量'領帶'在分配之前引用 – RDPython

+0

對!我已經提交了一份「全球性」聲明,這通常不是一個好主意,但可以完成工作。真的,你想要做的就是將遊戲狀態移動到它自己的對象中並傳遞該對象。 –

+0

我討厭問,但我沒有忘記全球的想法和身份證,而不是使用它。你能告訴我遊戲狀態經過嗎? – RDPython