Risto Roosipuu Risto Roosipuu - 1 year ago 103
Python Question

Incrementing score in Python CGI

I am having some trouble getting my score's to increment. It works but it keeps resetting to zero after the first "+1" has been done.

user1score = 0
user2score = 0

def main():
if form.has_key('choice'):
myMove = form['choice'].value
cpuM = computerMove()
result = compareMove(myMove, cpuM)
now = datetime.datetime.now()
writeFile(user, result, now)
print user
print now.strftime("%Y-%m-%d %H:%M")
print result


def computerMove():
cc = ["rock","scissor","paper"]
return random.choice(cc)

def compareMove(myMove, cpuM):
global user1score
global user2score
if myMove == cpuM:
return "Its a tie!"
elif myMove == 'rock':
if cpuM == 'paper':
user2score += 1
return "Paper beats Rock. Computer wins! " + str(user2score)
user1score += 1
return "Rock beats Scissors. You win! " + str(user1score)
elif myMove == 'paper':
if cpuM == 'rock':
user1score += 1
return "Paper beats Rock. You win! " + str(user1score)
user2score += 1
return "Scissors beats paper. Computer wins! " + str(user2score)
elif myMove == 'scissors':
if cpuM == 'rock':
user2score += 1
return "Rock beats scissors. Computer wins " + str(user2score)
user1score += 1
return "Scissors beats paper. You win " + str(user1score)

How can i prevent the score from returning to zero after the score is increased by 1? Everything else is working as intended.

Thank you.

Answer Source

As your script is called every time the user does something, it can't rembember the result of the previous rounds.

Either use some kind of a session(cookie) or add the scores to your form as hidden elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download