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()")
Related
I'm trying to create a rock paper scissors game for a class assignment with Python, but I can't get the result out.
The game is supposed to start with the 1) user's input, 2) show what computer randomly chose, 3) the result (You win, You lose, or Tie with how you won or lost), 4) then ask if you want to Play again, and 5) finally escape.
I did succeed on the first 2 parts, but I can't figure out why 3, 4, 5 is not printing...
The result after showing what the computer played(2), it says 'None' then it loops back to (1) getting the input from the user.
Below is the code. Please advise me on how to fix them. Thank you so much!!
import random
while True :
player = input("Enter a number (0 for rock, 1 for paper, 2 for scissors) >>")
RPS = [0,1,2]
computer = random.choics(RPS)
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
print("The computer played", RPC_dict.get(computer))
def game(player, computer):
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
if player == computer:
print("Tie!")
elif player == 0:
if computer == 1:
print("You lose!", RPS_dict.get(computer), 'covers', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'cut', RPS_dict.get(computer))
elif player == 1:
if computer == 2:
print("You lose!", RPS_dict.get(computer), 'cut', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'covers', RPS_dict.get(computer))
game(player, computer)
print(game(player, computer))
again = input("Play again? 0 for no, 1 for yes\n")
Your function should be outside your while loop and you don't need to call it within a print statement...
import random
def game(player, computer):
if player == computer:
print('game tied')
else:
if (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2):
print('you win')
else:
print('computer wins')
def choice(x):
y = None
if x == 1:
y = 'rock'
elif x == 2:
y = 'paper'
elif x == 3:
y = 'scissors'
return y
playing = True
while playing == True:
player_input = int(input("Enter 1 for rock, 2 for paper, 3 for scissors"))
print('You chose:'+ choice(player_input))
computer_input = random.choice([1,2,3])
print('Computer chose:'+ choice(computer_input))
game(player_input, computer_input)
restart = int(input("Enter 1 to play again or 2 to quit"))
if restart == 2:
playing = False
I wanted to make a simple Rock, Paper, Scissor game in Python. It goes well with the game, but the final scores are always being showed as a 0.
I wanted to show a smaller section of the code but, I don't know where the problem lies, so I am sorry for the length of the code.
I am still a novice learner, so please pardon me if the question is too silly or the code is not well formatted.
#Rock-Paper-Scissor Game
import random
print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")
userTally = 0
compTally = 0
def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])
if userInput == "R": #User Inputs R for Rock
if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1
elif userInput == "P": #User Inputs P for Paper
if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1
elif userInput == "S": #User Inputs S for Scissor
if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)
def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:
gameProcess(0, 0)
tryNum = tryNum + 1
tryCount()
print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()
You pass 0, 0 to gameProcess, which you treat as the scores within the function, and then return them modified, but you do not actually use the return value in the only place you call gameProcess (in tryCount), so the global userTally, compTally variables remain unchanged.
This is how you should change tryCount:
def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:
userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1
import random
name = input("What is your name?")
print ("Welcome to Rock Paper Scissors", name, "!")
def computerThrow():
throwOptions = ["rock","paper","scissors"]
randomChoice = random.randint(0,2)
return throwOptions [randomChoice]
def playerThrow():
player = input("rock, paper, scissors?")
return player
def compareThrows(player, computer):
if player == computer:
return("tie")
elif player == "rock":
if computer == "scissors":
return("win")
else:
return("lose")
elif player == "scissors":
if computer == "paper":
return("win")
else:
return("lose")
elif player == "paper":
if computer == "rock":
return("win")
else:
return("lose")
else:
return("invalid")
def printMatchOutcome(result, player, computer):
if result == "win":
print(player, "beats", computer, " — You win!")
if result == "lose":
print (computer,"beats",player, "- You lose!")
if result == "tie":
print("tie match!")
if result == "invalid":
print ("invalid...try again")
def oneRound():
player = playerThrow()
print("You threw:",player)
computer = computerThrow()
print("Computer threw:",computer)
compare = compareThrows(player, computer)
printMatchOutcome(compare, player, computer)
#define counter variable
gamesPlayed = 0
playerWins = 0
computerWins = 0
userWantsToPlay = True
while userWantsToPlay:
oneRound()
response = input("Do you want to play again? (yes / no)")
if response == 'yes':
userWantsToPlay = True
else:
userWantsToPlay = False
print("Thanks for playing!")
def score(result):
oneRound()
if result == "win":
return playerWins + 1
elif result == "lose":
return computerWins + 1
I am trying to add a score counter to my game so that once userWantsToPlay = False it will display the number of games played, and the score for the computer and the player. I have started it as a function but I am not sure if that is even right? How would I go about this?
I made a simple Rock Paper Scissors program, and I need to add a certain condition to this program.. I have to Let the
user play continuously until either the user or the computer wins more than two times in a row.I tried to find the answer in and out but unfortunately couldn't find it..
First off I tried
gameOver = False
playerScore = 0
computerScore = 0
and added
while not gameOver:
main()
if playerScore == 2 :
gameOver = True
and also added playerScore += 1 to the if statements..
But wouldn't work ...
any advise would help and much appreciated in advance.. cheers!
And here is my code..
import random
import sys
def main():
player = input("Enter your choice in number (rock 1 / paper 2 / scissors 0) :")
if (player == 0):
player = "scissors"
elif (player == 1):
player = "rock"
elif (player == 2):
player = "paper"
else:
print("Invalid Input Quitting...")
sys.exit(0)
computer = random.randint(0,2)
if (computer == 0):
computer = "scissors"
elif (computer == 1):
computer = "rock"
elif (computer == 2):
computer = "paper"
if (player == computer):
print("Player is ",player, "Computer is ",computer," You Draw!")
elif (player == "rock"):
if (computer == "paper"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
elif (player == "paper"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Win!")
else:
print("Player is ",player, "Computer is ",computer," You Lost!")
elif (player == "scissors"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
If you have your main() function return a value corresponding to who won, you could do:
gameOver = False
playerScore = 0
computerScore = 0
while not gameOver:
player_wins = main()
if player_wins == True:
playerScore += 1
computerScore = 0
if player_wins == False:
playerScore = 0
computerScore += 1
if player_wins == None:
# Draw, do nothing to the scores
pass
if playerScore == 2 or computerScore == 2:
print("Game over")
print(" playerScore:", playerScore)
print(" computerScore:", computerScore)
gameOver = True
Note that I had it return True if the player won, False if the computer won, and None if it was a draw.
I think you are asking only a schema:
(this is no true code)
Program starts:
gameover = False
lastWinner = ""
Loop until gameover == True
ask for player answer
make the random choice of the computer
winner = "asigned winner"
if lastWinner == winner:
gameover = True
Print something cool about who is the winner
else:
lastWinner = winner
You may be getting an error when attempting to modify the globals, but from your example it's not entirely clear.
If you try to modify playerScore or computerScore in your main() method, it'll yell at you unless you have a statement like:
global computerScore
before you modify it.
Also, avoid repeating yourself in your code. I was able to trim much of your code out by using the following:
computerWins = False
print "Player is %s; Computer is %s" % (computer, player)
if (player == computer):
print "Draw"
return 0
elif (player == "rock"):
computerWins = computer == "paper"
elif (player == "paper"):
computerWins = computer == "scissors"
elif (player == "scissors"):
computerWins = computer == "rock"
if computerWins:
global computerScore
computerScore = computerScore + 1
print "Computer wins"
else:
global playerScore
playerScore = playerScore + 1
print "You win"
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.)