Skip to content

Conversation

kimseonggyu03
Copy link

@kimseonggyu03 kimseonggyu03 commented Dec 30, 2024

Summary by CodeRabbit

  • New Features

    • Implemented a number guessing game with random number generation.
    • Added user input validation for three-digit numbers.
    • Introduced strike and ball comparison mechanics.
    • Created an interactive game loop with a restart option.
  • Documentation

    • Updated README with detailed game functionality and rules.

@coderabbitai
Copy link

coderabbitai bot commented Dec 30, 2024

Walkthrough

The pull request introduces a comprehensive implementation of a number guessing game in Python. The changes focus on developing a game where players attempt to guess a randomly generated three-digit number with unique digits. The implementation includes robust input validation, comparison logic for strikes and balls, and an interactive game loop that allows players to play multiple rounds and provides clear feedback on their guesses.

Changes

File Change Summary
docs/README.md Added detailed documentation for the number guessing game, describing its core functionalities including random number generation, input validation, comparison logic, and game result output.
src/baseball/main.py Completely refactored to implement game logic with new functions:
- player_input(): Handles user input validation
- game_comp(): Compares player's guess with generated number
- game_print(): Manages game flow and interaction.

Sequence Diagram

sequenceDiagram
    participant Player
    participant Game
    Game->>Game: Generate Random Number
    loop Game Round
        Game->>Player: Prompt for Input
        Player->>Game: Enter Guess
        Game->>Game: Validate Input
        Game->>Game: Compare Guess
        Game->>Player: Show Strikes/Balls
        alt Win Condition
            Game->>Player: Congratulate Player
            Game->>Game: End Game
        end
    end
Loading

Poem

🎲 A Rabbit's Number Game Delight 🐰

Three digits dance, a secret tight,
Guess and ponder with all your might,
Strikes and balls, the clues unfold,
A coding challenge, brave and bold!
Hop along the number's trail,
Victory waits beyond the veil! 🏆


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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: 0

🧹 Nitpick comments (3)
src/baseball/main.py (2)

16-25: Encapsulate global references for better modularity.
The game_comp() function references com_number from the outer scope. This can reduce testability and reusability, as the function depends on external state. Consider passing com_number as a parameter to make the function self-contained.

Use enumerate() to avoid manual index increments.
Instead of managing an index variable, utilize Python’s built-in enumerate() for cleaner, more Pythonic code.

-def game_comp(player_number) :
-    strike, ball, index = 0, 0, 0
-    for i in com_number :
-        if int(player_number[index]) == i :
-            strike += 1
-        elif int(player_number[index]) in com_number :
-            ball += 1
-        index += 1
-    return strike, ball
+def game_comp(player_number, com_number) :
+    strike, ball = 0, 0
+    for idx, val in enumerate(com_number):
+        if int(player_number[idx]) == val:
+            strike += 1
+        elif int(player_number[idx]) in com_number:
+            ball += 1
+    return strike, ball
🧰 Tools
🪛 Ruff (0.8.2)

24-24: Use enumerate() for index variable index in for loop

(SIM113)


41-55: Consider refactoring the exit routine.
Using exit() within a loop is effective for a quick script but can be disruptive if this code grows beyond a simple CLI. If you ever integrate this game into a larger system, a return from the main function or raising a custom exit exception might be safer.

docs/README.md (1)

