2012-03-02 3 views
2

내가 겪고있는 주된 문제는 사용자가 컴퓨터 (랜덤 기능)를 가지고 놀 때 총 승리를 얻으려고하는 것이다. 하지만 player_choice의 바위 종이 가위로 1, 2 또는 3을 입력 할 때마다이 오류가 계속 발생합니다.파이썬 용 나의 가위 가위 프로그램을 보시길.

Welcome to a game of paper, rock, scissors! 
Please input the correct number according 
to the object. 
Select rock(1), paper(2), or scissors(3): 2 
Computer chose ROCK . 
You chose PAPER . 
Traceback (most recent call last): 
    File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line  
114, in <module> 
    File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 
43, in main 
    File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 
106, in determine_winner 
builtins.UnboundLocalError: local variable 'win' referenced before assignment 

분명히 그 지역 변수 문제. 다른 해결책이 있습니까?

#import the library function "random" so that you can use it for computer 
#choice 
import random 

#define main 
def main(): 
    #assign win, lose, and tie variables to zero so that later it can be added 
    #and displayed 
    win = 0 
    lose = 0 
    tie = 0 

    #control loop with 'y' variable 
    play_again = 'y' 

    #start the game 
    while play_again == 'y': 
     #make a welcome message and give directions 
     print('Welcome to a game of paper, rock, scissors!') 
     print('Please input the correct number according') 
     print('to the object.') 

     #write computer and players choices as value returning functions and 
     #assign them to variables 
     computer_choice = get_computer_choice() 
     player_choice = get_player_choice() 

     #print outcome 
     print('Computer chose', computer_choice, '.') 
     print('You chose', player_choice, '.') 

     #determine who won by defining a function 
     determine_winner(computer_choice, player_choice) 

     #ask the user if they want to play again 
     play_again = input("Play again? Enter 'y' for yes or 'n' for no. ") 

    #print results 
    print('Your total wins are', win, '.') 
    print('Your total losses are', lose, '.') 
    print('Your total ties are', tie, '.') 

#define computer choice 
def get_computer_choice(): 
    #use imported random function from library 
    choice = random.randint(1,3) 

    #assign what the computer chose to rock, paper, or scissors 
    if choice == 1: 
     choice = 'ROCK' 
    elif choice == 2: 
     choice = 'PAPER' 
    else: 
     choice = 'SCISSORS' 

    #return value 
    return choice 

#define player choice 
def get_player_choice(): 
    #assign input to variable by prompting user 
    choice = int(input("Select rock(1), paper(2), or scissors(3): ")) 

    #use while function if user inputs the invalid selection 
    while choice != 1 and choice != 2 and choice != 3: 
     print('The valid numbers are rock(type in 1), paper(type in 2),') 
     print('or scissors(type in 3).') 
     choice = int(input('Enter a valid number please: ')) 

    #assign what the player chose to rock, paper, or scissors 
    if choice == 1: 
     choice = 'ROCK' 
    elif choice == 2: 
     choice = 'PAPER' 
    else: 
     choice = 'SCISSORS' 

    #return value 
    return choice 

#determine the winner by assigning the assigned variables 
def determine_winner(computer_choice, player_choice): 
    #if its a tie, add 1 to tie variable and display message 
    if computer_choice == player_choice: 
     tie += 1 
     print("It's a tie!") 

    #if its a win, add to win variable and display message 
    elif computer_choice == 'SCISSORS' and player_choice == 'ROCK': 
     win += 1 
     print('ROCK crushes SCISSORS! You win!') 
    elif computer_choice == 'PAPER' and player_choice == 'SCISSORS': 
     win += 1 
     print('SCISSORS cut PAPER! You win!') 
    elif computer_choice == 'ROCK' and player_choice == 'PAPER': 
     win += 1 
     print('PAPER covers ROCK! You win!') 

    #if it does not match any of the win criteria then add 1 to lose and 
    #display lose message 
    else: 
     lose += 1 
     print('You lose!') 
main() 

답변

1

determine_winner()이 변수 win, tie하고 main()에서 정의한 lose을 볼 수없는 기능 : 다음은 내 코드입니다. 따라서 win +=1을 할 수 없습니다.

어쨌든 파이썬에서는 보통 main() 루틴을 사용하지 않습니다. (최근에 몇 가지 질문을했는데, 누구에게 가르치고 있습니까?)하지만 그 내용을 최상위 수준으로 옮기더라도 프로그램을 실행하면 같은 이유에서 win += 1이 계속 실패 할 수 있기 때문에 작동하지 않습니다.

당신은 지역 변수를 determine_winner()에서 win, tielose을 정의하고 그 다음 상위 수준의 코드에서 각각의 변수들을 추가, 자신의 반환 값을 가질 수있다. 사실, 당신은 그 함수에서 그 변수들을 전혀 필요로하지 않습니다. 예를 들어

:

def determine_winner(computer_choice, player_choice): 
    #if its a tie, add 1 to tie variable and display message 
    if computer_choice == player_choice: 
     print("It's a tie!") 
     return 0 

    #if its a win, add to win variable and display message 
    elif computer_choice == 'SCISSORS' and player_choice == 'ROCK': 
     print('ROCK crushes SCISSORS! You win!') 
     return 1 
    elif computer_choice == 'PAPER' and player_choice == 'SCISSORS': 
     print('SCISSORS cut PAPER! You win!') 
     return 1 
    elif computer_choice == 'ROCK' and player_choice == 'PAPER': 
     print('PAPER covers ROCK! You win!') 
     return 1 

    #if it does not match any of the win criteria then add 1 to lose and 
    #display lose message 
    else: 
     print('You lose!') 
     return -1 

및 최상위 레벨의 :

result = determine_winner(computer_choice, player_choice) 
if result == -1: 
    lose += 1 
elif result == 0: 
    tie += 1 
else: 
    win += 1 
+0

정말 고마워요! 나는이 문제를 수 시간 동안 꼼짝 않고 바라 보았다! –

+2

'main()'함수를 사용하지 않아도 메인 코드를'if __name__ == "__main __":'문 아래에 두는 것은 좋은 생각입니다. –

+0

하단의'if __name__ == "__main__": main()'행은 실제로 내가 본 모든 사람들에 의해 수행됩니다. 하나의 목적은'main' 실행중인 모든 코드없이 파일을 가져올 수 있도록하는 것이라고 생각합니다. 그래서 당신은 가상의'randRGB()'함수 나 외부 스크립트의 파일에있는 어떤 것을 사용할 수 있습니다. – SimonT

0

파이썬은 어휘 범위 지정을 사용합니다. 즉 변수가 함수 내에 정의 된 경우 해당 함수 외부의 코드는이를 볼 수 없습니다 (global이라고 표시된 경우 제외).

신속하고 지저분한 수정은 winmain 외부에서 볼 필요가있는 기타 변수를 global으로 표시하는 것입니다. 더 나은 해결책은 코드를 재구성하는 것입니다.

+0

먼저 main()의 외부로 이동 시키거나 global이 아닐 것입니다. –

+0

'global' 문을 사용하면됩니다. 이것이 가장 우아한 해결책은 아닙니다. – Taymon

+0

아니요. 현재 모듈의 최상위 수준에서 정의되지 않았습니다. 'global' 문은 지역 변수를 전역 변수로 만들지 않습니다. 이것은 함수가 지역 변수를 생성하는 대신 글로벌 범위에서 * 참조 된 변수를 찾도록 지시합니다. 이것은 * 이미 글로벌 변수가 *있는 경우에만 작동합니다. –

1

당신은 변수를 이기고 잃고 묶을 수 있습니다. 여기서는 그렇지 않습니다. How to make them global

편집 : 글로벌 만들기가 좋은 해결책이 아니라는 데 동의합니다.

+0

나는 그것이 좋은 해결책이라고 생각하지 않는다. 첫째로, 글로벌하게 만들지라도'decide_winner()'의 시작 부분에서'global win'을 사용하지 않는 한 여전히 작동하지 않습니다. 둘째, 전역 변수는 결코 좋은 아이디어가 아닙니다. –

+0

결과를 반환하는 것이 전역을 사용하는 것보다 나은 해결책이라는 데 동의합니다. 나는 Oiugghog Jkhkh가 글로벌 변수를 사용하는 방법을 묻고 있다고 생각했습니다. – bmkorkut

+0

아니요, 그러지 마세요. –

관련 문제