Question 5: A Python solution
class RpsContestant:
"""A Rock-paper-scissors contestant"""
winner = {
'rock:rock': 0,
'rock:paper': 2,
'rock:scissors': 1,
'paper:rock': 1,
'paper:paper': 0,
'paper:scissors': 2,
'scissors:rock': 2,
'scissors:paper': 1,
'scissors:scissors': 0,
}
def __init__(self, filename):
self.filename = filename
choices = []
for line in open(filename):
if 'Name=' in line:
self.name = line[5:-1]
else:
choices.append(line[:-1])
choices.reverse()
self.choices = choices
def next_choice(self):
return self.choices.pop()
def set_token(self, loser):
self.token = self.name.upper() + loser.name.upper()
def engage(self, player2):
player1 = self
print(" {} vs {} ".format(player1.name, player2.name))
while True:
pair = player1.next_choice() + ':' + player2.next_choice()
result = self.winner[pair]
if result == 1:
print(" {} - {} wins!".format(pair, player1.name))
player1.set_token(player2)
return player1
elif result == 2:
print(" {} - {} wins!".format(pair, player2.name))
player2.set_token(player1)
return player2
else:
print(" {} - draw".format(pair))
from os import system, chdir
import glob
system("rm -rf work; mkdir work")
chdir("work")
system('tar xfz 05-rock-paper-scissors')
filenames = sorted(glob.glob("contestants/contestant*"))
players = [ RpsContestant(f) for f in filenames ]
round = 1
while len(players) > 1:
print("\nRound {}".format(round))
winners = []
while len(players) > 0:
player1 = players.pop(0)
player2 = players.pop(0)
winners.append(player1.engage(player2))
round += 1
players = winners
print("\nToken: {}".format(players[0].token))