Risto Roosipuu Risto Roosipuu - 4 days ago 7
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)
show(user)
print user
print now.strftime("%Y-%m-%d %H:%M")
print result



else:
show(user)



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)
else:
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)
else:
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)
else:
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

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.

Comments