Incrementing score in Python CGI - python

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.

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.

Related

Python Function not running?

It's my first time here and I'm kinda panicking. I have an assignment to code Rock, Paper, Scissors in Python. (I use Python 3.1) and for some reason the function is not running...?
Here's the code:
hscore = 0
cscore = 0
tries = 0
#computer choice
rock = ("rock")
paper = ("paper")
scissors = ("scissors")
rps = (rock, paper, scissors)
cchoice = random.choice(rps)
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
def humanfunction():
if choice == "rock":
if cchoice == scissors:
print("Human wins this round.")
hscore +=1
if choice == "scissors":
if cchoice == paper:
print("Human wins this round.")
hscore +=1
if choice == "paper":
if cchoice == rock:
print("Human wins this round.")
hscore +=1
if cchoice == choice:
print("Tie.")
def compfunction():
if cchoice == scissors:
if choice == "paper":
print("Computer wins this round.")
cscore +=1
if cchoice == rock:
if choice == "scissors":
print("Computer wins this round.")
cscore +=1
if cchoice == paper:
if choice == "rock":
print("Computer wins this rounud.")
cscore +=1
if cchoice == choice:
print("Tie.")
def choose():
tries = 0
while 0 == 0:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
print("\nHuman choice: ", choice)
print("Computer choice: ", cchoice)
print("Finished game number", tries)
if tries == 10:
print("Limit reached!")
break
humanfunction()
compfunction()
choose()
I've been trying to solve this for days now and for some reason, when I run the code, it doesn't show up who won. Help would be appreciated <3
EDIT:
here's what i get when i run the code:
output
the program is actually supposed to show this:
output2
Here is my take on your code.
The main reason it wasn't running is that your cscore variable was being referenced before it was initialized, because you had setup cscore as a global variable, but didn't declare it as a global variable in your function.
You also needed to import the random library
Also instead of doing 4 if/then statements I combined them into 1 if/then statement
EDIT: cleaned up the code a little more
EDIT 2: no more globals, avoid globals if possible
import random
def get_human_choice():
valid_choice = False
while not valid_choice:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
if choice == 'rock' or 'paper' or 'scissors':
valid_choice = True
return choice
def get_comp_choice():
rps = ('rock', 'paper', 'scissors')
comp_choice = random.choice(rps)
return comp_choice
def human_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Human wins this round.")
def comp_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Computer wins this round.")
def stats(attempts, human_score, comp_scored, tie_score):
print("Finished game number: %s" % attempts)
print('Human Score: %s' % human_score)
print('Computer Score: %s' % comp_scored)
print('Ties: %s' % tie_score)
def play_game(human_score, comp_score, tie_score):
choice = get_human_choice()
comp_choice = get_comp_choice()
if choice == 'rock':
if comp_choice == 'scissors':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'scissors':
if comp_choice == 'paper':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'paper':
if comp_choice == 'rock':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == comp_choice:
print("Tie.")
tie_score += 1
return human_score, comp_score, tie_score
if __name__ == '__main__':
tries = 1
h_score, c_score, t_score = 0, 0, 0
while tries <= 10:
h_score, c_score, t_score = play_game(h_score, c_score, t_score)
if tries == 10:
print("\nLimit reached!\n")
stats(tries, h_score, c_score, t_score)
break
else:
tries += 1

Win Count and Loop Help (Python 3)

