CSC111 Top-Down Rock-Paper-Scissors
--D. Thiebaut (talk) 19:15, 5 March 2014 (EST)
# rock, paper, scissors
# D. Thiebaut
# A top-down approach
from random import seed
from random import choice
seed()
HUMAN = "H"
COMPUTER = "C"
TIE = "T"
# pickAletter: lets user pick a letter that is 'R', 'S', or 'P'
# and keeps on prompting until the letter is correctly entered.
def pickALetter():
answer = " "
while answer != "P" and answer != "S" and answer != "R":
answer = input( "> " ).upper().strip()
return answer
# pickRandom: picks a random letter in 'R', 'S', 'P'.
def pickRandom():
OPTIONS = [ 'R', 'S', 'P' ]
answer = choice( OPTIONS )
#print( "Computer picked:" , answer )
return answer
# playRound: plays a round between computer and human. Human
# picks a letter, computer picks a letter at random.
# displays outcome of the game. Returns winner
def playRound():
computer = pickRandom()
human = pickALetter()
# tell the user what the computer picked
print( "I had picked", computer, end=": " )
# checks for ties
if human==computer:
print( "It's a tie!" )
return TIE
# look at conditions where computer wins
if (human=="P" and computer=="S") \
or (human=="R" and computer=="P") \
or (human=="S" and computer=="R"):
print( "I win this round" )
return COMPUTER
# human must have won
print( "You win this round!" )
return HUMAN
# printOutcome: gets the count of rounds won by two users, and
# displays winner.
def printOutcome( humanCount, computerCount ):
if humanCount > computerCount:
print( "You win!" )
else:
print( "I win!" )
def greetings():
print( "Welcome to Rock-Scissors-Paper!" )
print( "-------------------------------" )
# main: plays several rounds of the rock-paper-scissors game
# until one player gets 3 more points than the other. Then
# displays the winner.
def main():
# greets the user, displays the rules
greetings()
# counters for winning rounds
humanCount = 0
computerCount = 0
while ( abs( humanCount - computerCount ) < 3 ):
winner = playRound()
if winner == HUMAN:
humanCount += 1
if winner == COMPUTER:
computerCount += 1
printOutcome( humanCount, computerCount )
main()