2012-06-22 4 views
0

필자는 프로그래밍 수업을위한 Rock Paper Scissors 프로그램을 작성 중이며, 프로그램 끝 부분에 전체 점수를 표시하는 데 문제가 있습니다. 저는 파이썬에서 초보자입니다. 그래서 여기도 공상적입니다. 어떤 이유로 프로그램을 실행할 때 게임이 반복되는 횟수에 관계없이 표시되는 유일한 점수는 1입니다. 여기서 내가 뭘 잘못하고 있니?간단한 바위 종이 가위 게임, 점수를 반환하는 데 문제가 있습니까?

from myro import * 
from random import * 

def announceGame(): 
    """ Announces the game to the user """ 
    speak("Welcome to Rock, Paper, Scissors. I look forward to playing you.") 

def computerMove(): 
    """ Determines a random choice for the computer """ 
randomNumber = random() 
    if randomNumber == 1: 
     compMove = "R" 
    elif randomNumber == 2: 
     compMove = "P" 
    else: 
     compMove = "S" 
return compMove 

def userMove(): 
    """ Asks the user to input their choice.""" 
    userChoice = raw_input("Please enter R, P, or S: ") 
    return userChoice 

def playGame(userChoice, compMove): 
    """ Compares the user's choice to the computer's choice, and decides who wins.""" 

    global userWin 
    global compWin 
    global tie 

    userWin = 0 
    compWin = 0 
    tie = 0 

    if (userChoice == "R" and compMove == "S"): 
     userWin = userWin + 1 
     print "You win." 

    elif (userChoice == "R" and compMove == "P"): 
     compWin = compWin + 1 
     print "I win." 

    elif (userChoice == "S" and compMove == "R"): 
     compWin = compWin + 1 
     print "I win." 

    elif (userChoice == "S" and compMove == "P"): 
     userWin = userWin + 1 
     print "You win" 

    elif (userChoice == "P" and compMove == "S"): 
     compWin = compWin + 1 
     print "I win" 

    elif (userChoice == "P" and compMove == "R"): 
     userWin = userWin + 1 
     print "You win" 

    else: 
     tie = tie + 1 
     print "It's a tie" 


    return compWin, userWin, tie 


def printResults(compWin, userWin, tie): 
    """ Prints the results at the end of the game. """ 
    print "  Rock Paper Scissors Results " 
    print "------------------------------------" 
    print "Computer Wins: " + str(compWin) 
    print "User Wins: " + str(userWin) 
    print "Ties: " + str(tie) 

def main(): 
    announceGame() 
    for game in range(1,6): 
     u = userMove() 
     c = computerMove() 
     game = playGame(u,c) 

    printResults(compWin, userWin, tie) 


main() 

답변

2

playGame 내부, 당신은 제로에 userWin, compWintie을 설정합니다. 따라서 함수를 호출 할 때마다 새 값이 추가되기 전에 0으로 설정됩니다. 루프에서 호출하는 함수 외부에서 이러한 변수를 초기화해야합니다. 예를 들어, announceGame에서 초기화 할 수 있습니다.

+0

코드 조각을 announceGame() 함수로 이동했지만 여전히 0으로 표시되거나 할당 전에 로컬 변수가 참조되었다고 알려줍니다. – user1473879

+0

그 함수에서 전역 변수를 참조하려면'playgame'에'global' 문을 포함시켜야합니다. 값을 유지하려면 0으로 설정하면 안됩니다. – BrenBarn

+0

아, 고맙습니다. 지금은 잘 작동합니다. – user1473879

관련 문제