4-4: Use markdown headings instead of emphasis for clearer structure.
The lines with "**" are being parsed as emphasis instead of actual headings. Converting them to headings (e.g., ## 1. …) is more semantically correct and will pass MD036 checks.

-**1.숫자를 랜덤으로 생성한다**
+## 1. 숫자를 랜덤으로 생성한다

-**3.입력받은 수와 생성된 수를 비교한다**
+## 3. 입력받은 수와 생성된 수를 비교한다

-**4.비교 결과를 출력한다**
+## 4. 비교 결과를 출력한다

Also applies to: 13-13, 18-18

🧰 Tools
🪛 Markdownlint (0.37.0)

4-4: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9aa8d4f and ff2d3e7.

📒 Files selected for processing (2)
  • docs/README.md (1 hunks)
  • src/baseball/main.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/baseball/main.py

24-24: Use enumerate() for index variable index in for loop

(SIM113)

🪛 Markdownlint (0.37.0)
docs/README.md

4-4: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


13-13: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


18-18: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🔇 Additional comments (2)
src/baseball/main.py (2)

3-14: Ensure consistent validation messages and flow.
The player_input() function does a good job verifying that the input is a three-digit number with unique digits. The validation messages are also clear.


28-40: Use more descriptive break conditions to clarify intent.
This inner while True: loop breaks only when strike == 3. The logic is correct for a number-guessing scenario. For long-term maintainability, consider adding a clarifying comment or a more explicit condition to indicate that the game ends when the player’s guess is correct.

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: 3

🧹 Nitpick comments (2)
src/baseball/main.py (2)

3-11: Improve input validation robustness and message handling

The input validation logic is good, but there are a few improvements to consider:

  1. Consider internationalizing error messages for wider accessibility
  2. The indentation after line 7 is inconsistent
  3. Add validation for negative numbers and leading zeros
 def player_input() :
-    player_number = input("숫자를 입력해주세요: ")
+    player_number = input("Enter a number: ")
     if len(player_number) != 3 or not player_number.isdigit():
-        raise ValueError("입력은 3자리 숫자여야 합니다.")
+        raise ValueError("Input must be a 3-digit number")
-            
     elif len(set(player_number)) != 3:
-        raise ValueError("입력 값의 각 자리는 서로 달라야 합니다.")
+        raise ValueError("All digits must be unique")
+    elif player_number.startswith('0'):
+        raise ValueError("Number cannot start with zero")
     return player_number

1-56: Consider restructuring the code for better separation of concerns

The current implementation would benefit from a more modular design:

  1. Separate UI logic (input/output) from game logic
  2. Create a GameState class to manage game state
  3. Implement proper internationalization
  4. Add configuration file for constants and messages

Would you like me to provide an example of how to restructure the code with better separation of concerns?

🧰 Tools
🪛 Ruff (0.8.2)

22-22: Use enumerate() for index variable index in for loop

(SIM113)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff2d3e7 and 9dc0846.

📒 Files selected for processing (1)
  • src/baseball/main.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/baseball/main.py

22-22: Use enumerate() for index variable index in for loop

(SIM113)

Comment on lines 14 to 23
def game_comp(com_number, player_number) :
strike, ball, index = 0, 0, 0

for i in com_number :
if int(player_number[index]) == i :
strike += 1
elif int(player_number[index]) in com_number :
ball += 1
index += 1
return strike, ball
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize comparison logic and improve readability

The comparison logic can be improved for better efficiency and readability:

  1. Use enumerate() instead of manual index tracking
  2. Convert player_number to list of integers once before the loop
  3. Use more descriptive variable names
 def game_comp(com_number, player_number) :
     strike, ball = 0, 0
-    index = 0
+    player_digits = [int(d) for d in player_number]
     
-    for i in com_number :
-        if int(player_number[index]) == i :
+    for idx, computer_digit in enumerate(com_number):
+        if player_digits[idx] == computer_digit:
             strike += 1
-        elif int(player_number[index]) in com_number :
+        elif player_digits[idx] in com_number:
             ball += 1
-        index += 1
     return strike, ball
📝 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 game_comp(com_number, player_number) :
strike, ball, index = 0, 0, 0
for i in com_number :
if int(player_number[index]) == i :
strike += 1
elif int(player_number[index]) in com_number :
ball += 1
index += 1
return strike, ball
def game_comp(com_number, player_number) :
strike, ball = 0, 0
player_digits = [int(d) for d in player_number]
for idx, computer_digit in enumerate(com_number):
if player_digits[idx] == computer_digit:
strike += 1
elif player_digits[idx] in com_number:
ball += 1
return strike, ball
🧰 Tools
🪛 Ruff (0.8.2)

22-22: Use enumerate() for index variable index in for loop

(SIM113)

Comment on lines 26 to 39
def game_print(com_number) :
while True:
number = player_input()
strike, ball = game_comp(com_number, number)
if strike==0 and ball==0:
print("낫싱")
continue
elif strike == 3 :
print(strike,"스트라이크")
print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
else:
print(ball,"볼"," ",strike,"스트라이크")
continue
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor function for better separation of concerns and maintainability

The function needs several improvements:

  1. Rename function to better reflect its purpose (e.g., play_game_round)
  2. Extract magic numbers into constants
  3. Use f-strings for better string formatting
  4. Consider internationalizing the output messages
+WINNING_STRIKES = 3
+
-def game_print(com_number) :
+def play_game_round(com_number) :
     while True:
         number = player_input()
         strike, ball = game_comp(com_number, number)
         if strike==0 and ball==0:
-            print("낫싱")
+            print("Nothing!")
             continue
-        elif strike == 3 :
-            print(strike,"스트라이크")
-            print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
+        elif strike == WINNING_STRIKES:
+            print(f"{strike} strikes")
+            print("Congratulations! You've won the game!")
             break
         else:
-            print(ball,"볼"," ",strike,"스트라이크")
+            print(f"{ball} balls, {strike} strikes")
             continue
📝 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 game_print(com_number) :
while True:
number = player_input()
strike, ball = game_comp(com_number, number)
if strike==0 and ball==0:
print("낫싱")
continue
elif strike == 3 :
print(strike,"스트라이크")
print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
else:
print(ball,"볼"," ",strike,"스트라이크")
continue
WINNING_STRIKES = 3
def play_game_round(com_number) :
while True:
number = player_input()
strike, ball = game_comp(com_number, number)
if strike==0 and ball==0:
print("Nothing!")
continue
elif strike == WINNING_STRIKES:
print(f"{strike} strikes")
print("Congratulations! You've won the game!")
break
else:
print(f"{ball} balls, {strike} strikes")
continue

Comment on lines 41 to 55
def main():
while True :
com_number = random.sample(range(1,10),3)
print("숫자 야구 게임을 시작합니다.")
game_print(com_number)


result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
if result == '1':
main()
elif result == '2':
print("게임을 종료합니다.")
exit()
else:
raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical issues in main game loop implementation

The main function has several critical issues that need to be addressed:

  1. Recursive call for game restart can cause stack overflow
  2. Direct exit() call is not a good practice
  3. Missing error handling for random.sample
  4. Internationalization needed for messages
 def main(): 
-    while True :
-        com_number = random.sample(range(1,10),3)
-        print("숫자 야구 게임을 시작합니다.")
-        game_print(com_number)
-    
-        
-        result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
-        if result == '1':
-            main()
-        elif result == '2':
-            print("게임을 종료합니다.")
-            exit()
-        else:
-            raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
+    play_game = True
+    while play_game:
+        try:
+            com_number = random.sample(range(1,10),3)
+            print("Welcome to the Baseball Number Game!")
+            play_game_round(com_number)
+            
+            while True:
+                result = input("Enter 1 to play again, 2 to quit: ")
+                if result == '1':
+                    break
+                elif result == '2':
+                    print("Thanks for playing!")
+                    play_game = False
+                    break
+                else:
+                    print("Invalid input. Please enter 1 or 2.")
+        except Exception as e:
+            print(f"An error occurred: {e}")
+            play_game = False

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member

@swthewhite swthewhite left a comment

Choose a reason for hiding this comment

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

사소한 부분이지만 놓치기 쉬운 부분들이예요.
사용하는 문법에 대해선 하나하나 디테일하게 알아두는 것이 큰 도움이 될 겁니다.

Comment on lines 49 to 50
print("게임을 다시 시작합니다.")
break # 이곳에서 안쪽 while 문을 종료하고 게임을 다시 시작
main()
Copy link
Member

Choose a reason for hiding this comment

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

main()문을 다시 실행해버리면 n번째 main으로 깊게 들어가버릴 수 있어요.
그러면 정상 종료가 힘들어 지겠죠?

여기선 continue를 써주면 매끄럽게 게임을 재진행합니다

elif result == '2':
print("게임을 종료합니다.")
exit() # 프로그램을 종료
exit()
Copy link
Member

Choose a reason for hiding this comment

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

exit()보단 return을 활용해서 해당 함수를 탈출해 상위 함수로 가는 것으로 생각해봅시다
(early return)

print("낫싱")
continue
elif strike == 3 :
print(strike,"스트라이크")
Copy link
Member

Choose a reason for hiding this comment

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

print문에서 ,를 쓰게 되면 무조건 두 변수 사이에 하나의 공백이 들어가게 됩니다.
공백을 의도해서 사용할 때 아니면 string의 +연산이나 fstring을 사용해주세요.

print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
else:
print(ball,"볼"," ",strike,"스트라이크")
Copy link
Member

Choose a reason for hiding this comment

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

(동일 이슈)
print문에서 ,를 쓰게 되면 무조건 두 변수 사이에 하나의 공백이 들어가게 됩니다.
공백을 의도해서 사용할 때 아니면 string의 +연산이나 fstring을 사용해주세요.

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)