I found a basic rock-paper-scissors game and wanted to know how to create a score table for it. Also, I'm confused how to make the game last forever until the player wants to end it. Here is the coding for the game:
import random;
wins_history = [0]
ties_history = [0]
losses_history = [0]
def initial_wins():
return wins_history[0]
def cur_wins():
return wins_history[-1]
def affect_wins(delta):
wins_history.append(cur_wins() + delta)
return cur_wins()
def initial_ties():
return ties_history[0]
def cur_ties():
return ties_history[-1]
def affect_ties(delta):
ties_history.append(cur_ties() + delta)
return cur_ties()
def initial_losses():
return losses_history[0]
def cur_losses():
return losses_history[-1]
def affect_losses(delta):
losses_history.append(cur_losses() + delta)
return cur_losses()
while True:
player = input("Enter your choice (rock/paper/scissors): ");
player = player.lower();
while (player != "rock" and player != "paper" and player != "scissors"):
print(player);
player = input("That choice is not valid. Enter your choice (rock/paper/scissors): ");
player = player.lower();
computerInt = random.randint(0,2);
if (computerInt == 0):
computer = "rock";
elif (computerInt == 1):
computer = "paper";
elif (computerInt == 2):
computer = "scissors";
else:
computer = "Huh? Error...";
if (player == computer):
print("Draw!");
affect_ties(+1)
print ("Your new tie score is, cur_ties()")
elif (player == "rock"):
if (computer == "paper"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
elif (player == "paper"):
if (computer == "rock"):
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
else:
print("Computer wins!")
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
elif (player == "scissors"):
if (computer == "rock"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")

Python while loop not working like i want it to. Building rock,paper scissors game

I am having a huge problem with my game. Whenever I run the shell(cmd) only runs it once and its supposed to run 10 times. I've tried everything, in fact i just recently changed the while loop to a function but it didn't help. I tried refreshing m pc but that did'nt help either. Does somebody kow how to fix this.
Here is my code:
import random
pc_rock = 1
pc_paper = 2
pc_scissors = 3
you_rock = ['1', 'rock', 'one']
you_paper = ['2', 'paper', 'two']
you_scissors = ['3', 'scrissors', 'three']
def ifs():
turns = 0
while turns < 10:
turns = turns + 1
pc_score = 0
you_score = 0
if you == you_rock and comp == pc_rock:
print "Draw"
elif you == you_rock and comp == pc_paper:
print "You lose"
pc_score = pc_score + 1
elif you == you_rock and comp == pc_scissors:
print "You win"
you_score = you_score + 1
elif you == you_paper and comp == pc_paper:
print "Draw"
elif you == you_paper and comp == pc_rock:
print "You win"
you_score = you_score + 1
elif you == you_paper and comp == pc_scissors:
print "You lose"
pc_score = pc_score + 1
elif you == you_scissors and comp == pc_scissors:
print "Draw"
elif you == you_scissors and comp == pc_rock:
print "You lose"
pc_score = pc_score + 1
elif you == you_scissors and comp == pc_paper:
print "You win"
you_score = you_score + 1
else:
print you_score , "is your score"
print pc_score , "is the pc's score"
if you_score > pc_score:
print "You win!"
elif pc_score > you_score:
print "You lose!"
elif pc_score == you_score:
print "Its a Draw!"
comp = random.randrange(1, 4)
print "You are about to play a fun game of rock, paper and scissors against"
print "your pc"
print "It is completely random so the pc can lose"
print "You will play 10 rounds"
print "Do you pick rock, paper or scissors"
print "ROCK = 1"
print "PAPER = 2"
print "SCISSORS = 3"
you = raw_input('>>>>')
#Pc ifs
#__________________
if comp == pc_rock:
print "The PC picks rock"
elif comp == pc_paper:
print "The PC picks paper"
elif comp == pc_scissors:
print "The PC picks scissors"
else:
print " ERROR |" * 10
print "STH WENT WRONG PLEASE GO BACK AND CHECK THE CODE"
#You ifs
#__________________
if you in you_rock:
print "You picked rock"
ifs()
elif you in you_paper:
print "You picked paper"
ifs()
elif you in you_scissors:
print "You picked scissors"
ifs()
else:
while you != you_rock or you_paper or you_scissors:
print "Either rock paper or scissors please!"
you = raw_input('>>>>')
ifs()
You are comparing an integer value with a list you == you_rock,
within the function.
So it returns false, as there is no else within the while loop it
doen,t print anything. But the loop executes 10 times.
Replace you == you_rock as you == you_rock[0] as well as change
other if conditions.
Now run the program, you will see that it executes 10 times.
NOTE : Your while loop is wrongly placed. Change it according to your
required output.
As others have said, you have the while loop in the wrong place. I've modified your code so that the game runs properly, 10 times (and added a few print statements to clarify what turn it is), but there are still some bugs you need to sort out.
import random
pc_rock = 1
pc_paper = 2
pc_scissors = 3
you_rock = ['1', 'rock', 'one']
you_paper = ['2', 'paper', 'two']
you_scissors = ['3', 'scrissors', 'three']
def game():
print( "You are about to play a fun game of rock, paper and scissors against")
print( "your pc")
print( "It is completely random so the pc can lose")
print( "You will play 10 rounds")
turns = 0
pc_score = 0
you_score = 0
while turns < 10:
comp = random.randrange(1, 4)
print( "Current round: " + str(turns + 1))
print( "Your score: " + str(you_score))
print( "PC score: " + str(pc_score))
print( "Do you pick rock, paper or scissors")
print( "ROCK = 1")
print( "PAPER = 2")
print( "SCISSORS = 3")
you = raw_input('>>>>')
#Pc ifs
#__________________
if comp == pc_rock:
print( "The PC picks rock")
elif comp == pc_paper:
print( "The PC picks paper")
elif comp == pc_scissors:
print( "The PC picks scissors")
else:
print( " ERROR |" * 10)
print( "STH WENT WRONG PLEASE GO BACK AND CHECK THE CODE")
#You ifs
#__________________
if you in you_rock:
print( "You picked rock")
elif you in you_paper:
print( "You picked paper")
elif you in you_scissors:
print( "You picked scissors")
else:
while you != you_rock or you_paper or you_scissors:
print( "Either rock paper or scissors please!")
you = raw_input('>>>>')
turns = turns + 1
if you == you_rock and comp == pc_rock:
print( "Draw")
elif you == you_rock and comp == pc_paper:
print( "You lose")
pc_score = pc_score + 1
elif you == you_rock and comp == pc_scissors:
print( "You win")
you_score = you_score + 1
elif you == you_paper and comp == pc_paper:
print( "Draw")
elif you == you_paper and comp == pc_rock:
print( "You win")
you_score = you_score + 1
elif you == you_paper and comp == pc_scissors:
print( "You lose")
pc_score = pc_score + 1
elif you == you_scissors and comp == pc_scissors:
print( "Draw")
elif you == you_scissors and comp == pc_rock:
print( "You lose")
pc_score = pc_score + 1
elif you == you_scissors and comp == pc_paper:
print( "You win")
you_score = you_score + 1
print('')
else:
print( you_score , "is your score")
print( pc_score , "is the pc's score")
if you_score > pc_score:
print( "You win!")
elif pc_score > you_score:
print( "You lose!")
elif pc_score == you_score:
print( "Its a Draw!")
game()
You'll probably notice that the section of if and elif statements to determine who won each round, and to increment that player's score, does not function properly. The scores remain at 0 after every turn. I was thinking about just fixing it, but I think that will be a fun debugging exercise for you. Happy coding!

How to give concatenate function results to a class in python 2.7

So this is a quick code for Rock Scissors Paper I 've made. It works fine and it is written pretty simply in relevance to other codes I have seen (i think), however I have a problem with the score keeping. Algorithmically speaking I need to save the score in a class, outside the loop Play - Results - Score of last game - Rematch, and to do that I have to connect somehow the Score of last game with the Score class so that it concatenates each game.
My code is bellow:
import random
def main():
pick_list = ["Rock","Paper","Scissors"]
player_pick = str(raw_input("Rock, Scissors, Paper! Make your Pick! "))
pc_pick = random.choice(pick_list)
if player_pick not in pick_list:
print "Oops, looks like you didn't pick correctly. Try again!"
main()
else:
print "Your pick was " + player_pick
print "My pick was " + pc_pick
results(pc_pick,player_pick)
table_score(results,pc_pick,player_pick)
Score(pc_pick, player_pick)
rematch()
def results(pc_pick,player_pick):
if pc_pick == player_pick:
print "It's a tie!"
elif pc_pick == "Rock" and player_pick == "Paper":
print "You win!"
return "Victory"
elif pc_pick == "Rock" and player_pick == "Scissors":
print "Sorry, I win"
return "Loss"
elif pc_pick == "Scissors" and player_pick == "Rock":
print "You win!"
return "Victory"
elif pc_pick == "Scissors" and player_pick == "Paper":
print "Sorry, I win"
return "Loss"
elif pc_pick == "Paper" and player_pick == "Scissors":
print "You win!"
return "Victory"
elif pc_pick == "Paper" and player_pick == "Rock":
print "Sorry, I win"
return "Loss"
def rematch():
challenge = str(raw_input('Wanna go again? [Y/n]'))
positive_answers =['Y','y', 'yes','Yes']
negative_answers = ['N','n','No','no']
if challenge in positive_answers:
main()
elif challenge in negative_answers:
print "Goodbye!"
raw_input("Press any key to exit")
else:
print "Sorry I didn't get that, try again"
rematch()
def table_score(results, pc_pick, player_pick):
pc_score = 0
player_score = 0
if results(pc_pick, player_pick) == "Victory":
player_score += 1
elif results(pc_pick,player_pick) == "Loss":
pc_score += 1
else:
player_score += 0
pc_score += 0
print "Player:" + str(player_score)
print "Pc:" + str(pc_score)
class Score():
pass
main()
The thing is that because of my rematch function, I need to keep "saving" the score somewhere outside the loop. I know it's a stupid thing but I just got stuck. Thanks
You need something like this:
class Score(object):
pc_score = 0
player_score = 0
def update_score(self, pc_score, player_score):
self.pc_score += pc_score
self.player_score += player_score
Alright, so far I 've managed to solve the problem with this code:
import random
def main():
pick_list = ["Rock","Paper","Scissors"]
player_pick = str(raw_input("Rock, Scissors, Paper! Make your Pick! "))
pc_pick = random.choice(pick_list)
if player_pick not in pick_list:
print "Oops, looks like you didn't pick correctly. Try again!"
main()
else:
print "Your pick was " + player_pick
print "My pick was " + pc_pick
results(pc_pick,player_pick)
table_score(results,pc_pick,player_pick)
print "The score so far is... You: ",Score.player_score ,"Me", Score.pc_score
rematch()
def results(pc_pick,player_pick):
if pc_pick == player_pick:
print "It's a tie!"
elif pc_pick == "Rock" and player_pick == "Paper":
print "You win!"
return "Victory"
elif pc_pick == "Rock" and player_pick == "Scissors":
print "Sorry, I win"
return "Loss"
elif pc_pick == "Scissors" and player_pick == "Rock":
print "You win!"
return "Victory"
elif pc_pick == "Scissors" and player_pick == "Paper":
print "Sorry, I win"
return "Loss"
elif pc_pick == "Paper" and player_pick == "Scissors":
print "You win!"
return "Victory"
elif pc_pick == "Paper" and player_pick == "Rock":
print "Sorry, I win"
return "Loss"
def rematch():
challenge = str(raw_input('Wanna go again? [Y/n]'))
positive_answers =['Y','y', 'yes','Yes']
negative_answers = ['N','n','No','no']
if challenge in positive_answers:
main()
elif challenge in negative_answers:
print "Goodbye!"
raw_input("Press any key to exit")
else:
print "Sorry I didn't get that, try again"
rematch()
def table_score(results, pc_pick, player_pick):
pc_score = 0
player_score = 0
if results(pc_pick, player_pick) == "Victory":
Score.player_score += 1
elif results(pc_pick,player_pick) == "Loss":
Score.pc_score += 1
else:
Score.player_score += 0
Score.pc_score += 0
print "Player:" + str(player_score)
print "Pc:" + str(pc_score)
class Score:
def __init__(self):
self.pc_score = 0
self.player_score = 0
Score = Score()
main()
The only problem I have is that the output gives me 3 times the "It's a tie" output (if it is a tie) and twice the "I win" "You win" outputs... I cannot figure out why yet.

Simple Rock Paper Scissors game, problems with returning score?

I'm writing this Rock Paper Scissors program for my Programming class, and having some problems getting the full score to show up at the end of the program. I'm super beginner in Python, so nothing too fancy here. For some reason, as I run the program, the only score that shows up is 1 regardless of how many times the game loops. What am I doing wrong here?
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()
Inside playGame, you set userWin, compWin, and tie to zero. So every time you call that function, they get set to zero before the new values are added. You should initialize these variables outside the function that you are calling in the loop. (For instance, you could initialize them in announceGame.)

Categories

Resources