-
Notifications
You must be signed in to change notification settings - Fork 10
[숫자야구게임] 송채원 미션 제출합니다. #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
""" WalkthroughREADME 파일에는 변경 사항이 없으며, 메인 게임 로직에 대한 수정이 포함되었습니다. Changes
Sequence Diagram(s)sequenceDiagram
participant U as 사용자
participant G as 게임 메인
participant V as 입력 검증 (checkInput)
participant R as 숫자 생성 (generateNum)
participant C as 결과 계산 (calculate)
participant F as 결과 포맷 (format)
U->>G: 게임 시작, 숫자 입력
G->>V: 입력 유효성 검사 요청
V-->>G: 유효성 결과 (정상 또는 오류)
alt 게임 시작 시
G->>R: 3자리 난수 생성 요청
R-->>G: 생성된 난수 전달
end
G->>C: 사용자 입력과 난수 비교 요청
C-->>G: 스트라이크와 볼 결과 전달
G->>F: 결과 메시지 포맷 요청
F-->>G: 포맷된 결과 전달
alt 정답일 경우
G->>U: 승리 메시지 및 재시작/종료 안내
else
G->>U: 지속 진행
end
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (4)
src/baseball/main.py (3)
26-30: 타입 힌트와 문서화 추가 필요함수의 구현은 정확하나, 가독성과 유지보수성을 위해 타입 힌트와 문서화가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
-def generateNum(): +def generateNum() -> str: + """ + 1부터 9까지의 서로 다른 숫자로 이루어진 3자리 수를 생성합니다. + + Returns: + str: 3자리의 무작위 숫자 문자열 + """ num = random.sample(range(1,10), 3) computer = "".join(map(str, num)) return computer
45-50: 계산 로직 가독성 개선 필요계산 로직은 정확하나, 가독성을 위해 변수명과 로직을 더 명확하게 표현할 필요가 있습니다.
다음과 같이 수정하는 것을 제안합니다:
-def calculate(user, computer): +def calculate(user_input: str, target_number: str) -> bool: + """ + 사용자 입력값과 목표 숫자를 비교하여 스트라이크와 볼의 개수를 계산합니다. + + Args: + user_input: 사용자가 입력한 3자리 숫자 + target_number: 맞춰야 할 3자리 숫자 + + Returns: + bool: 정답인 경우 True, 아닌 경우 False + """ - strike = sum(1 for i in range(3) if user[i] == computer[i]) - ball = sum(1 for b in user if b in computer) - strike + strike_count = sum(1 for i in range(3) if user_input[i] == target_number[i]) + ball_count = sum(1 for digit in user_input if digit in target_number) - strike_count - return format(strike, ball) + return format(strike_count, ball_count)
51-64: 결과 출력 함수 개선 필요결과 출력 로직은 정확하나, 함수명과 문서화를 개선할 필요가 있습니다.
다음과 같이 수정하는 것을 제안합니다:
-def format(strike, ball): +def format_result(strike_count: int, ball_count: int) -> bool: + """ + 게임 결과를 포맷팅하여 출력합니다. + + Args: + strike_count: 스트라이크 개수 + ball_count: 볼 개수 + + Returns: + bool: 정답(3 스트라이크)인 경우 True, 아닌 경우 False + """ - if strike == 3: + if strike_count == 3: print("3스트라이크") return True output = [] - if ball > 0: - output.append(f"{ball}볼") - if strike > 0: - output.append(f"{strike}스트라이크") + if ball_count > 0: + output.append(f"{ball_count}볼") + if strike_count > 0: + output.append(f"{strike_count}스트라이크") print(" ".join(output) if output else "낫싱") return Falsedocs/README.md (1)
1-34: 문서 구조화 및 상세 설명 추가 필요문서의 기본 구조는 좋으나, 다음과 같은 개선이 필요합니다:
- 게임 규칙에 대한 구체적인 설명 추가
- 예시 실행 화면 추가
- 에러 상황별 대응 방법 명시
다음과 같이 수정하는 것을 제안합니다:
☑️ 게임 시작 서로 다른 숫자로 이루어진 세 자리 수 생성 함수 구현 플레이어가 세자리인 숫자가 아니거나 동일한 수 입력 받는 경우 ValueError로 종료 입력받은 수에 대한 볼, 스트라이크 계산 함수 구현 및 결과 출력 +## 게임 규칙 +1. 컴퓨터는 1-9 사이의 서로 다른 숫자 3개를 무작위로 선택합니다. +2. 플레이어는 3자리 숫자를 입력합니다. +3. 숫자와 위치가 모두 일치하면 스트라이크, 숫자만 일치하면 볼입니다. +4. 3스트라이크가 되면 게임이 종료됩니다. + +## 예시 실행 화면 +``` +숫자 야구 게임을 시작합니다. +숫자를 입력해주세요 : 123 +1볼 1스트라이크 +숫자를 입력해주세요 : 456 +낫싱 +``` + +## 에러 처리 +- 3자리가 아닌 숫자 입력 시: "3자리 숫자만 입력 가능합니다." +- 중복된 숫자 입력 시: "서로 다른 숫자만 입력 가능합니다." +- 숫자가 아닌 값 입력 시: "숫자만 입력 가능합니다." ☑️ 게임 종료
src/baseball/main.py
Outdated
| def checkInput(user) : | ||
| if not user.isdigit() : | ||
| raise ValueError | ||
|
|
||
| num = int(user) | ||
| if num < 100 or num > 999 : | ||
| raise ValueError | ||
|
|
||
| check = list(user) | ||
| if len(set(check)) != 3 : | ||
| raise ValueError | ||
|
|
||
| return True | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
입력 검증 에러 메시지 개선 필요
입력 검증 로직은 정확하나, 각 검증 단계별로 구체적인 에러 메시지가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
-def checkInput(user):
+def checkInput(user: str) -> bool:
+ """
+ 사용자 입력값이 유효한 3자리 숫자인지 검증합니다.
+
+ Args:
+ user: 사용자가 입력한 문자열
+
+ Returns:
+ bool: 입력값이 유효한 경우 True
+
+ Raises:
+ ValueError: 입력값이 유효하지 않은 경우
+ """
if not user.isdigit():
- raise ValueError
+ raise ValueError("숫자만 입력 가능합니다.")
num = int(user)
if num < 100 or num > 999:
- raise ValueError
+ raise ValueError("3자리 숫자만 입력 가능합니다.")
check = list(user)
if len(set(check)) != 3:
- raise ValueError
+ raise ValueError("서로 다른 숫자만 입력 가능합니다.")
return True📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def checkInput(user) : | |
| if not user.isdigit() : | |
| raise ValueError | |
| num = int(user) | |
| if num < 100 or num > 999 : | |
| raise ValueError | |
| check = list(user) | |
| if len(set(check)) != 3 : | |
| raise ValueError | |
| return True | |
| def checkInput(user: str) -> bool: | |
| """ | |
| 사용자 입력값이 유효한 3자리 숫자인지 검증합니다. | |
| Args: | |
| user: 사용자가 입력한 문자열 | |
| Returns: | |
| bool: 입력값이 유효한 경우 True | |
| Raises: | |
| ValueError: 입력값이 유효하지 않은 경우 | |
| """ | |
| if not user.isdigit(): | |
| raise ValueError("숫자만 입력 가능합니다.") | |
| num = int(user) | |
| if num < 100 or num > 999: | |
| raise ValueError("3자리 숫자만 입력 가능합니다.") | |
| check = list(user) | |
| if len(set(check)) != 3: | |
| raise ValueError("서로 다른 숫자만 입력 가능합니다.") | |
| return True |
| def main(): | ||
| """ | ||
| 프로그램의 진입점 함수. | ||
| 여기에서 전체 프로그램 로직을 시작합니다. | ||
| """ | ||
| # 프로그램의 메인 로직을 여기에 구현 | ||
| while True : | ||
| computer = generateNum() | ||
|
|
||
| print("숫자 야구 게임을 시작합니다.") | ||
| while(True) : | ||
| print("숫자를 입력해주세요 : ", end='') | ||
| user = input() | ||
| checkInput(user) | ||
|
|
||
| if (calculate(user, computer)) : | ||
| break | ||
|
|
||
| print("3개의 숫자를 모두 맞히셨습니다! 게임 종료") | ||
| print("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.") | ||
| select = input() | ||
| if select == "1" : | ||
| continue | ||
| elif select == "2" : | ||
| break | ||
| else : | ||
| raise ValueError | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
메인 게임 로직 개선 필요
게임의 전반적인 흐름은 잘 구현되어 있으나, 다음과 같은 개선이 필요합니다:
- 에러 처리를 try-except 블록으로 감싸서 사용자 친화적인 에러 메시지를 표시해야 합니다.
- 매직 넘버(1, 2)를 상수로 정의하여 가독성을 높여야 합니다.
다음과 같이 수정하는 것을 제안합니다:
+RESTART_GAME = "1"
+END_GAME = "2"
def main():
+ try:
while True:
computer = generateNum()
print("숫자 야구 게임을 시작합니다.")
while(True):
print("숫자를 입력해주세요 : ", end='')
user = input()
checkInput(user)
if (calculate(user, computer)):
break
print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
print("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
select = input()
- if select == "1":
+ if select == RESTART_GAME:
continue
- elif select == "2":
+ elif select == END_GAME:
break
else:
raise ValueError
+ except ValueError:
+ print("잘못된 입력입니다. 게임을 종료합니다.")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def main(): | |
| """ | |
| 프로그램의 진입점 함수. | |
| 여기에서 전체 프로그램 로직을 시작합니다. | |
| """ | |
| # 프로그램의 메인 로직을 여기에 구현 | |
| while True : | |
| computer = generateNum() | |
| print("숫자 야구 게임을 시작합니다.") | |
| while(True) : | |
| print("숫자를 입력해주세요 : ", end='') | |
| user = input() | |
| checkInput(user) | |
| if (calculate(user, computer)) : | |
| break | |
| print("3개의 숫자를 모두 맞히셨습니다! 게임 종료") | |
| print("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.") | |
| select = input() | |
| if select == "1" : | |
| continue | |
| elif select == "2" : | |
| break | |
| else : | |
| raise ValueError | |
| RESTART_GAME = "1" | |
| END_GAME = "2" | |
| def main(): | |
| try: | |
| while True: | |
| computer = generateNum() | |
| print("숫자 야구 게임을 시작합니다.") | |
| while(True): | |
| print("숫자를 입력해주세요 : ", end='') | |
| user = input() | |
| checkInput(user) | |
| if (calculate(user, computer)): | |
| break | |
| print("3개의 숫자를 모두 맞히셨습니다! 게임 종료") | |
| print("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.") | |
| select = input() | |
| if select == RESTART_GAME: | |
| continue | |
| elif select == END_GAME: | |
| break | |
| else: | |
| raise ValueError | |
| except ValueError: | |
| print("잘못된 입력입니다. 게임을 종료합니다.") |
…rs entered by the player
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/baseball/main.py (1)
5-27: 🛠️ Refactor suggestion예외 처리 로직 추가 필요
게임의 전체적인 흐름은 잘 구현되어 있으나, 사용자 입력 오류에 대한 처리가 누락되어 있습니다.
다음과 같이 try-except 블록을 추가하는 것을 제안합니다:
def main(): + try: while True: computer = generateNum() # ... 기존 코드 ... + except ValueError as e: + print(f"오류가 발생했습니다: {e}") + print("게임을 종료합니다.")
🧹 Nitpick comments (3)
src/baseball/main.py (3)
28-31: 타입 힌트와 문서화 추가 필요함수의 구현은 정확하나, 타입 힌트와 문서화가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
-def generateNum() : +def generateNum() -> str: + """ + 1부터 9까지의 서로 다른 숫자 3개로 구성된 문자열을 생성합니다. + + Returns: + str: 3자리의 무작위 숫자로 구성된 문자열 + """ num = random.sample(range(1,10), 3) computer = "".join(map(str, num)) return computer
47-51: 타입 힌트 추가와 가독성 개선 필요함수의 로직은 정확하나, 타입 힌트가 없고 변수명이 더 명확할 수 있습니다.
다음과 같이 수정하는 것을 제안합니다:
-def calculate(user, computer) : # ball, strike 계산 +def calculate(user_input: str, computer_number: str) -> bool: + """ + 사용자 입력과 컴퓨터 숫자를 비교하여 스트라이크와 볼의 개수를 계산합니다. + + Args: + user_input: 사용자가 입력한 3자리 숫자 + computer_number: 컴퓨터가 생성한 3자리 숫자 + + Returns: + bool: 3스트라이크인 경우 True, 그 외의 경우 False + """ - strike = sum(1 for i in range(3) if user[i] == computer[i]) - ball = sum(1 for b in user if b in computer) - strike + strike_count = sum(1 for i in range(3) if user_input[i] == computer_number[i]) + ball_count = sum(1 for digit in user_input if digit in computer_number) - strike_count - return format(strike, ball) + return format(strike_count, ball_count)
53-65: 타입 힌트와 문서화 추가 필요출력 포맷팅 로직은 잘 구현되어 있으나, 타입 힌트와 문서화가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
-def format(strike, ball) : # 출력 포맷 +def format(strike: int, ball: int) -> bool: + """ + 스트라이크와 볼의 개수를 기반으로 결과 메시지를 출력합니다. + + Args: + strike: 스트라이크 개수 + ball: 볼 개수 + + Returns: + bool: 3스트라이크인 경우 True, 그 외의 경우 False + """ if strike == 3: print("3스트라이크") return True output = [] if ball > 0: output.append(f"{ball}볼") if strike > 0: output.append(f"{strike}스트라이크") print(" ".join(output) if output else "낫싱") return False
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/baseball/main.py(1 hunks)
🔇 Additional comments (1)
src/baseball/main.py (1)
1-3: 상수 정의와 임포트가 적절합니다!매직 넘버를 상수로 분리하여 코드의 가독성이 향상되었습니다.
Codecov ReportAttention: Patch coverage is
|
d859158 to
2f79f30
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/baseball/main.py (2)
28-31: 타입 힌트와 문서화가 필요합니다함수의 목적과 반환 값을 명확히 하기 위해 타입 힌트와 문서화를 추가하는 것이 좋습니다.
다음과 같이 수정하는 것을 제안합니다:
-def generateNum() : +def generateNum() -> str: + """ + 서로 다른 세 자리 숫자를 무작위로 생성합니다. + + Returns: + str: 생성된 세 자리 숫자 문자열 + """ num = random.sample(range(1,10), 3) computer = "".join(map(str, num)) return computer
47-65: 게임 로직 함수들의 문서화가 필요합니다함수들의 동작은 정확하나, 타입 힌트와 자세한 문서화가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
-def calculate(user, computer) : +def calculate(user: str, computer: str) -> bool: + """ + 사용자 입력과 정답을 비교하여 볼과 스트라이크를 계산합니다. + + Args: + user: 사용자가 입력한 숫자 + computer: 정답 숫자 + + Returns: + bool: 정답 여부 + """ -def format(strike, ball) : +def format(strike: int, ball: int) -> bool: + """ + 게임 결과를 형식에 맞게 출력합니다. + + Args: + strike: 스트라이크 개수 + ball: 볼 개수 + + Returns: + bool: 게임 종료 여부 + """
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
docs/README.md(1 hunks)src/baseball/main.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/README.md
🔇 Additional comments (4)
src/baseball/main.py (4)
1-3: 상수 정의가 잘 되어있습니다!게임 제어를 위한 상수를 모듈 레벨에서 정의한 것이 좋은 실천 사례입니다.
5-27: 예외 처리 개선이 필요합니다메인 게임 로직에 예외 처리가 누락되어 있습니다. 사용자 경험 향상을 위해 try-except 블록을 추가해야 합니다.
다음과 같이 수정하는 것을 제안합니다:
def main(): + try: while True: computer = generateNum() # ... 기존 코드 ... + except ValueError as e: + print(f"오류가 발생했습니다: {e}") + print("게임을 종료합니다.")
33-45: 입력 검증이 잘 구현되어 있습니다!타입 힌트와 명확한 에러 메시지를 포함한 견고한 입력 검증 구현이 잘 되어 있습니다.
67-68: 메인 실행 검사가 올바르게 구현되어 있습니다!Python의 표준적인 메인 모듈 실행 검사가 잘 구현되어 있습니다.
Summary by CodeRabbit
새로운 기능
문서 업데이트