14-23: 🛠️ Refactor suggestion

Optimize comparison logic and improve readability

The comparison logic needs optimization:

  1. Use enumerate() instead of manual index tracking (as flagged by static analysis)
  2. Convert player_number to integers once before the loop
  3. Use more descriptive variable names
 def game_comp(com_number, player_number) :
     strike, ball = 0, 0
-    index = 0
+    player_digits = [int(d) for d in player_number]
 
-    for i in com_number :
-        if int(player_number[index]) == i :
+    for idx, computer_digit in enumerate(com_number):
+        if player_digits[idx] == computer_digit:
             strike += 1
-        elif int(player_number[index]) in com_number :
+        elif player_digits[idx] in com_number:
             ball += 1
-        index += 1
     return strike, ball
🧰 Tools
🪛 Ruff (0.8.2)

22-22: Use enumerate() for index variable index in for loop

(SIM113)

🧹 Nitpick comments (1)
src/baseball/main.py (1)

3-11: Enhance input validation and internationalization

The input validation logic is good, but could be improved:

  1. Add validation to prevent zero digits
  2. Consider internationalizing error messages
  3. Remove unnecessary empty line
 def player_input() :
-
     player_number = input("숫자를 입력해주세요: ")
     if len(player_number) != 3 or not player_number.isdigit():
-        raise ValueError("입력은 3자리 숫자여야 합니다.")
+        raise ValueError("Input must be a 3-digit number.")
     
     elif len(set(player_number)) != 3:
-        raise ValueError("입력 값의 각 자리는 서로 달라야 합니다.")
+        raise ValueError("All digits must be unique.")
+    elif '0' in player_number:
+        raise ValueError("Digits must be between 1 and 9.")
     return player_number
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9dc0846 and 745a3ad.

📒 Files selected for processing (1)
  • src/baseball/main.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/baseball/main.py

22-22: Use enumerate() for index variable index in for loop

(SIM113)

🔇 Additional comments (3)
src/baseball/main.py (3)

55-57: LGTM!

The entry point implementation follows Python best practices.


40-54: ⚠️ Potential issue

Fix critical issues in main game loop

Several critical issues need to be addressed:

  1. Recursive call to main() can cause stack overflow (as noted in previous feedback)
  2. Missing error handling for random.sample
  3. Messages need internationalization
 def main(): 
     while True :
-        com_number = random.sample(range(1,10),3)
-        print("숫자 야구 게임을 시작합니다.")
-        game_print(com_number)
-
-
-        result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
-        if result == '1':
-            main()
-        elif result == '2':
-            print("게임을 종료합니다.")
-            return
-        else:
-            raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
+        try:
+            com_number = random.sample(range(1,10),3)
+            print("Welcome to the Baseball Number Game!")
+            game_print(com_number)
+            
+            while True:
+                result = input("Enter 1 to continue, 2 to quit: ")
+                if result == '1':
+                    break  # Continue the outer loop
+                elif result == '2':
+                    print("Thanks for playing!")
+                    return
+                else:
+                    print("Invalid input. Please enter 1 or 2.")
+        except Exception as e:
+            print(f"An error occurred: {e}")
+            return

Likely invalid or redundant comment.


25-38: 🛠️ Refactor suggestion

Improve game flow implementation and string formatting

Several improvements needed:

  1. Replace comma-separated prints with f-strings (as noted in previous feedback)
  2. Extract magic number '3' into a constant
  3. Consider internationalizing the messages
  4. Remove unnecessary continue statements
+WINNING_STRIKES = 3
+
 def game_print(com_number) :
     while True:
         number = player_input()
         strike, ball = game_comp(com_number, number)
         if strike==0 and ball==0:
-            print("낫싱")
+            print("Nothing!")
-            continue
-        elif strike == 3 :
-            print(str(strike)+"스트라이크")
-            print("게임 종료")
+        elif strike == WINNING_STRIKES:
+            print(f"{strike} strikes")
+            print("Game Over!")
             break
         else:
-            print(str(ball)+"볼", str(strike)+"스트라이크")
-            continue
+            print(f"{ball} balls, {strike} strikes")

