• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

혼자 클래스로 구현해봤는데 깔끔하지가 않습니다.

21.09.27 22:12 작성 조회수 109

2

import random
import os

# 게임 초기화
os.system("clear")

print("*"*60)
print("숫자야구게임을 시작하겠습니다.")
print("*"*60)

# 사용자 입력
def user_input(cast=str):
    while True:
        user_num=cast(input("0~9까지 숫자를 겹치지 않게 3개를 입력해주세요. >> "))
        if user_num.isnumeric() and len(user_num)==3:
            return user_num
        else:
            continue

# 숫자생성
def com_input():
    com_num=""
    com_n=str(random.randint(0,9))
    for i in range(3):
        while com_n in com_num:
            com_n=str(random.randint(0,9))
        com_num+=com_n
    return com_num

# 게임시작
def game(*args):
    count_strike=0
    count_ball=0
    for i in range(3):
        for j in range(3):
            if args[0][i] == args[1][j] and i==j:
                count_strike+=1
            elif args[0][i] == args[1][j] and i!=j:
                count_ball+=1
    return count_strike, count_ball

# 게임결과
def result(*args):
    if args[0]==0 and args[1]==0:
        print("3아웃입니다.")
    else:
        hint=""
        if args[0]>0:
            hint+="{} 스트라이크".format(args[0])
        if args[1]>0:
            hint+=" {} 볼".format(args[1])
        print(hint.strip())

# 종합
go=[0]
com_num=com_input()
while go[0]<3:
    user_num=user_input()
    go=game(user_num,com_num)
    result(go[0],go[1])
print("3 스트라이크!! 게임종료")

 

홀로 4번쯤 연습하다가 마지막 한번은 클래스로 구현해봤는데 깔끔하게 표현되지가 않습니다 ㅠ

 

더 깔끔하게 코딩가능하다면 조언 부탁드리겠습니다..

 

답변 1

답변을 작성해보세요.

0

위의 코딩은 클래스가 아닌 함수로 구현하신겁니다. ^^ 어쨌든 중요한건 아주 잘!!! 작성하셨습니다.

그래서 올려주신 코드를 참고해서 말씀하신 "클래스" 로 구현한 코드를 첨부하니 이런 스타일도 참고해보시기 바랍니다. 고생하셨습니다.

 

import random
import os

class GuessNumber():
    def __init__(self):
        self.com_num, self.user_num = "", ""
        self.count_strike,  self.count_ball = 0, 0
        self.is_end = False
        self.limit_count = 10
        self.intro()
        self.make_number()
    
    def intro(self):
        print("*"*60)
        print("숫자야구게임을 시작하겠습니다.")
        print("*"*60)

    def make_number(self):
        self.com_num = ""
        com_n = str(random.randint(0, 9))
        for i in range(3):
            while com_n in self.com_num:
                com_n = str(random.randint(0, 9))
            self.com_num += com_n

    def user_input(self, cast=str):
        while True:
            self.user_num=cast(input("0~9까지 숫자를 겹치지 않게 3개를 입력해주세요. >> "))
            if self.user_num.isnumeric() and len(self.user_num)==3:
                return self.game()
            else:
                continue

    def game(self):
        self.count_strike = self.count_ball = 0
        for i in range(3):
            for j in range(3):
                if self.com_num[i] == self.user_num[j] and i == j:
                    self.count_strike += 1
                elif self.com_num[i] == self.user_num[j] and i != j:
                    self.count_ball += 1
        self.result()

    def result(self):
        self.limit_count -= 1
        if self.count_strike == 0 and self.count_ball == 0:
            print("3 아웃 입니다.", "[{} 번의 기회가 남았습니다.]".format(self.limit_count))
        else:
            hint=""
            if self.count_strike > 0:
                hint+="{} 스트라이크".format(self.count_strike)
            if self.count_ball > 0:
                hint+=" {} 볼".format(self.count_ball)
            print(hint.strip(), "[{} 번의 기회가 남았습니다.]".format(self.limit_count))
        if self.count_strike == 3:
            self.is_end = True
        if self.limit_count <= 0:
            print(">>>>> 모든 기회를 소진하였습니다 <<<<<")
            self.is_end = True

# 게임을 클래스화
game = GuessNumber()
while not game.is_end:
    game.user_input()
print("게임종료")
역학자님의 프로필

역학자

질문자

2021.10.05

와 역시 이렇게 깔끔해질 수 있군요. 마치 제 방을 보는것처럼..

빠르고 깔끔한 답변, 그리고 예시코딩 감사드립니다~