diff --git a/.gitignore b/.gitignore index 76611b072..c194c7f59 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,9 @@ bin/ .idea *.iws *.iml -*.ipr \ No newline at end of file +*.ipr + +### personal gitignore setting +/gradle +gradle* +settings.gradle \ No newline at end of file diff --git a/build.gradle b/build.gradle index 45d61697f..edc026cd8 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,7 @@ dependencies { java { toolchain { - languageVersion = JavaLanguageVersion.of(8) + languageVersion = JavaLanguageVersion.of(11) } } diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..27496c201 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,61 @@ +# :pushpin: 자동차 경주 게임 기능 목록 + +## 구현 기능 목록 +
+입력 +
+ +- [x] 경주할 자동차 이름을 입력 받기 + +**예외처리** +> - [x] 공백을 입력했을 경우.(자동차가 한대도 없는 경우) +> - [x] ,로 분리 했을때 자동차 길이가 공백이거나 비어 있을 경우 +> - [x] 자동차 이름은 5글자 이하 +> - [x] 같은 이름의 자동차 있을시 중복 체크 +- [x] 시도할 회수를 입력 받기 +> - [x] 숫자아닌 문자 예외 체크 +> - [x] 0 이하 숫자 입력시 예외 체크 +> - [x] integer 최대 수 보다 큰 수 입력시 예외 생성 +> - **예외처리** +- [x]사용자가 잘못된 값을 입력할 경우 [ERROR]로 시작하는 에러 메시지를 출력 후 그 부분부터 다시 입력 받기 + +
+
+ +
+출력 +
+ +- [x] 각 차수별 진행 결과 출력 +> - [x] 아래 형식 준수하기 (전진하는 자동차를 출력할 때 자동차 이름을 같이 출력하기) +``` +pobi : -- +woni : ---- +jun : --- +``` +- [x] 단독 우승자 안내 문구 출력하기 +- [x] 공동 우승자 안내 문구 출력하기 +> - [x] 우승자가 여러명일 경우 , 통해서 구분하기 +- [x] 예외 상황 시 [ERROR]로 시작하는 에러 문구를 출력 + +
+
+ +
+체크리스트 및 구현 로직 +
+ +- [x] Car 객체를 활용해 구현 한다. +> - [x] 기본생성자 추가 불가, private 접근제어자 변경 불가, setPosition 메서드 사용 불가 + +- [x] 전진하는 로직 구현 +> - [x] 게임 실행횟수만큼 실행한다 +> - [x] 1. 일단 list돌면서 Car마다 playTheGame메서드 실행 +> - [x] 2. list 돌면서 `car이름 : getPosition()\n` 마다 string으로 변환 +> - [x] list를 돌면서 `car이름 : `을 생성하고 게임을 실행해서 +> - [x] 전진하는 조건은 0에서 9 사이에서 무작위 값을 구한 후 무작위 값이 4 이상일 경우이다. + +- [x] position의 길이가 최대인 우승자 계산 + +
+
\ No newline at end of file diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index 16e868eed..000000000 --- a/gradle.properties +++ /dev/null @@ -1,2 +0,0 @@ -org.gradle.jvmargs=-Dfile.encoding=UTF-8 -org.gradle.console=plain diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 87b738cbd..000000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 28ff446a2..000000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index af6708ff2..000000000 --- a/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 6d57edc70..000000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/src/main/java/racingcar/Application.java b/src/main/java/racingcar/Application.java index b9ed0456a..dd6bf2456 100644 --- a/src/main/java/racingcar/Application.java +++ b/src/main/java/racingcar/Application.java @@ -1,7 +1,10 @@ package racingcar; +import racingcar.controller.RacingGameController; + public class Application { public static void main(String[] args) { - // TODO 구현 진행 + RacingGameController controller = new RacingGameController(); + controller.run(); } } diff --git a/src/main/java/racingcar/Car.java b/src/main/java/racingcar/Car.java index ab3df9492..937e672c1 100644 --- a/src/main/java/racingcar/Car.java +++ b/src/main/java/racingcar/Car.java @@ -1,5 +1,7 @@ package racingcar; +import camp.nextstep.edu.missionutils.Randoms; + public class Car { private final String name; private int position = 0; @@ -9,4 +11,17 @@ public Car(String name) { } // 추가 기능 구현 + public void playGame(){ + if(Randoms.pickNumberInRange(0, 9) >= 4){ + position += 1; + } + } + + public String getName() { + return name; + } + + public int getPosition() { + return position; + } } diff --git a/src/main/java/racingcar/controller/RacingGameController.java b/src/main/java/racingcar/controller/RacingGameController.java new file mode 100644 index 000000000..00515bf24 --- /dev/null +++ b/src/main/java/racingcar/controller/RacingGameController.java @@ -0,0 +1,71 @@ +package racingcar.controller; + +import racingcar.Car; +import racingcar.domain.CarGenerator; +import racingcar.domain.ResultStringGenerator; +import racingcar.view.InputView; +import racingcar.view.OutputView; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingGameController { + + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + + String carNames = inputView.readCarName(); + CarGenerator carGenerator = new CarGenerator(carNames); + List cars = carGenerator.generateNamesToCars(); + + int gameCount = inputView.readGameCount(); + outputView.printResultMessage(); + // 게임 횟수만큼 게임 실행 + playTheGame(cars, gameCount); + // 우승 car 구하기 + String winner = getWinners(cars); + // 우승자 출력 + outputView.printWinner(winner); + } + + private String getWinners(List cars) { + List winners = getWinnerCars(cars); + return winners.stream().map(Car::getName).collect(Collectors.joining(", ")); + } + + private void playTheGame(List cars, int gameCount) { + for (int i = 0; i < gameCount; i++) { + //1. 일단 list돌면서 Car마다 playTheGame메서드 실행 + cars.forEach(Car::playGame); + //2. list 돌면서 `car이름 : getPosition()\n` 마다 string으로 변환 + String executionResult = getExecutionResult(cars); + outputView.printResult(executionResult); + } + } + + private String getExecutionResult(List cars) { + return cars.stream() + .map(ResultStringGenerator.generateExecutionResult()) + .collect(Collectors.joining()); + } + + private List getWinnerCars(List cars) { + Integer maxPosition = getMaxPosition(cars); + return calculateWinner(cars, maxPosition); + } + + private Integer getMaxPosition(List cars) { + return cars.stream() + .map(Car::getPosition) + .reduce(Integer::max) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] 최댓값을 구할 수 없습니다")); + } + + private List calculateWinner(List cars, int maxPosition) { + return cars.stream() + .filter(i -> i.getPosition() == maxPosition) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/racingcar/domain/CarGenerator.java b/src/main/java/racingcar/domain/CarGenerator.java new file mode 100644 index 000000000..ac0d91024 --- /dev/null +++ b/src/main/java/racingcar/domain/CarGenerator.java @@ -0,0 +1,22 @@ +package racingcar.domain; + +import racingcar.Car; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class CarGenerator { + + private final String carNames; + + public CarGenerator(String carNames) { + this.carNames = carNames; + } + + public List generateNamesToCars() { + return Arrays.stream(carNames.split(",")) + .map(carName -> new Car(carName.trim())) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/racingcar/domain/ResultStringGenerator.java b/src/main/java/racingcar/domain/ResultStringGenerator.java new file mode 100644 index 000000000..ec09e9d58 --- /dev/null +++ b/src/main/java/racingcar/domain/ResultStringGenerator.java @@ -0,0 +1,13 @@ +package racingcar.domain; + +import racingcar.Car; +import racingcar.util.Util; + +import java.util.function.Function; + +public class ResultStringGenerator { + + public static Function generateExecutionResult() { + return car -> car.getName() + " : " + Util.convertPositionToBar(car.getPosition()) + "\n"; + } +} diff --git a/src/main/java/racingcar/util/Util.java b/src/main/java/racingcar/util/Util.java new file mode 100644 index 000000000..75a00046f --- /dev/null +++ b/src/main/java/racingcar/util/Util.java @@ -0,0 +1,23 @@ +package racingcar.util; + +public class Util { + + public static final String BAR = "-"; + + public static int convertStringToInt(String input) { + try { + long longValue = Long.parseLong(input); + Validator.validateNumberValue(longValue); + return (int) longValue; + } catch (NumberFormatException e) { + throw new IllegalArgumentException("[ERROR] 숫자를 입력하셔야 합니다"); + } + } + + public static String convertPositionToBar(int position) { + return BAR.repeat(position); + } + +} + + diff --git a/src/main/java/racingcar/util/Validator.java b/src/main/java/racingcar/util/Validator.java new file mode 100644 index 000000000..a2219571d --- /dev/null +++ b/src/main/java/racingcar/util/Validator.java @@ -0,0 +1,78 @@ +package racingcar.util; + +import java.util.Arrays; + +public class Validator { + + public static final String DELIMITER = ","; + + public static void validateCarName(String carNames) { + // 공백을 입력했을 경우 + validateBlank(carNames); + // 자동차 길이는 5 이하 + validateCarNameLength(carNames); + // ,로 분리했을 때, 자동차 길이가 공백이거나 비어 있을 경우 + validateEmptyCarName(carNames); + // 중복된 값이 있을 경우 예외발생 + validateDuplicateCarName(carNames); +// Arrays.stream(carNames.split(DELIMITER)).filter(car -> car.length() < ) + } + + private static void validateDuplicateCarName(String carNames) { + if (getCarCount(carNames) != getDistinctCarCount(carNames)) { + throw new IllegalArgumentException("[ERROR] 중복된 값을 입력하셨습니다. 다시 입력해 주세요"); + } + } + + private static long getDistinctCarCount(String carNames) { + return Arrays.stream(carNames.split(DELIMITER)) + .map(String::trim) + .distinct() + .count(); + } + + private static long getCarCount(String carNames) { + return Arrays.stream(carNames.split(DELIMITER)) + .map(String::trim) + .count(); + } + + private static void validateEmptyCarName(String carNames) { + if (isBlankCarNameExist(carNames) ){ + throw new IllegalArgumentException("[ERROR] 길이가 5이하의 자동차 이름을 다시 입력해 주세요"); + } + } + + private static boolean isBlankCarNameExist(String carNames) { + return Arrays.stream(carNames.split(DELIMITER)) + .anyMatch(car -> car.trim().length() == 0); + } + + private static void validateCarNameLength(String carNames) { + if (isCarNameMoreThanFiveLetters(carNames)){ + throw new IllegalArgumentException("[ERROR] 자동차 이름은 5이하여야 합니다"); + } + } + + private static boolean isCarNameMoreThanFiveLetters(String carNames) { + long carNameOverFive = Arrays.stream(carNames.split(DELIMITER)).filter(car -> car.length() > 5).count(); + return carNameOverFive > 0; + } + + private static void validateBlank(String carNames) { + if (carNames.split(",").length == 0) { + throw new IllegalArgumentException("[ERROR] 자동차 이름을 다시 입력해 주세요"); + } + } + public static void validateNumberValue(long longValue) { + if (longValue >= Integer.MAX_VALUE) { + throw new IllegalArgumentException("[ERROR] INT 범위 안의 숫자를 입력해 주세요"); + } + } + + public static void validateGameCount(int gameCount) { + if (gameCount <= 0) { + throw new IllegalArgumentException("[ERROR] 1 이상의 값을 입력해 주세요"); + } + } +} diff --git a/src/main/java/racingcar/view/InputView.java b/src/main/java/racingcar/view/InputView.java new file mode 100644 index 000000000..32a23d168 --- /dev/null +++ b/src/main/java/racingcar/view/InputView.java @@ -0,0 +1,32 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; +import racingcar.util.Util; +import racingcar.util.Validator; + +public class InputView { + + public String readCarName() { + try { + System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"); + String carNames = Console.readLine(); + Validator.validateCarName(carNames); + return carNames; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + return readCarName(); + } + + public int readGameCount() { + try { + System.out.println("시도할 회수는 몇회인가요?"); + int gameCount = Util.convertStringToInt(Console.readLine()); + Validator.validateGameCount(gameCount); + return gameCount; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + return readGameCount(); + } +} diff --git a/src/main/java/racingcar/view/OutputView.java b/src/main/java/racingcar/view/OutputView.java new file mode 100644 index 000000000..e74014016 --- /dev/null +++ b/src/main/java/racingcar/view/OutputView.java @@ -0,0 +1,20 @@ +package racingcar.view; + +public class OutputView { + + public void printResult(String result) { + System.out.println(result); + } + + public void printResultMessage() { + System.out.println("실행 결과"); + } + + public void printWinner(String winner) { + System.out.println("최종 우승자 : " + winner); + } + + public void printErrorMessage(IllegalArgumentException exception) { + System.out.println(exception.getMessage()); + } +}