Need help on stopping the score from resetting every game,
this is my code so far and its not working.
This is part of a function that checks who's the winner etc.
def winner ():
global Win
if alist [0] == player1 and alist[1] == player1 and alist[2] ==player1:#top line horizontal
Win = 'player1'
return True
elif alist[3] == player1 and alist[4] == player1 and alist[5] ==player1:#middleline horizontal
Win = 'player1'
return True
this statement determines the score and whether to start another game.
if winner():
if Win == 'player1':
print("player1 is winner")
p1score = p1score+1
elif Win == 'player2':
print("player2 is winner")
p2score = p2score+1
print('Player1s score =', p1score,'Player2s score =', p2score)
print("Would you like to play again(yes or no)")
restart = input("")
if restart == 'yes':
return gamemode()
Ok so at the end of the game the score displays correctly, but when another game is played it resets?
def playervscomputer():
global Player1Score
Player1Score = 0
global ComputerScore
ComputerScore = 0
players = [name, 'computer']
global turn
turn = random.randint(0,1)
while True:
print('its\s %s\'s turn' % players[turn])
if winner1():
#Check if people have won
if Win == 'player1':
print("player1 is winner")
Player1Score = Player1Score+1
print("player1s score is", Player1Score, 'Computer Score=', ComputerScore)
print("would you like to play again?(yes or no)")
restart = input("")
if restart =='yes':
return main()
else:
print("Thanks for playing")
elif Win == 'Computer':
print("Computer is winner")
ComputerScore = ComputerScore+1
print('Player1s score =', Player1Score,'Computers score =', ComputerScore)
Any ideas or any help on it keeping the scores after a few games have been played.
Thanks
Looks like you're not fully understanding scope. Try changing p1score and p2score to global variables (like you did with Win).
This YouTube video helped me understand the difference between global and local variables, maybe it will help you.
https://www.youtube.com/watch?v=A054Ged9suI
A simple programm, that uses a function to increment two independent variables (in a list):
score = [0,0]
def increment(Player):
global score
if Player == 1:
score[0]+=1
elif Player ==2:
score[1]+=1
else:
print('Input not defined')
def main():
global score
print(score)
increment(1)
increment(2)
increment(2)
print(score)
Related
I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass
So I'm currently having some trouble with working out how to basically create a "count" function work within my Rock, Paper, Scissors game. I'm new to Python and this is my first foray into the use of multiple functions to execute game logic. Here's my code...
import random
from random import choice
cpu_score = 0
player_score = 0
# dictionary from which gestures are pulled
gestures = ["rock","paper","scissors"]
n_rounds = int(input("How many rounds would you like to play? "))
while n_rounds % 2 == 0 or n_rounds <= -1:
print("Number of rounds must be an odd number! Select an odd number!")
n_rounds = input("How many rounds?")
break
print("Lets play",n_rounds,"rounds!")
rounds_to_win = ((n_rounds + 1)//2)
rounds_to_win = round(rounds_to_win)
print("You must win",rounds_to_win,"rounds to beat the game!")
def computer_choice():
"""Movement made by the computer"""
comp = random.choice(gestures)
return comp
def player_gesture():
"""Movement by player"""
player = input("Please select, rock, paper or scissors")
if player not in gestures:
print("That's not an option! Please try again.")
player = input("Please select, rock, paper or scissors")
return player
def who_won_round(comp, player):
'''Who is the winner of the round.'''
winner = 0
if ((player == "rock") and (comp == "paper")) or \
((player == "paper") and (comp == "scissors")) or \
((player == "scissors") and (comp == "rock")):
winner = 1
elif ((comp == "rock") and (player == "paper")) or \
((comp == "paper") and (player == "scissors")) or \
((comp == "scissors") and (player == "rock")):
winner = 2
else:
winner = 0
return winner
def win_counter(winner, cpu_score,player_score):
rounds = 1
if winner == 1:
player_score += 1
print("This is round",rounds)
rounds += 1
return player_score
if winner == 2:
cpu_score += 1
print("This is round",rounds)
rounds += 1
return cpu_score
def count_round(winner, player, comp, cpu_score, player_score):
if winner == 0:
print("It's a tie!")
elif winner == 1:
print("The player chose",player)
print("The computer chose",comp)
print("The computer won the round!")
print("The computer has won",cpu_score,"rounds!")
elif winner == 2:
print("The player chose",player)
print("The computer chose",comp)
print("The player won the round!")
print("The player has won",player_score,"rounds!")
def game_structure():
while rounds_to_win < n_rounds:
comp = computer_choice()
player = player_gesture()
winner = who_won_round(comp,player)
win_count = win_counter(winner, cpu_score,player_score)
count = count_round(winner, player, comp, cpu_score, player_score)
game_structure()
Basically I'm having issues returning the variables in order to keep count of the scores of the "number of rounds" and "cpu_score" and "player_score". I prefer to not declare global variables as I realise they can be messy to use, but I'm not quite sure how to avoid this.
If you must avoid the use of global variables, you should take an object oriented approach. That way you can store the variables in the object.
So basically you do something like this:
newgame = mytictactoe()
while True #infinite loop
input("wanna play?")
if input == yes:
newgame.start
else:
break
From what I see, the cpu_score and player_score are never updated. You only have the newest result in win_count, that is not assigned to cpu_score or player_score at anytime. It could be something like:
win_count = win_counter(winner, cpu_score,player_score)
if winner == 1:
cpu_score = win_count
if winner == 2:
player_score = win_count
rounds_to_win = max(player_score, cpu_score)
count_round(winner, player, comp, cpu_score, player_score)
I did not run it, but this modifications should do the trick. There are better ways of doing it; maybe using a list to keep the scores and use winner as the index, or an object approach as someone else said, but I do not want to change too much the code.
Also, bear in mind that the round variable in win_counter does nothing.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'd like some assistance on my rock paper scissors game code. I'd like to add a function where the player can choose a specific number of rounds, instead of having a preset number of rounds. I am quite stuck on how to do this and I've just started to pick up Python again, so i am a bit rusty. Thank you so much ! (Please ignore spelling ;D)
CODE:
import random #imports a random moduel for the computer.
game = ["ROCK", "PAPER", "SCISSORS"] #sets the game answers.
count = 0 #game count is set to zero.
score = 0 #player score is set to zero.
computerscore =0 #computers score is set to zero.
print ("Welcome")
while count == 0: #starts game if count is zero.
for i in range (3): #repeats the turns 3 times.
answer = input ("Pick rock, paper or scissors.") #users answer.
print (answer.upper()) # prints the users answer
computer= random.choice(game) #computer picks randomly
print ("Computer picks",computer) #prints the computers choice.
if answer.upper() == "ROCK" and computer == "ROCK": #This whole set of code sets the game that what beats what.
print ("Its a tie!") # prints after each response that who won.
count +=1 #the count variable is increased.
elif answer.upper() == "PAPER" and computer == "PAPER":
print ("Its a tie!")
count +=1
elif answer.upper() == "SCISSORS" and computer == "SCISSORS":
print ("Its a tie!")
count +=1
elif answer.upper() == "PAPER" and computer == "ROCK":
print ("You win!")
count +=1
score +=1 #user score is added.
elif answer.upper() == "PAPER" and computer == "SCISSORS":
print ("You lose!")
count +=1
computerscore +=1 #computers score is added.
elif answer.upper() == "ROCK" and computer == "PAPER":
print ("You lose!")
count +=1
computerscore +=1
elif answer.upper() == "ROCK" and computer == "SCISSORS":
print ("You win!")
count +=1
score +=1
elif answer.upper() == "SCISSORS" and computer == "ROCK":
print ("lose!")
count +=1
computerscore +=1
elif answer.upper() == "SCISSORS" and computer == "PAPER":
print ("You win!")
count +=1
score +=1
if score < computerscore: #prints out at the end who scored how much and who won.
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Computer wins!.")
if score > computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("You win!.")
if score == computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Its a tie!!.")
Change the while count == 0:
to while count < x:
where x is the number of games you want to play
also i suggest to split your code into more functions, it will be much cleaner
Create a rounds variable to store the user input:
rounds = 3
Add this just before the while-loop:
user_input = input('How many rounds do you want to play?')
try:
rounds = int(user_input)
except ValueError:
print('Not a number')
And change your loop's condition to for i in range(rounds):
I am working on Rock, Paper, Scissors in Python 3. I need help trying to implement where the computer keeps track of the users choices so it can tell what the player favors and have an advantage over the player. I also have the computer choosing random using an integer but I need to make the players choice a lowercase 'r' 'p' 's' and a 'q' to quit so it can check for invalid entry and display message and ask again. I don't want to use integers for the player.
Here is what I have:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
Try using a dictionary:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')
I am not sure why I am getting an error that game is not defined:
#!/usr/bin/python
# global variables
wins = 0
losses = 0
draws = 0
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name?')
print 'Hello ',human
# start game
game()
def game():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors, Q - Quit: ')
while humanSelect not in ['R', 'P', 'S', 'Q']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
main()
Because, at the time the statement game() is executed you have not yet reached the statement def game(): and game is, therefore, undefined.
If you move game() to after def game() you will then get a similar error on main() which is harder to fix as you don't appear to be defining a function called main anywhere in the code.
You have to define the function game before you can call it.
def game():
...
game()
Okay, I spent some time tinkering with this today and now have the following:
import random
import string
# global variables
global wins
wins = 0
global losses
losses = 0
global draws
draws = 0
global games
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name? ')
print 'Hello ',human
def readyToPlay():
ready = raw_input('Ready to Play? <Y> or <N> ')
ready = string.upper(ready)
if ready == 'Y':
game()
else:
if games == 0:
print 'Thanks for playing'
exit
else:
gameResults(games, wins, losses, draws)
return
def game():
global games
games += 1
human = humanChoice()
computer = computerChoice()
playResults(human, computer)
readyToPlay()
def humanChoice():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors: ')
while humanSelect not in ['R', 'P', 'S']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
def computerChoice():
computerInt = random.randint(1, 3)
if computerInt == '1':
computerSelect = 'R'
elif computerInt == '2':
computerSelect = 'P'
else:
computerSelect = 'S'
return computerSelect
def playResults(human, computer):
global draws
global wins
global losses
if human == computer:
print 'Draw'
draws += 1
elif human == 'R' and computer == 'P':
print 'My Paper wrapped your Rock, you lose.'
losses += 1
elif human == 'R' and computer == 'S':
print 'Your Rock smashed my Scissors, you win!'
wins += 1
elif human == 'P' and computer == 'S':
print 'My Scissors cut your paper, you lose.'
losses += 1
elif human == 'P' and computer == 'R':
print 'Your Paper covers my Rock, you win!'
wins += 1
elif human == 'S' and computer == 'R':
print 'My Rock smashes your Scissors, you lose.'
losses += 1
elif human == 'S' and computer == 'P':
print 'Your Scissors cut my Paper, you win!'
wins += 1
def gameResults(games, wins, losses, draws):
print 'Total games played', games
print 'Wins: ', wins, ' Losses: ',losses, ' Draws: ', draws
exit
readyToPlay()
I am going to work on the forcing the humanSelect variable to upper case in the same manner that I did with ready, ready = string.upper(ready). I ran into indentation errors earlier today, but will iron that out later tonight.
I do have a question. Is it possible to use a variable between the () of a raw_input function similar to this:
if game == 0:
greeting = 'Would you like to play Rock, Paper, Scissors?'
else:
greeting = 'Play again?'
ready = raw_input(greeting)