Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 46 additions & 7 deletions src/baseball/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,49 @@
def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
import random

def randnumber():
return random.sample(range(1, 10), 3)
while True:
arr = randnumber()

while True:
try:
num = int(input()) # 메시지 없이 입력받음
if num < 100 or num > 999: # 3자리 숫자가 아닐 경우
raise ValueError("3자리 숫자를 입력해야 합니다.")
except ValueError:
raise ValueError(("잘못된 입력입니다"))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

예외 처리 로직 개선

except 블록 내에서 동일한 예외를 다시 발생시키면 프로그램이 종료될 수 있습니다. 사용자에게 오류 메시지를 출력하고 입력을 다시 받도록 수정하는 것이 좋습니다.

다음과 같이 수정해보세요:

 except ValueError:
-    raise ValueError(("잘못된 입력입니다"))
+    print("잘못된 입력입니다. 다시 입력해 주세요.")
+    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
raise ValueError(("잘못된 입력입니다"))
except ValueError:
- raise ValueError(("잘못된 입력입니다"))
+ print("잘못된 입력입니다. 다시 입력해 주세요.")
+ continue
🧰 Tools
🪛 Ruff (0.8.2)

15-15: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)



num_arr = [(num // 100), ((num // 10) % 10), (num % 10)]
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

입력 숫자의 중복 검사 추가

숫자야구 게임에서는 서로 다른 세 자리 숫자를 사용합니다. 현재 입력된 숫자에서 중복된 자릿수에 대한 검사가 없으므로, 중복 여부를 확인하는 로직을 추가하는 것이 필요합니다.

다음과 같이 중복 검사를 추가해보세요:

 num_arr = [(num // 100), ((num // 10) % 10), (num % 10)]  
+if len(set(num_arr)) != 3:
+    print("각 자릿수는 서로 다른 숫자여야 합니다. 다시 입력해 주세요.")
+    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
num_arr = [(num // 100), ((num // 10) % 10), (num % 10)]
num_arr = [(num // 100), ((num // 10) % 10), (num % 10)]
if len(set(num_arr)) != 3:
print("각 자릿수는 서로 다른 숫자여야 합니다. 다시 입력해 주세요.")
continue


strike_Cnt = 0
ball_Cnt = 0

for x in range(3):
for y in range(3):
if arr[x] == num_arr[y]:
if x == y:
strike_Cnt += 1
else:
ball_Cnt += 1

if strike_Cnt == 3:
print("3스트라이크")
print("게임 종료")
break # 정답을 맞추면 게임 종료
elif strike_Cnt == 0 and ball_Cnt == 0:
print("낫싱")
elif strike_Cnt == 1 and ball_Cnt == 1:
print("1볼 1스트라이크")
elif ball_Cnt == 3:
print("3볼")

Check warning on line 40 in src/baseball/main.py

View check run for this annotation

Codecov / codecov/patch

src/baseball/main.py#L40

Added line #L40 was not covered by tests
else:
continue # 지정된 출력 패턴이 아닌 경우 무시하고 다시 입력받음

Check warning on line 42 in src/baseball/main.py

View check run for this annotation

Codecov / codecov/patch

src/baseball/main.py#L42

Added line #L42 was not covered by tests
Comment on lines +31 to +42
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

게임 결과 출력 로직 개선

현재 코드는 특정한 스트라이크와 볼의 조합에 대해서만 결과를 출력하고 있습니다. 모든 경우에 대해 적절한 결과를 사용자에게 제공하기 위해 조건문을 일반화하는 것이 좋습니다.

다음과 같이 수정하여 모든 경우에 대응할 수 있습니다:

     if strike_cnt == 3:
         print("3스트라이크")
         print("게임 종료")
         break  # 정답을 맞추면 게임 종료
     elif strike_cnt == 0 and ball_cnt == 0:
         print("낫싱")
     else:
-        if strike_Cnt == 1 and ball_Cnt == 1:
-            print("1볼 1스트라이크")
-        elif ball_Cnt == 3:
-            print("3볼")
-        else:
-            continue  # 지정된 출력 패턴이 아닌 경우 무시하고 다시 입력받음
+        result = ""
+        if ball_cnt > 0:
+            result += f"{ball_cnt}볼 "
+        if strike_cnt > 0:
+            result += f"{strike_cnt}스트라이크"
+        print(result.strip())

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


menu = input() # 입력 메시지 없이 입력받음
if menu != '1': # 1이 아니면 게임 종료
break

if __name__ == "__main__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
main()
main()

Check warning on line 49 in src/baseball/main.py

View check run for this annotation

Codecov / codecov/patch

src/baseball/main.py#L49

Added line #L49 was not covered by tests
Loading