Skip to content
Open
Changes from 12 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
85 changes: 83 additions & 2 deletions src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,93 @@
import random


THRESHOLD = 4 # 성공 기준 값
MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값


def is_number(data):
"""
data가 숫자인지 확인하는 함수.
숫자가 아니면 ValueError를 발생시킴.
"""
try:
int(data) # data가 int 형식인지 확인
except ValueError as e:
raise ValueError("숫자만 입력해주세요.") from e # 숫자가 아닌 값 입력시 예외 처리


def validate_name(data):
for i in range(len(data)):
if len(data[i]) > 5:
raise ValueError("이름은 5자 이하만 가능합니다.")
elif len(data[i]) == 0:
raise ValueError("이름은 빈칸일 수 없습니다.")
elif data.count(data[i]) != 1:
raise ValueError("중복되는 이름이 있습니다.")
data[i] = [data[i], 0]


def validate_input(data):
if isinstance(data, str):
is_number(data)
if int(data) <= 0:
raise ValueError("시도할 횟수는 양의 정수이어야 합니다.")
elif isinstance(data, list):
validate_name(data)
return data


def try_input():
print("시도할 횟수는 몇 회인가요?")
try_number = input()
validate_input(try_number)
return int(try_number)


def play_1set_of_game(data):
for i in range(len(data)):
value = random.randint(0, MAX_RANDOM_VALUE)
if value >= THRESHOLD:
data[i][1] += 1
return data


def check_winner(data):
win_list, winner_count = list(), 0
for i in range(len(data)):
if data[i][1] > winner_count:
win_list, winner_count = [data[i][0]], data[i][1]
elif data[i][1] == winner_count:
win_list.append(data[i][0])
return win_list


def print_game_play_result(data, try_number):
for i in range(try_number):
data = play_1set_of_game(data)
for i in range(len(data)):
print("{0} : {1}".format(data[i][0], "-" * data[i][1]))
print()
return data


def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
print("프로그램이 시작되었습니다.")
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
name_list = validate_input(list(map(str, input().replace(" ","").split(","))))
try_number = try_input()
Comment on lines +80 to +87

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

입력 처리와 PEP8 스타일을 개선해주세요.

  1. 입력 문자열 처리를 개선하고
  2. PEP8 스타일 가이드를 준수하도록 수정이 필요합니다:
-    print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
-    name_list = validate_input(list(map(str, input().replace(" ","").split(","))))
+    print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
+    raw_input = input().strip()
+    name_list = validate_input([name.strip() for name in raw_input.split(",")])
📝 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
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
name_list = validate_input(list(map(str, input().replace(" ","").split(","))))
try_number = try_input()
print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
raw_input = input().strip()
name_list = validate_input([name.strip() for name in raw_input.split(",")])
try_number = try_input()
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

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


[error] 81-81: E501 line too long (82 > 79 characters)

print()
print("실행 결과")

win_list = check_winner(print_game_play_result(name_list, try_number))

print("최종 우승자 : {0}".format(', '.join(win_list)))
Comment on lines +80 to +93

Copy link
Copy Markdown

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. 입력값 처리를 더 견고하게 만들 수 있습니다.
-    print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
-    get_name = input().replace(" ", "").split(",")
-    name_list = validate_input(list(map(str, get_name)))
-    try_number = try_input()
-    print()
-    print("실행 결과")
-
-    win_list = check_winner(print_game_play_result(name_list, try_number))
-
-    print("최종 우승자 : {0}".format(', '.join(win_list)))
+    try:
+        print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
+        raw_input = input().strip()
+        name_list = validate_input([name.strip() for name in raw_input.split(",")])
+        
+        try_number = try_input()
+        print("\n실행 결과")
+        
+        final_state = print_game_play_result(name_list, try_number)
+        win_list = check_winner(final_state)
+        
+        print(f"최종 우승자 : {', '.join(win_list)}")
+        return 0
+    except ValueError as e:
+        print(f"오류: {e}")
+        return 1
📝 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
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
get_name = input().replace(" ", "").split(",")
name_list = validate_input(list(map(str, get_name)))
try_number = try_input()
print()
print("실행 결과")
win_list = check_winner(print_game_play_result(name_list, try_number))
print("최종 우승자 : {0}".format(', '.join(win_list)))
try:
print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
raw_input = input().strip()
name_list = validate_input([name.strip() for name in raw_input.split(",")])
try_number = try_input()
print("\n실행 결과")
final_state = print_game_play_result(name_list, try_number)
win_list = check_winner(final_state)
print(f"최종 우승자 : {', '.join(win_list)}")
return 0
except ValueError as e:
print(f"오류: {e}")
return 1



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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

파일 끝에 개행을 추가해주세요.

PEP8 스타일 가이드를 준수하기 위해 파일 끝에 빈 줄을 추가해주세요.

 if __name__ == "__main__":
     # 프로그램이 직접 실행될 때만 main() 함수를 호출
-    main()
+    main()
+
📝 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__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
main()
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 93-93: src/racingcar/main.py#L93
Added line #L93 was not covered by tests

🪛 GitHub Actions: Check Indentation Depth

[warning] 93-93: Final newline missing (missing-final-newline)

🪛 GitHub Actions: Check PEP8 Style

[warning] 93-93: W292 no newline at end of file