[Tutor] paper scissors
bob gailer
bgailer at gmail.com
Fri Sep 23 01:35:09 CEST 2011
On 9/22/2011 1:04 PM, Joseph Shakespeare wrote:
> Hello,
Hi - please use a meaningful subject line - I've changed it this time
>
> I am new Python (about 2 weeks) and need some help. I am making a rock
> paper scissors game that a user can play with the computer by using a
> while loop and if elif else statements. It needs to keep score of the
> amount of losses and wins, and give the user the option to play again
> after each round. I've tried so many different options and I don't
> know what else to try. My problem is making the program loop back
> around when the user selects y(yes) to play again and defining the
> variables at the beginning. Here's my program:
>
I've taken the liberty to extensively edit (and simplify) your program.
Cut 60 lines to 34. Study it - there are a lot of useful ideas in it.
Feel free to ask questions.
The following 3 llnes will NOT get you what you want. You appear to be
confusing variable names with strings.
> y="something"
> play=y
> while play==y:
The while condition is not true - the program will not run.
The proper initialization is:
play = "y"
However I've eliminated the need for even that.
import random
# Use a triple-quoted string rather than a bunch of print statements.
print """Welcome to Rock,Paper, Scissors! This is a game of chance.
The computer randomly picks one of three throws.
Rock beats Scissors, but is beaten by Paper.
Scissors beat Paper, but are beaten by Rock.
Paper beats Rock, but is beaten by Scissors.
You enter:
r for Rock
s for Scissors
p for Paper
q to Quit'"""
wins = loses = 0
while True: # "endless" loop - exited by break statement
player = raw_input("Please pick your throw: (r, s, p, or q ):")
if player == "q":
break # exits the loop
elif player not in "rps": # check for valid entry
print "Invalid entry"
else:
computer= random.choice("rsp") # no need for a list - a string
is a sequence
print "Computer throw:", computer
if player == computer: # testing various conditiions cam be
greatly simplified
print "Tie! Throw again."
elif player + computer in ["rs", "sp", "pr"]:
print "You win! " + player + " beats " + computer
wins += 1 # simpler than wins = wins + 1
else:
print "You lose! " + computer + " beats " + player
loses +=1
print """Game Summary
Wins: %s
Loses:" %s""" % (wins,loses) # using % formatting and triple quoted string
print"Thanks for playing!"
-- Bob Gailer 919-636-4239 Chapel Hill NC
More information about the Tutor
mailing list