Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[자동차 경주] 김성규 과제 제출합니다. #4

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
29 changes: 29 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 자동차 경주 게임

## 기능 목록

1. **자동차 이름 입력**
- 사용자가가 쉼표(`,`)로 구분된 자동차 이름을 입력
- 각 자동차 이름은 1~5자의 문자
- 잘못된 입력일 경우 `ValueError`를 발생시키고 프로그램을 종료료

2. **이동 횟수 입력**
- 사용자가 몇 번의 이동을 할 것인지 숫자로 입력
- 1 이상의 정수를 입력해야 하며, 잘못된 입력 시 `ValueError` 발생

3. **자동차 이동 로직**
- 각 자동차는 매 턴마다 0~9 사이의 무작위 값을 얻음
- 값이 4 이상이면 자동차는 한 칸(`-`) 전진
- 값이 3 이하이면 그대로 멈춤

4. **경기 진행 및 결과 출력**
- 입력받은 횟수만큼 경기를 진행
- 매 턴마다 각 자동차의 진행 상태를 출력

5. **우승자 선정**
- 가장 멀리 간 자동차가 우승자
- 우승자가 여러 명일 경우 쉼표(`,`)로 구분하여 출력

6. **예외 처리**
- 잘못된 자동차 이름(1~5자 초과 또는 공백) 입력 시 `ValueError` 발생
- 이동 횟수를 1 이상의 정수로 입력하지 않으면 `ValueError` 발생
57 changes: 49 additions & 8 deletions src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,53 @@
def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
print("프로그램이 시작되었습니다.")
import random

def get_car_names():
names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)\n").split(",")
names = [name.strip() for name in names]

if not names or any(len(name) > 5 or not name for name in names):
raise ValueError("자동차 이름은 1~5자의 문자여야 합니다.")

return names

def get_attempt_count():
try:
count = int(input("시도할 횟수는 몇 회인가요?\n"))
if count <= 0:
raise ValueError

Check warning on line 16 in src/racingcar/main.py

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L16

Added line #L16 was not covered by tests
return count
except ValueError:
raise ValueError("올바른 횟수를 입력하세요. (양의 정수)")

Check warning on line 19 in src/racingcar/main.py

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L18-L19

Added lines #L18 - L19 were not covered by tests
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

예외 처리 방식 개선이 필요합니다.

예외의 원인을 더 명확하게 추적할 수 있도록 raise from 구문을 사용하고, 에러 케이스에 대한 테스트를 추가해주세요.

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

     try:
         count = int(input("시도할 횟수는 몇 회인가요?\n"))
         if count <= 0:
-            raise ValueError
+            raise ValueError("시도 횟수는 양의 정수여야 합니다.")
         return count
-    except ValueError:
-        raise ValueError("올바른 횟수를 입력하세요. (양의 정수)")
+    except ValueError as e:
+        raise ValueError("올바른 횟수를 입력하세요. (양의 정수)") from 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
def get_attempt_count():
try:
count = int(input("시도할 횟수는 몇 회인가요?\n"))
if count <= 0:
raise ValueError
return count
except ValueError:
raise ValueError("올바른 횟수를 입력하세요. (양의 정수)")
def get_attempt_count():
try:
count = int(input("시도할 횟수는 몇 회인가요?\n"))
if count <= 0:
raise ValueError("시도 횟수는 양의 정수여야 합니다.")
return count
except ValueError as e:
raise ValueError("올바른 횟수를 입력하세요. (양의 정수)") from e
🧰 Tools
🪛 Ruff (0.8.2)

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

(B904)

🪛 GitHub Check: codecov/patch

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


[warning] 25-26: src/racingcar/main.py#L25-L26
Added lines #L25 - L26 were not covered by tests


def move_car():
return "-" if random.randint(0, 9) >= 4 else ""
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-else 문을 사용해야 합니다.

 def move_car():
-    return "-" if random.randint(0, 9) >= 4 else ""
+    if random.randint(0, 9) >= 4:
+        return "-"
+    return ""
📝 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 move_car():
return "-" if random.randint(0, 9) >= 4 else ""
def move_car():
if random.randint(0, 9) >= 4:
return "-"
return ""
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[warning] 21-21: E302 expected 2 blank lines, found 1


def run_race(cars, attempts):
results = {car: "" for car in cars}

print("\n실행 결과")
for _ in range(attempts):
for car in cars:
results[car] += move_car()
for car, progress in results.items():
print(f"{car} : {progress}")
print()
return results

def get_winners(results):
max_distance = max(len(progress) for progress in results.values())
winners = [car for car, progress in results.items() if len(progress) == max_distance]
return winners
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

PEP8 라인 길이 제한을 준수해주세요.

38번 라인이 PEP8의 최대 길이 제한(79자)을 초과합니다.

 def get_winners(results):
     max_distance = max(len(progress) for progress in results.values())
-    winners = [car for car, progress in results.items() if len(progress) == max_distance]
+    winners = [
+        car for car, progress in results.items()
+        if len(progress) == max_distance
+    ]
     return winners
📝 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 get_winners(results):
max_distance = max(len(progress) for progress in results.values())
winners = [car for car, progress in results.items() if len(progress) == max_distance]
return winners
def get_winners(results):
max_distance = max(len(progress) for progress in results.values())
winners = [
car for car, progress in results.items()
if len(progress) == max_distance
]
return winners
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[warning] 36-36: E302 expected 2 blank lines, found 1


[error] 38-38: E501 line too long (89 > 79 characters)


def main():
try:
cars = get_car_names()
attempts = get_attempt_count()
results = run_race(cars, attempts)
winners = get_winners(results)
print(f"최종 우승자 : {', '.join(winners)}")
except ValueError as e:
print(f"입력 오류: {e}")
raise
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

후행 공백을 제거해주세요.

55번 줄의 후행 공백을 제거해야 합니다.

-        raise  
+        raise
📝 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():
try:
cars = get_car_names()
attempts = get_attempt_count()
results = run_race(cars, attempts)
winners = get_winners(results)
print(f"최종 우승자 : {', '.join(winners)}")
except ValueError as e:
print(f"입력 오류: {e}")
raise
def main():
try:
cars = get_car_names()
attempts = get_attempt_count()
results = run_race(cars, attempts)
winners = get_winners(results)
print(f"최종 우승자 : {', '.join(winners)}")
except ValueError as e:
print(f"입력 오류: {e}")
raise
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

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


[warning] 55-55: W291 trailing whitespace

🪛 GitHub Actions: Check Indentation Depth

[warning] 55-55: Trailing whitespace (trailing-whitespace)


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