0

I need some help in creating a tally for the following code:

import random

def number_to_name(selection):
    # convert number to a name using if/elif/else
    if   selection == 0: return "rock"
    elif selection == 1: return "Spock"
    elif selection == 2: return "paper"
    elif selection == 3: return "lizard"
    elif selection == 4: return "scissors"
    else:             return None

def name_to_number(name):
    # convert name to number using if/elif/else
    if   name == "rock":     return 0
    elif name == "Spock":    return 1
    elif name == "paper":    return 2
    elif name == "lizard":   return 3
    elif name == "scissors": return 4
    else:                    return None


def rpsls(name): 
    # convert name to player_number using name_to_number

    # compute random guess for comp_number using random.randrange()

    # compute difference of player_number and comp_number modulo five

    # use if/elif/else to determine winner

    # convert comp_number to name using number_to_name

    # print results
    player_number = name_to_number(name)
    comp_number = random.randrange(0, 5)
    difference = (player_number - comp_number)  % 5

    print "\nComputer 2 chooses", name
    print "Computer 1 chooses", number_to_name(comp_number)

    #print "Score was:", difference # XXX

    if   difference == 0: print "Computer 2 and Computer 1 tie!"
    elif difference <= 2: print "Computer 2 wins!"
    else:                 print "Computer 1 wins!"

    print

# test code
print                         "Welcome to..."
import sys
import time
line = "Rock! Paper! Scissors! Lizard! Spock!."
for char in line:
     sys.stdout.write(char)
     time.sleep(0.02)
print "\n<Follow the enter key prompts!>"
raw_input("\n\nPress the enter key to continue.")

rpsls("rock")
raw_input("\n\nPress the enter key to continue.")
rpsls("Spock")
raw_input("\n\nPress the enter key to continue.")
rpsls("paper")
raw_input("\n\nPress the enter key to continue.")
rpsls("lizard")
raw_input("\n\nPress the enter key to continue.")
rpsls("scissors")
raw_input("\n\nPress the enter key to continue.")
rpsls("rock")
raw_input("\n\nPress the enter key to continue.")
rpsls("Spock")
raw_input("\n\nPress the enter key to continue.")
rpsls("paper")
raw_input("\n\nPress the enter key to continue.")
rpsls("lizard")
raw_input("\n\nPress the enter key to continue.")
rpsls("scissors")

raw_input('\n\nPress the enter key to exit')

After each individual game (of rock paper scissors lizard spock) I need a tally to calculate the wins losses and draws of each 'Computer'.

e.g. Computer 2 chooses rock 
Computer 1 chooses paper 
Computer 1 wins!

        > <Computer 1 : Draws = 1
        >               Wins = 3
        >               Losses = 2
        > 
        > Computer 2 : Draws = 1
        >              Wins = 2
        >              Losses = 3>

Or something along those lines, the simpler the better.

Please help, I've only just started python, all help is greatly appreciated.

2
  • Are you allowed to use dictionaries? Aug 16, 2015 at 10:51
  • Yea, we are allowed to use dictionaries.
    – Zinc
    Aug 16, 2015 at 11:50

2 Answers 2

2

As well as adding some score-keeping code I've made your program more compact by using lists, loops, and a dictionary. I've also made it more modular by putting the test code into a main() function.

#!/usr/bin/env python

""" Rock Spock Paper Lizard Scissors

    Written by Zinc & PM 2Ring 2015.08.16

    See http://stackoverflow.com/q/32034190/4014959
"""

import sys
import time
import random

#Build a list to convert move numbers to names
move_names = "rock Spock paper lizard scissors".split()

#Build a dict to convert move names to numbers
move_numbers = dict((name, num) for num, name in enumerate(move_names))

win_messages = [
    "Computer 2 and Computer 1 tie!",
    "Computer 1 wins!",
    "Computer 2 wins!",
]

def rpsls(name): 
    # convert Computer 1 name to player_number
    player_number = move_numbers[name]

    # generate random guess Computer 2
    comp_number = random.randrange(0, 5)

    # compute difference modulo five to determine winner
    difference = (player_number - comp_number) % 5

    print "\nComputer 2 chooses", name
    print "Computer 1 chooses", move_names[comp_number]
    #print "Score was:", difference # XXX

    #Convert difference to result number.
    #0: tie. 1: Computer 1 wins. 2:Computer 2 wins
    if difference == 0: 
        result = 0
    elif difference <= 2:
        result = 2
    else:
        result = 1

    return result


def main():
    banner = "! ".join([word.capitalize() for word in move_names]) + "!.\n"
    print "Welcome to..."
    for char in banner:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.02)

    print "\n<Follow the enter key prompts!>"

    #A list of moves for Computer 1
    computer1_moves = [
        "rock",
        "Spock",
        "paper",
        "lizard",
        "scissors",
        "rock",
        "Spock",
        "paper",
        "lizard",
        "scissors",
    ]

    #Create a list to hold the scores
    scores = [0, 0, 0]

    for name in computer1_moves:
        result = rpsls(name)
        scores[result] += 1 
        print result, win_messages[result], scores
        raw_input("\n\nPress the enter key to continue.")

    print "\nFinal scores"
    print "Computer 1 wins:", scores[1]
    print "Computer 2 wins:", scores[2]
    print "Ties:", scores[0]

    raw_input("\n\nPress the enter key to exit")


if __name__ == "__main__":
    main()

typical output

Welcome to...
Rock! Spock! Paper! Lizard! Scissors!.

<Follow the enter key prompts!>

Computer 2 chooses rock
Computer 1 chooses rock
0 Computer 2 and Computer 1 tie! [1, 0, 0]


Press the enter key to continue.

Computer 2 chooses Spock
Computer 1 chooses lizard
1 Computer 1 wins! [1, 1, 0]


Press the enter key to continue.

Computer 2 chooses paper
Computer 1 chooses paper
0 Computer 2 and Computer 1 tie! [2, 1, 0]


Press the enter key to continue.

Computer 2 chooses lizard
Computer 1 chooses rock
1 Computer 1 wins! [2, 2, 0]


Press the enter key to continue.

Computer 2 chooses scissors
Computer 1 chooses scissors
0 Computer 2 and Computer 1 tie! [3, 2, 0]


Press the enter key to continue.

Computer 2 chooses rock
Computer 1 chooses lizard
2 Computer 2 wins! [3, 2, 1]


Press the enter key to continue.

Computer 2 chooses Spock
Computer 1 chooses rock
2 Computer 2 wins! [3, 2, 2]


Press the enter key to continue.

Computer 2 chooses paper
Computer 1 chooses scissors
1 Computer 1 wins! [3, 3, 2]


Press the enter key to continue.

Computer 2 chooses lizard
Computer 1 chooses lizard
0 Computer 2 and Computer 1 tie! [4, 3, 2]


Press the enter key to continue.

Computer 2 chooses scissors
Computer 1 chooses lizard
2 Computer 2 wins! [4, 3, 3]


Press the enter key to continue.

Final scores
Computer 1 wins: 3
Computer 2 wins: 3
Ties: 4


Press the enter key to exit
4
  • Wow, nice code. Any good links to learn how to use main()? This is because I need to make another 'rock, paper, scissors, spock' code with an input system (player input vs computer) but I have no idea as to how to do it, any tips?
    – Zinc
    Aug 16, 2015 at 11:56
  • @Zinc: The raw_input() function does more than just detecting when the user hits Enter: if the user types a line of text before hitting Enter then that text string becomes the output of raw_input(). Try this: s=raw_input('enter text: ') print s. You should put those 2 commands on 2 separate lines, although in the interpreter it might be more convenient to separate them with a ;.
    – PM 2Ring
    Aug 16, 2015 at 12:03
  • That makes so much sense, thanks for that man.
    – Zinc
    Aug 16, 2015 at 12:05
  • @Zinc: If you think that my answer has helped you, please feel free to accept it. :)
    – PM 2Ring
    Aug 16, 2015 at 12:07
0

Simply create int variables called "playerWinCount", "playerTieCount" and so on. Then add 1 to the correct variable after each game.

playerWinCount = 0 #intergers that hold results of each game
playerTieCount = 0
playerLossCount = 0

computerWinCount = 0
computerTieCount = 0
computerLossCount = 0

if   difference == 0: 
    print "Computer 2 and Computer 1 tie!"
    computerTieCount += 1 # adds one to the variable
    playerTieCount += 1
elif difference <= 2: 
    print "Computer 2 wins!"
    playerWinCount += 1
    computerLossCount += 1


else:
    print "Computer 1 wins!"
    computerWinCount += 1
    playerLossCount += 1

Just remember to reset each variable to 0 after each game.

4
  • Okay, so I tried implementing this in my code but I'm really struggling here bro, please help.
    – Zinc
    Aug 16, 2015 at 11:53
  • Well what exactly is not working? Aug 16, 2015 at 11:55
  • It says 'difference' is not defined and I have been going in circles trying to figure out how to define it.
    – Zinc
    Aug 16, 2015 at 11:57
  • 1
    'difference' is local to the rpsls function and can only be accessed from there. Aug 16, 2015 at 12:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.