Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active October 25, 2021 20:47
Show Gist options
  • Save shiracamus/175f08d27a7b4e1306a7416339e8b697 to your computer and use it in GitHub Desktop.
Save shiracamus/175f08d27a7b4e1306a7416339e8b697 to your computer and use it in GitHub Desktop.
import random
class Hand:
def __init__(self, shape, stronger_than):
self.shape = shape
self._stronger_than = stronger_than
def __repr__(self):
return repr(self.shape)
def __str__(self):
return self.shape
def stronger_than(self, enemy):
return self._stronger_than == enemy.shape
HANDS = {1: Hand("グー", "チョキ"),
2: Hand("チョキ", "パー"),
3: Hand("パー", "グー")}
class Player:
def __init__(self, name):
self.name = name
class Human(Player):
def pon(self):
print('選択肢:', HANDS)
while True:
hand = input(f"{self.name}の出す手を入力してください(整数:1, 2, 3): ")
if hand in ("1", "2", "3"):
self.hand = HANDS[int(hand)]
return
class Computer(Player):
def pon(self):
self.hand = random.choice(list(HANDS.values()))
class Janken:
def __init__(self, players):
self.players = players
def play(self):
print("じゃんけんぽん!")
self.pon()
while not (winners := self.winners()):
print("\nあいこでしょ!!")
self.pon()
print(f"{'と'.join(winners)}の勝ち!")
def pon(self):
for player in self.players:
player.pon()
for player in self.players:
print(f"{player.name}の手:{player.hand}")
def winners(self):
hands = set(player.hand for player in self.players)
if len(hands) != 2:
return None
hand1, hand2 = hands
win = hand1 if hand1.stronger_than(hand2) else hand2
return [player.name for player in self.players if player.hand == win]
def janken():
#players = Human("あなた"), Computer(f"コンピュータ")
players = Human("あなた"), *[Computer(f"コンピュータ#{i}") for i in "123"]
Janken(players).play()
if __name__ == "__main__":
janken()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment