Skip to content
80 changes: 75 additions & 5 deletions src/baseball/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,80 @@
def main():
import random

def check_valid_input():
arr_list=list(input("숫자를 입력하세요: "))

if len(arr_list)!=3:
raise ValueError("3 자리 숫자를 입력하세요")
for i in range(3):
if not arr_list[i].isdigit():
raise ValueError("정수를 입력하세요")

if len(arr_list) != len(set(arr_list)):
raise ValueError("중복된 숫자를 입력하였습니다")

return [int(x) for x in arr_list]

def regame():
val = input("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.: ")
if val in ["1","2"]:
return int(val)
else:
raise ValueError("1혹은 2를 입력해주세요.")

def make_num():
return random.sample(range(1,10),3)

def input_num():
return check_valid_input()

def check(com, arr):
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
숫자 야구 게임의 결과를 계산하는 함수
- 같은 위치에 같은 숫자가 있으면 스트라이크
- 다른 위치에 같은 숫자가 있으면 볼
"""
# 프로그램의 메인 로직을 여기에 구현
strikes=0
balls=0

for i in range(3):
if arr[i] == com[i]:
strikes += 1
else:
if arr[i] in com:
balls += 1

return strikes, balls

def game():
com=make_num()

while(1):
arr=input_num()
strikes, balls = check(com,arr)

if strikes==0 and balls==0:
print("낫싱")
elif strikes==3:
print("3스트라이크")
print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
else:
print(f"{balls}볼 {strikes}스트라이크")

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

게임 함수 스타일 및 로직 개선

game() 함수에 여러 스타일 및 로직 문제가 있습니다:

  1. PEP8 스타일 가이드를 준수하지 않습니다:

    • 연산자 주변에 공백이 누락됨 (com=make_num()com = make_num())
    • 빈 줄에 공백이 포함됨 (45줄)
    • while 키워드 뒤에 공백이 필요함 (while(1)while (1))
    • 매개변수 사이의 쉼표 뒤에 공백이 누락됨 (com,arrcom, arr)
    • 비교 연산자 주변에 공백이 누락됨 (strikes==0strikes == 0)
    • 함수 사이에 빈 줄 2개가 필요함
  2. 로직 개선 사항:

    • 시도 횟수 제한이나 정보 표시가 없습니다.
    • 사용자가 승리한 후 정답(컴퓨터의 숫자)을 보여주는 것이 좋습니다.
-def game():
-    com=make_num()
-    
-    while(1):
-        arr=input_num()
-        strikes, balls = check(com,arr)
+
+
+def game():
+    com = make_num()
+    attempts = 0
+    
+    while True:
+        attempts += 1
+        print(f"시도 #{attempts}")
+        arr = input_num()
+        strikes, balls = check(com, arr)

-        if strikes==0 and balls==0:
+        if strikes == 0 and balls == 0:
             print("낫싱")
-        elif strikes==3:
+        elif strikes == 3:
             print("3스트라이크")
-            print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
+            print(f"3개의 숫자를 모두 맞히셨습니다! (시도 횟수: {attempts})")
+            print(f"정답은 {com} 이었습니다.")
             break
         else:
             print(f"{balls}볼 {strikes}스트라이크")
-        
📝 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():
com=make_num()
while(1):
arr=input_num()
strikes, balls = check(com,arr)
if strikes==0 and balls==0:
print("낫싱")
elif strikes==3:
print("3스트라이크")
print("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
else:
print(f"{balls}{strikes}스트라이크")
def game():
com = make_num()
attempts = 0
while True:
attempts += 1
print(f"시도 #{attempts}")
arr = input_num()
strikes, balls = check(com, arr)
if strikes == 0 and balls == 0:
print("낫싱")
elif strikes == 3:
print("3스트라이크")
print(f"3개의 숫자를 모두 맞히셨습니다! (시도 횟수: {attempts})")
print(f"정답은 {com} 이었습니다.")
break
else:
print(f"{balls}{strikes}스트라이크")
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 43-43: E302 expected 2 blank lines, found 1


[error] 44-44: E225 missing whitespace around operator


[error] 45-45: W293 blank line contains whitespace


[error] 46-46: E275 missing whitespace after keyword


[error] 47-47: E225 missing whitespace around operator


[error] 48-48: E231 missing whitespace after ','


[error] 50-50: E225 missing whitespace around operator


[error] 50-50: E225 missing whitespace around operator


[error] 52-52: E225 missing whitespace around operator


[error] 58-58: W293 blank line contains whitespace

def main():

print("숫자 야구 게임을 시작합니다.")

while(1):
try:
game()
if regame()==1:
continue
elif regame()==2:
break
except ValueError as e:
print(e)
break

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