Likely invalid or redundant comment.

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

♻️ Duplicate comments (2)
src/baseball/main.py (2)

14-23: 🛠️ Refactor suggestion

Optimize comparison logic and improve readability

The comparison logic can be improved for better efficiency and readability.

🧰 Tools
🪛 Ruff (0.8.2)

22-22: Use enumerate() for index variable index in for loop

(SIM113)


25-39: 🛠️ Refactor suggestion

Extract magic numbers into constants

Define constants for better maintainability and clarity:

+WINNING_STRIKES = 3
+
 def game_print(com_number) :
     while True:
         number = player_input()
         strike, ball = game_comp(com_number, number)
         if strike==0 and ball==0:
             print("낫싱")
             continue
-        elif strike == 3 :
+        elif strike == WINNING_STRIKES:

The string formatting issues with print statements have been previously noted.

🧹 Nitpick comments (1)
src/baseball/main.py (1)

3-11: Add try-except block for more robust input handling

While the validation is thorough, consider adding a try-except block to handle non-numeric input more gracefully. Also, consider extracting the messages for future internationalization.

+INVALID_LENGTH_MSG = "입력은 3자리 숫자여야 합니다."
+INVALID_UNIQUE_MSG = "입력 값의 각 자리는 서로 달라야 합니다."

 def player_input() :
-    player_number = input("숫자를 입력해주세요: ")
-    if len(player_number) != 3 or not player_number.isdigit():
-        raise ValueError("입력은 3자리 숫자여야 합니다.")
-    elif len(set(player_number)) != 3:
-        raise ValueError("입력 값의 각 자리는 서로 달라야 합니다.")
+    try:
+        player_number = input("숫자를 입력해주세요: ")
+        if len(player_number) != 3 or not player_number.isdigit():
+            raise ValueError(INVALID_LENGTH_MSG)
+        elif len(set(player_number)) != 3:
+            raise ValueError(INVALID_UNIQUE_MSG)
+        return player_number
+    except ValueError as e:
+        raise ValueError(str(e))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 745a3ad and 84860b0.

📒 Files selected for processing (1)
  • src/baseball/main.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/baseball/main.py

22-22: Use enumerate() for index variable index in for loop

(SIM113)

Comment on lines 57 to +58
if __name__ == "__main__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
main()
main()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add global error handling

Add try-except block in the main execution to handle unexpected errors gracefully:

 if __name__ == "__main__":
-    main()
+    try:
+        main()
+    except KeyboardInterrupt:
+        print("\n게임이 중단되었습니다.")
+    except Exception as e:
+        print(f"오류가 발생했습니다: {str(e)}")
📝 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
if __name__ == "__main__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
main()
main()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n게임이 중단되었습니다.")
except Exception as e:
print(f"오류가 발생했습니다: {str(e)}")

Comment on lines +40 to +55
def main():
while True :
com_number = random.sample(range(1,10),3)
print("숫자 야구 게임을 시작합니다.")
game_print(com_number)


result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
if result == '1':
main()
return
elif result == '2':
print("게임을 종료합니다.")
return
else:
raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove recursive call to prevent stack overflow

The current implementation uses recursion for game restart, which could lead to stack overflow after multiple restarts. Replace with a loop-based approach:

 def main(): 
     while True:
         com_number = random.sample(range(1,10),3)
         print("숫자 야구 게임을 시작합니다.")
         game_print(com_number)
         
         result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
         if result == '1':
-            main()
-            return
+            continue
         elif result == '2':
             print("게임을 종료합니다.")
             return
         else:
             raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
📝 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 :
com_number = random.sample(range(1,10),3)
print("숫자 야구 게임을 시작합니다.")
game_print(com_number)
result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
if result == '1':
main()
return
elif result == '2':
print("게임을 종료합니다.")
return
else:
raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")
def main():
while True:
com_number = random.sample(range(1,10),3)
print("숫자 야구 게임을 시작합니다.")
game_print(com_number)
result = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
if result == '1':
continue
elif result == '2':
print("게임을 종료합니다.")
return
else:
raise ValueError("잘못된 입력입니다. 1 또는 2를 입력하세요.")

AI-WonYJ added a commit to AI-WonYJ/python-baseball that referenced this pull request Feb 4, 2025
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