Last active
April 12, 2020 20:36
-
-
Save ricardodani/9e0be5c13c7820c31b81e3ac4cb4836a to your computer and use it in GitHub Desktop.
pedra papel tesoura
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from ansi.colour import fg, bg | |
PEDRA = 0 | |
TESOURA = 1 | |
PAPEL = 2 | |
WINNERS_LOOSERS = {PEDRA: TESOURA, TESOURA: PAPEL, PAPEL: PEDRA} | |
LABELS = { | |
TESOURA: 'Tesoura', | |
PEDRA: 'Pedra', | |
PAPEL: 'Papel' | |
} | |
CHOICES = list(LABELS.keys()) | |
def get_label(label): | |
return LABELS[label] | |
def get_user_input(): | |
return input( | |
fg.yellow( | |
' | '.join( | |
f"{choice} > {get_label(choice)}" | |
for choice in CHOICES | |
) + ' => ' | |
) | |
) | |
def get_winner(player_1, player_2): | |
if player_1 == player_2: | |
return | |
return player_1 if WINNERS_LOOSERS[player_1] == player_2 else player_2 | |
wins, looses, draws = 0, 0, 0 | |
def print_stats(): | |
print() | |
print(bg.green(f"Você ganhou {wins} vezes.")) | |
print(bg.red(f"Computador ganhou {looses} vezes")) | |
print(bg.white(fg.black(f"Empate {draws} vezes"))) | |
if looses: | |
aproveitamento = (wins/looses) * 100 | |
elif wins: | |
aproveitamento = float('inf') | |
if aproveitamento == float('inf'): | |
print(bg.green(fg.boldblack(f"Você foi o campeão invicto (Aproveitamento tendendo ao infinito)!!!"))) | |
elif wins > looses: | |
print(bg.green(f"Você foi o campeão (Seu aproveitamento: {aproveitamento}%)")) | |
elif wins < looses: | |
print(bg.red(f"Computador foi o campeão (Seu aproveitamento: {aproveitamento}%)")) | |
else: | |
print(bg.white(fg.black(f"Não houve campeão"))) | |
while True: | |
try: | |
user_choice = int(get_user_input()) | |
if user_choice not in CHOICES: | |
raise ValueError | |
except ValueError: | |
print(bg.yellow(fg.black(f"Opção inválida. Disponíveis: {LABELS!r}"))) | |
except KeyboardInterrupt: | |
print_stats() | |
break | |
else: | |
computer_choice = random.choice(CHOICES) | |
print(bg.cyan(fg.black( | |
f"Você escolheu {get_label(user_choice)} e o computador escolheu {get_label(computer_choice)} !" | |
))) | |
winner = get_winner(user_choice, computer_choice) | |
if winner is None: | |
draws += 1 | |
print(bg.white(fg.black("Empate"))) | |
elif winner == user_choice: | |
wins += 1 | |
print(bg.green("Você ganhou")) | |
else: | |
looses += 1 | |
print(bg.red("Computador ganhou")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment