Skip to content

Conversation

@chaerishme
Copy link

@chaerishme chaerishme commented Feb 4, 2025

Summary by CodeRabbit

  • 새로운 기능

    • 완전한 숫자 야구 게임 흐름이 구현되어, 사용자가 숫자를 입력하고 결과(스트라이크/볼)를 확인할 수 있습니다.
    • 게임 승리 후 재시작이나 종료를 선택할 수 있는 옵션이 제공됩니다.
    • 사용자 입력에 대한 유효성 검사가 추가되어, 잘못된 선택 시 오류 메시지가 표시됩니다.
  • 문서 업데이트

    • README 파일에 변경 사항이 없으며, 게임 작동 방식에 대한 추가 설명이 없습니다.

@coderabbitai
Copy link

coderabbitai bot commented Feb 4, 2025

"""

Walkthrough

README 파일에는 변경 사항이 없으며, 메인 게임 로직에 대한 수정이 포함되었습니다. src/baseball/main.py에서 main 함수가 구조화된 루프로 변경되어 사용자 입력을 지속적으로 요청하고 검증하며, 무작위로 생성된 숫자와 비교하는 완전한 게임 루프가 구현되었습니다. 새로운 함수들이 추가되어 입력 검증, 난수 생성, 결과 계산 및 출력 포맷 기능이 포함되었으며, 잘못된 입력에 대해서는 ValueError가 발생합니다.

Changes

파일/경로 변경 내용 요약
docs/README.md 변경 없음
src/baseball/main.py 게임 루프 도입, 사용자 입력 검증(checkInput), 3자리 숫자 생성(generateNum), 결과 계산(calculate), 결과 포맷팅(format) 및 게임 재시작/종료 로직 구현

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
Loading

Poem

귀여운 토끼가 뛰놀며 외치네,
코드의 숲 속에서 변화의 향기 느껴지고,
야구공처럼 굴러가는 새 게임 로직,
입력과 난수, 스트라이크와 볼 춤추며,
"모두 환영이야!"라며 말한 변화의 마법,
작은 오류도 토끼 발자국처럼 사뿐히 사라지길.
"""

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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 False
docs/README.md (1)

1-34: 문서 구조화 및 상세 설명 추가 필요

문서의 기본 구조는 좋으나, 다음과 같은 개선이 필요합니다:

  1. 게임 규칙에 대한 구체적인 설명 추가
  2. 예시 실행 화면 추가
  3. 에러 상황별 대응 방법 명시

다음과 같이 수정하는 것을 제안합니다:

 ☑️ 게임 시작
   
 서로 다른 숫자로 이루어진 세 자리 수 생성 함수 구현
 
 플레이어가 세자리인 숫자가 아니거나 동일한 수 입력 받는 경우 ValueError로 종료
 
 입력받은 수에 대한 볼, 스트라이크 계산 함수 구현 및 결과 출력
 
+## 게임 규칙
+1. 컴퓨터는 1-9 사이의 서로 다른 숫자 3개를 무작위로 선택합니다.
+2. 플레이어는 3자리 숫자를 입력합니다.
+3. 숫자와 위치가 모두 일치하면 스트라이크, 숫자만 일치하면 볼입니다.
+4. 3스트라이크가 되면 게임이 종료됩니다.
+
+## 예시 실행 화면
+```
+숫자 야구 게임을 시작합니다.
+숫자를 입력해주세요 : 123
+1볼 1스트라이크
+숫자를 입력해주세요 : 456
+낫싱
+```
+
+## 에러 처리
+- 3자리가 아닌 숫자 입력 시: "3자리 숫자만 입력 가능합니다."
+- 중복된 숫자 입력 시: "서로 다른 숫자만 입력 가능합니다."
+- 숫자가 아닌 값 입력 시: "숫자만 입력 가능합니다."
 
 ☑️ 게임 종료
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b9f52ee and d2199c7.

📒 Files selected for processing (2)
  • docs/README.md (1 hunks)
  • src/baseball/main.py (1 hunks)

Comment on lines 31 to 46
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

Copy link

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.

Suggested change
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

Comment on lines 3 to 27
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

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

메인 게임 로직 개선 필요

게임의 전반적인 흐름은 잘 구현되어 있으나, 다음과 같은 개선이 필요합니다:

  1. 에러 처리를 try-except 블록으로 감싸서 사용자 친화적인 에러 메시지를 표시해야 합니다.
  2. 매직 넘버(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.

Suggested change
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("잘못된 입력입니다. 게임을 종료합니다.")

AI-WonYJ added a commit to AI-WonYJ/python-baseball that referenced this pull request Feb 4, 2025
Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between d2199c7 and bcb11cb.

📒 Files selected for processing (1)
  • src/baseball/main.py (1 hunks)
🔇 Additional comments (1)
src/baseball/main.py (1)

1-3: 상수 정의와 임포트가 적절합니다!

매직 넘버를 상수로 분리하여 코드의 가독성이 향상되었습니다.

@chaerishme chaerishme changed the title Chaerishme [$숫자야구게임] $송채원 미션 제출합니다. Feb 5, 2025
@chaerishme chaerishme changed the title [$숫자야구게임] $송채원 미션 제출합니다. [숫자야구게임] 송채원 미션 제출합니다. Feb 5, 2025
@codecov
Copy link

codecov bot commented Feb 6, 2025

Codecov Report

Attention: Patch coverage is 86.00000% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/baseball/main.py 86.00% 4 Missing and 3 partials ⚠️
Files with missing lines Coverage Δ
src/baseball/main.py 84.61% <86.00%> (ø)

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between d859158 and 8fd5cd3.

📒 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의 표준적인 메인 모듈 실행 검사가 잘 구현되어 있습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants