Created
March 3, 2024 09:14
-
-
Save shiracamus/16e82d93c5566337a0cb1a8a5e9734f7 to your computer and use it in GitHub Desktop.
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 | |
class Answer: | |
"""出題者""" | |
def __init__(self, digits: int) -> None: | |
"""digits桁の重複しない数を作って隠し持つ""" | |
self._number = ''.join(map(str, random.sample(range(0, 10), digits))) | |
def __str__(self) -> str: | |
"""表示用文字列を返す""" | |
return self._number | |
def __eq__(self, number: str) -> bool: | |
"""numberが正解ならTrue、違えばFalseを返す""" | |
return number == self._number | |
def judge(self, number: str) -> None: | |
"""numberのhit数,blow数を表示する""" | |
hit = blow = 0 | |
for g, a in zip(number, self._number): | |
if g == a: # 同じ桁で同じ数 | |
hit += 1 | |
elif g in self._number: # 違う桁で正解の中に数がある | |
blow += 1 | |
print(f'{hit} HIT {blow} BLOW') | |
class Player: | |
"""回答者""" | |
def guess_number(self, digits: int) -> str: | |
"""digits桁の重複しない数を推測する""" | |
while True: | |
number = input(f'{digits}桁の重複しない数を入力: ') | |
if len(set(number)) == digits and number.isdigit(): | |
return number | |
class HitAndBlow: | |
"""数当てゲーム""" | |
LIMIT = 10 # 回答制限回数 | |
def play(self, digits: int = 3) -> None: | |
"""digits桁の数当てゲームを遊ぶ""" | |
answer = Answer(digits) | |
player = Player() | |
print('Hit and Blowを開始します') | |
for limit in range(self.LIMIT, 0, -1): | |
print(f'あと{limit}回') | |
number = player.guess_number(digits) | |
answer.judge(number) | |
if number == answer: # answer.__eq__(number) | |
print(f'おめでとう!正解の数は{answer}だ!') # answer.__str__() | |
return | |
print(f'おしい!正解の数字は{answer}') # answer.__str__() | |
if __name__ == '__main__': | |
HitAndBlow().play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment