Skip to content

Instantly share code, notes, and snippets.

@ixtel
Forked from bbengfort/rpsls.py
Created October 19, 2015 12:56
Show Gist options
  • Save ixtel/d484ef3153cecc66d73a to your computer and use it in GitHub Desktop.
Save ixtel/d484ef3153cecc66d73a to your computer and use it in GitHub Desktop.
Learning to program with Rock, Paper, Scissors, Lizard, Spock; a class based version with an indexed data store for reference.
#!/usr/bin/env python
"""
The 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
"""
import random
class RPSLS(object):
data = ["rock", "Spock", "paper", "lizard", "scissors"]
def number_to_name(self, idx):
"""
Given a number, convert to the name
"""
return self.data[idx]
def name_to_number(self, name):
"""
Given a name, convert to the number
"""
for idx, val in enumerate(self.data):
if name == val: return idx
return None
def computer_guess(self):
return random.randrange(0, 4)
def play(self, name):
"""
Play your hand against the computer to see who wins!
rock > lizard, scissors
Spock > rock, paper
paper > rock, lizard
lizard > scissors, Spock
scissors > paper, Spock
"""
player = self.name_to_number(name)
robot = self.computer_guess()
winner = (player - robot) % len(self.data)
output = "Player plays '%s'\tRobot plays '%s'\tWinner: %s"
if winner == 0:
# Result is 0
winner = "Tie"
elif winner % 2 == 0:
# Result is even
winner = "Player"
else:
# Result is odd
winner ="Robot"
player = self.number_to_name(player)
robot = self.number_to_name(robot)
return output % (player, robot, winner)
if __name__ == "__main__":
game = RPSLS()
print game.play("rock")
print game.play("Spock")
print game.play("paper")
print game.play("lizard")
print game.play("scissors")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment