Skip to content

Instantly share code, notes, and snippets.

@michaelrice
Created September 29, 2014 16:09
Show Gist options
  • Select an option

  • Save michaelrice/91ed85bb4d3c749e3b8e to your computer and use it in GitHub Desktop.

Select an option

Save michaelrice/91ed85bb4d3c749e3b8e to your computer and use it in GitHub Desktop.
RPSLS
# Copyright 2014 Michael Rice <michael@michaelrice.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#from __future__ import print_function
import random
# Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
NAME_RPSLS = {'rock': 0, 'Spock': 1, 'paper': 2, 'lizard': 3, 'scissors': 4}
NUM_RPSLS = dict(zip(NAME_RPSLS.values(), NAME_RPSLS.keys()))
def name_to_number(name):
return NAME_RPSLS.get(name)
def number_to_name(number):
return NUM_RPSLS.get(number)
def rpsls(player_choice):
# print a blank line to separate consecutive games
print
# convert the player's choice to player_number using the function name_to_number()
player_number = name_to_number(player_choice)
# print out the message for the player's choice
print "Player chooses {0}".format(player_choice)
#+ '->' + str(player_number)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0, len(NAME_RPSLS))
# convert comp_number to comp_choice using the function number_to_name()
comp_choice = number_to_name(comp_number)
# print out the message for computer's choice
print 'Computer chooses {0}'.format(comp_choice)
#+ '->' + str(comp_number)
# compute difference of comp_number and player_number modulo five
modulo_diff = (player_number - comp_number) % 5
if modulo_diff is 0:
print 'Player and computer tie!'
elif modulo_diff > 2:
print 'Computer Wins!'
else:
print 'Player Wins!'
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# always remember to check your completed program against the grading rubric
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment