diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..581bf51 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..41d7826 --- /dev/null +++ b/build.gradle @@ -0,0 +1,23 @@ +plugins { + id 'java' +} + +group = 'sehee' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + // JUnit + testImplementation platform('org.junit:junit-bom:5.9.1') + testImplementation 'org.junit.jupiter:junit-jupiter' + + // assertJ + testImplementation 'org.assertj:assertj-core:3.26.0' +} + +test { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..71696c7 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun May 12 02:16:23 KST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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 Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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" "-Xms64m" + +@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 execute + +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 execute + +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 + +: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 %* + +: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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3a4a665 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'java-baseball' + diff --git a/src/main/java/sehee/GameContainer.java b/src/main/java/sehee/GameContainer.java new file mode 100644 index 0000000..b68a748 --- /dev/null +++ b/src/main/java/sehee/GameContainer.java @@ -0,0 +1,36 @@ +package sehee; + +import java.util.Random; +import sehee.answer.AnswerFactory; +import sehee.exception.ExceptionHandler; +import sehee.game.Game; +import sehee.game.NumberBaseballGame; +import sehee.game.player.GamePlayer; +import sehee.io.in.CliReader; +import sehee.io.in.Reader; +import sehee.io.out.CliPrinter; +import sehee.io.out.Printer; +import sehee.util.numbermaker.NumberMaker; +import sehee.util.numbermaker.RandomNumberMaker; + +public class GameContainer { + + public static void main(String[] args) { + // IO + Reader reader = new CliReader(); + Printer printer = new CliPrinter(); + + // Exception + ExceptionHandler exceptionHandler = new ExceptionHandler(printer); + + // Set Game + NumberMaker numberMaker = new RandomNumberMaker(new Random()); + AnswerFactory answerFactory = new AnswerFactory(numberMaker); + Game game = new NumberBaseballGame(reader, printer, answerFactory, exceptionHandler); + + // Play Game! + GamePlayer gamePlayer = new GamePlayer(reader, printer, game, exceptionHandler); + gamePlayer.on(); + } + +} diff --git a/src/main/java/sehee/answer/Answer.java b/src/main/java/sehee/answer/Answer.java new file mode 100644 index 0000000..cccfa2b --- /dev/null +++ b/src/main/java/sehee/answer/Answer.java @@ -0,0 +1,39 @@ +package sehee.answer; + +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; + +public class Answer { + + private final int[] numbers; + + // package-private + Answer(int[] numbers) { + this.numbers = numbers; + } + + public Hint match(Answer otherAnswer) { + Hint hint = new Hint(); + for (int i = 0; i < ANSWER_LENGTH; i++) { + this.matchInAnswer(i, otherAnswer, hint); + } + + return hint; + } + + private void matchInAnswer(int index, Answer otherAnswer, Hint hint) { + for (int j = 0; j < ANSWER_LENGTH; j++) { + this.matchNumberWithIndex(index, otherAnswer.numbers[j], j, hint); + } + } + + private void matchNumberWithIndex(int index, int otherNumber, int otherIndex, Hint hint) { + if (this.numbers[index] == otherNumber) { + if (index == otherIndex) { + hint.increaseStrikeCount(); + return; + } + + hint.increaseBallCount(); + } + } +} diff --git a/src/main/java/sehee/answer/AnswerFactory.java b/src/main/java/sehee/answer/AnswerFactory.java new file mode 100644 index 0000000..bfb2a2b --- /dev/null +++ b/src/main/java/sehee/answer/AnswerFactory.java @@ -0,0 +1,25 @@ +package sehee.answer; + +import sehee.util.numbermaker.NumberMaker; + +public class AnswerFactory { + + private final NumberMaker numberMaker; + + public AnswerFactory(NumberMaker numberMaker) { + this.numberMaker = numberMaker; + } + + public Answer make() { + int[] numbers = numberMaker.makeAllUnique(); + + return new Answer(numbers); + } + + public Answer make(int[] numbers) { + AnswerNumberValidator.check(numbers); + + return new Answer(numbers); + } + +} diff --git a/src/main/java/sehee/answer/AnswerNumberValidator.java b/src/main/java/sehee/answer/AnswerNumberValidator.java new file mode 100644 index 0000000..6968475 --- /dev/null +++ b/src/main/java/sehee/answer/AnswerNumberValidator.java @@ -0,0 +1,37 @@ +package sehee.answer; + +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; +import static sehee.util.constant.NumberBaseballGameMessage.ANSWER_LENGTH_EXCEPTION_MESSAGE; +import static sehee.util.constant.NumberBaseballGameMessage.DUPLICATED_EXCEPTION_MESSAGE; + +// package-private +final class AnswerNumberValidator { + + static void check(int[] numbers) { + checkLength(numbers); + checkAllUnique(numbers); + } + + private static void checkLength(int[] numbers) { + if (numbers.length != ANSWER_LENGTH) { + throw new IllegalArgumentException(ANSWER_LENGTH_EXCEPTION_MESSAGE); + } + } + + private static void checkAllUnique(int[] numbers) { + boolean[] isExist = new boolean[10]; + isExist[0] = true; + for (int number : numbers) { + checkUnique(number, isExist); + } + } + + private static void checkUnique(int number, boolean[] isExist) { + if (isExist[number]) { + throw new IllegalArgumentException(DUPLICATED_EXCEPTION_MESSAGE); + } + + isExist[number] = true; + } + +} diff --git a/src/main/java/sehee/answer/Hint.java b/src/main/java/sehee/answer/Hint.java new file mode 100644 index 0000000..dd506d5 --- /dev/null +++ b/src/main/java/sehee/answer/Hint.java @@ -0,0 +1,55 @@ +package sehee.answer; + +import static sehee.util.constant.NumberBaseballGameConstant.BALL; +import static sehee.util.constant.NumberBaseballGameConstant.NOTHING; +import static sehee.util.constant.NumberBaseballGameConstant.STRIKE; + +public class Hint { + + private int ballCount; + private int strikeCount; + + // package-private + Hint() { + ballCount = 0; + strikeCount = 0; + } + + @Override + public String toString() { + if (ballCount == 0 && strikeCount == 0) { + return NOTHING; + } + + StringBuilder hintStringBuilder = new StringBuilder(); + + if (ballCount != 0) { + hintStringBuilder.append(ballCount) + .append(BALL); + } + + if (strikeCount != 0) { + if (ballCount != 0) { + hintStringBuilder.append(" "); + } + + hintStringBuilder.append(strikeCount) + .append(STRIKE); + } + + return hintStringBuilder.toString(); + } + + public boolean isThreeStrike() { + return strikeCount == 3; + } + + void increaseBallCount() { + this.ballCount++; + } + + void increaseStrikeCount() { + this.strikeCount++; + } + +} diff --git a/src/main/java/sehee/exception/ExceptionHandler.java b/src/main/java/sehee/exception/ExceptionHandler.java new file mode 100644 index 0000000..2bf0293 --- /dev/null +++ b/src/main/java/sehee/exception/ExceptionHandler.java @@ -0,0 +1,13 @@ +package sehee.exception; + +import sehee.io.out.Printer; + +public record ExceptionHandler( + Printer printer +) { + + public void alert(Exception exception) { + printer.println(exception.getMessage()); + } + +} diff --git a/src/main/java/sehee/game/Game.java b/src/main/java/sehee/game/Game.java new file mode 100644 index 0000000..9cc4da8 --- /dev/null +++ b/src/main/java/sehee/game/Game.java @@ -0,0 +1,9 @@ +package sehee.game; + +import java.io.IOException; + +public interface Game { + + void play() throws IOException; + +} diff --git a/src/main/java/sehee/game/NumberBaseballGame.java b/src/main/java/sehee/game/NumberBaseballGame.java new file mode 100644 index 0000000..7202508 --- /dev/null +++ b/src/main/java/sehee/game/NumberBaseballGame.java @@ -0,0 +1,89 @@ +package sehee.game; + +import static sehee.util.constant.NumberBaseballGameMessage.ALL_STRIKE_MESSAGE; +import static sehee.util.constant.NumberBaseballGameMessage.COMPUTER_CHOOSE_NUMBERS_MESSAGE; +import static sehee.util.constant.NumberBaseballGameMessage.GAME_OVER_MESSAGE; +import static sehee.util.constant.NumberBaseballGameMessage.WRITE_NUMBERS_MESSAGE; + +import java.io.IOException; +import sehee.answer.Answer; +import sehee.answer.AnswerFactory; +import sehee.answer.Hint; +import sehee.exception.ExceptionHandler; +import sehee.io.in.Reader; +import sehee.io.out.Printer; + +public class NumberBaseballGame implements Game { + + private final Reader reader; + private final Printer printer; + private final AnswerFactory answerFactory; + private final ExceptionHandler exceptionHandler; + + public NumberBaseballGame( + Reader reader, + Printer printer, + AnswerFactory answerFactory, + ExceptionHandler exceptionHandler + ) { + this.reader = reader; + this.printer = printer; + this.answerFactory = answerFactory; + this.exceptionHandler = exceptionHandler; + } + + @Override + public void play() throws IOException { + Answer answer = setComputerAnswer(); + boolean playing = true; + while (playing) { + playing = checkPlaying(answer); + } + + gameOver(); + } + + private boolean checkPlaying(Answer answer) throws IOException { + try { + Answer userAnswer = readUserAnswer(); + Hint hint = answer.match(userAnswer); + printer.println(hint); + + return !checkThreeStrike(hint); + } catch (IllegalArgumentException e) { + exceptionHandler.alert(e); + + return true; + } + } + + private boolean checkThreeStrike(Hint hint) { + if (!hint.isThreeStrike()) { + return false; + } + + printer.println(ALL_STRIKE_MESSAGE); + + return true; + + } + + private Answer readUserAnswer() throws IOException { + printer.print(WRITE_NUMBERS_MESSAGE); + int[] userInputs = reader.readNumbers(); + + return answerFactory.make(userInputs); + } + + private Answer setComputerAnswer() { + Answer answer = answerFactory.make(); + printer.println(COMPUTER_CHOOSE_NUMBERS_MESSAGE); + + return answer; + } + + private void gameOver() { + printer.println(GAME_OVER_MESSAGE); + } + +} diff --git a/src/main/java/sehee/game/player/GamePlayer.java b/src/main/java/sehee/game/player/GamePlayer.java new file mode 100644 index 0000000..5843248 --- /dev/null +++ b/src/main/java/sehee/game/player/GamePlayer.java @@ -0,0 +1,67 @@ +package sehee.game.player; + +import static sehee.util.constant.GamePlayerMessage.CHOOSE_START_OR_END_EXCEPTION_MESSAGE; +import static sehee.util.constant.GamePlayerMessage.CHOOSE_START_OR_END_MESSAGE; +import static sehee.util.constant.GamePlayerMessage.OFF_MESSAGE; +import static sehee.util.constant.NumberBaseballGameConstant.END_NUMBER; +import static sehee.util.constant.NumberBaseballGameConstant.START_NUMBER; + +import java.io.IOException; +import sehee.exception.ExceptionHandler; +import sehee.game.Game; +import sehee.io.in.Reader; +import sehee.io.out.Printer; + +public class GamePlayer { + + private final Reader reader; + private final Printer printer; + private final Game game; + private final ExceptionHandler exceptionHandler; + + public GamePlayer(Reader reader, Printer printer, Game game, ExceptionHandler exceptionHandler) { + this.reader = reader; + this.printer = printer; + this.game = game; + this.exceptionHandler = exceptionHandler; + } + + public void on() { + boolean working = true; + while (working) { + working = checkWorkingAndPlayGame(); + } + printer.println(OFF_MESSAGE); + } + + private boolean checkWorkingAndPlayGame() { + try { + if (checkStopGame()) { + return false; + } + + game.play(); + } catch (Exception exception) { + exceptionHandler.alert(exception); + } + + return true; + } + + private boolean checkStopGame() throws IOException { + printer.println(CHOOSE_START_OR_END_MESSAGE); + + int flag = reader.readOneNumber(); + switch (flag) { + case START_NUMBER -> { + return false; + } + case END_NUMBER -> { + return true; + } + } + + throw new IllegalArgumentException(CHOOSE_START_OR_END_EXCEPTION_MESSAGE); + } + +} diff --git a/src/main/java/sehee/io/in/CliReader.java b/src/main/java/sehee/io/in/CliReader.java new file mode 100644 index 0000000..243b4e4 --- /dev/null +++ b/src/main/java/sehee/io/in/CliReader.java @@ -0,0 +1,55 @@ +package sehee.io.in; + +import static sehee.io.in.ReadConstant.ASCII_CODE_DECIMAL_NINE; +import static sehee.io.in.ReadConstant.ASCII_CODE_DECIMAL_ONE; +import static sehee.io.in.ReadConstant.CHAR_ZERO; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CliReader implements Reader { + + private final BufferedReader cliReader; + + public CliReader() { + cliReader = new BufferedReader(new InputStreamReader(System.in)); + } + + @Override + public int readOneNumber() throws IOException { + char[] inputs = getStringInput().toCharArray(); + if (inputs.length > 1) { + throw new IllegalArgumentException("1자리 숫자만 입력해주세요."); + } + + return convertCharToInt(inputs[0]); + } + + @Override + public int[] readNumbers() throws IOException { + char[] inputs = getStringInput().toCharArray(); + int[] numbers = new int[inputs.length]; + for (int i = 0; i < inputs.length; i++) { + numbers[i] = convertCharToInt(inputs[i]); + } + + return numbers; + } + + private String getStringInput() throws IOException { + return cliReader.readLine(); + } + + private int convertCharToInt(char inputs) { + checkIsNumber(inputs); + return inputs - CHAR_ZERO; + } + + private void checkIsNumber(char character) { + if (character < ASCII_CODE_DECIMAL_ONE || ASCII_CODE_DECIMAL_NINE < character) { + throw new NumberFormatException("숫자를 입력해주세요."); + } + } + +} diff --git a/src/main/java/sehee/io/in/ReadConstant.java b/src/main/java/sehee/io/in/ReadConstant.java new file mode 100644 index 0000000..c414a84 --- /dev/null +++ b/src/main/java/sehee/io/in/ReadConstant.java @@ -0,0 +1,10 @@ +package sehee.io.in; + +// package-private +final class ReadConstant { + + static final char CHAR_ZERO = '0'; + static final int ASCII_CODE_DECIMAL_ONE = 49; + static final int ASCII_CODE_DECIMAL_NINE = 57; + +} diff --git a/src/main/java/sehee/io/in/Reader.java b/src/main/java/sehee/io/in/Reader.java new file mode 100644 index 0000000..329f4cd --- /dev/null +++ b/src/main/java/sehee/io/in/Reader.java @@ -0,0 +1,11 @@ +package sehee.io.in; + +import java.io.IOException; + +public interface Reader { + + int readOneNumber() throws IOException; + + int[] readNumbers() throws IOException; + +} diff --git a/src/main/java/sehee/io/out/CliPrinter.java b/src/main/java/sehee/io/out/CliPrinter.java new file mode 100644 index 0000000..07b4365 --- /dev/null +++ b/src/main/java/sehee/io/out/CliPrinter.java @@ -0,0 +1,30 @@ +package sehee.io.out; + +import static sehee.io.out.PrintConstant.LINE_SEPARATOR; + +import java.io.PrintStream; + +public class CliPrinter implements Printer { + + private final PrintStream cliPrinter; + + public CliPrinter() { + cliPrinter = System.out; + } + + @Override + public void print(String message) { + cliPrinter.print(message); + } + + @Override + public void println(String message) { + cliPrinter.print(message + LINE_SEPARATOR); + } + + @Override + public void println(T object) { + println(object.toString()); + } + +} diff --git a/src/main/java/sehee/io/out/PrintConstant.java b/src/main/java/sehee/io/out/PrintConstant.java new file mode 100644 index 0000000..a124a8a --- /dev/null +++ b/src/main/java/sehee/io/out/PrintConstant.java @@ -0,0 +1,8 @@ +package sehee.io.out; + +// package-private +final class PrintConstant { + + static final String LINE_SEPARATOR = System.lineSeparator(); + +} diff --git a/src/main/java/sehee/io/out/Printer.java b/src/main/java/sehee/io/out/Printer.java new file mode 100644 index 0000000..c9115bb --- /dev/null +++ b/src/main/java/sehee/io/out/Printer.java @@ -0,0 +1,11 @@ +package sehee.io.out; + +public interface Printer { + + void print(String message); + + void println(String message); + + void println(T object); + +} diff --git a/src/main/java/sehee/util/constant/GamePlayerMessage.java b/src/main/java/sehee/util/constant/GamePlayerMessage.java new file mode 100644 index 0000000..f1b2477 --- /dev/null +++ b/src/main/java/sehee/util/constant/GamePlayerMessage.java @@ -0,0 +1,13 @@ +package sehee.util.constant; + +import static sehee.util.constant.NumberBaseballGameConstant.END_NUMBER; +import static sehee.util.constant.NumberBaseballGameConstant.START_NUMBER; + +public final class GamePlayerMessage { + + public static final String OFF_MESSAGE = "애플리케이션이 종료되었습니다."; + public static final String CHOOSE_START_OR_END_MESSAGE = + "게임을 새로 시작하려면 " + START_NUMBER + ", 종료하려면 " + END_NUMBER + "를 입력하세요."; + public static final String CHOOSE_START_OR_END_EXCEPTION_MESSAGE = "1(시작) 혹은 9(종료)를 입력해주세요."; + +} diff --git a/src/main/java/sehee/util/constant/NumberBaseballGameConstant.java b/src/main/java/sehee/util/constant/NumberBaseballGameConstant.java new file mode 100644 index 0000000..12567da --- /dev/null +++ b/src/main/java/sehee/util/constant/NumberBaseballGameConstant.java @@ -0,0 +1,12 @@ +package sehee.util.constant; + +public final class NumberBaseballGameConstant { + + public static final String NOTHING = "낫싱"; + public static final String BALL = "볼"; + public static final String STRIKE = "스트라이크"; + public static final int START_NUMBER = 1; + public static final int END_NUMBER = 9; + public static final int ANSWER_LENGTH = 3; + +} diff --git a/src/main/java/sehee/util/constant/NumberBaseballGameMessage.java b/src/main/java/sehee/util/constant/NumberBaseballGameMessage.java new file mode 100644 index 0000000..9719bd0 --- /dev/null +++ b/src/main/java/sehee/util/constant/NumberBaseballGameMessage.java @@ -0,0 +1,14 @@ +package sehee.util.constant; + +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; + +public final class NumberBaseballGameMessage { + + public static final String COMPUTER_CHOOSE_NUMBERS_MESSAGE = "컴퓨터가 " + ANSWER_LENGTH + "자의 중복 없는 숫자를 뽑았습니다."; + public static final String WRITE_NUMBERS_MESSAGE = ANSWER_LENGTH + "자의 숫자를 중복 없이 입력해주세요: "; + public static final String ALL_STRIKE_MESSAGE = ANSWER_LENGTH + "자의 숫자를 모두 맞히셨습니다."; + public static final String GAME_OVER_MESSAGE = "-------게임 종료-------"; + public static final String ANSWER_LENGTH_EXCEPTION_MESSAGE = ANSWER_LENGTH + "자의 숫자로 입력해주세요."; + public static final String DUPLICATED_EXCEPTION_MESSAGE = "1~9 사이의 모두 다른 숫자여야합니다."; + +} diff --git a/src/main/java/sehee/util/numbermaker/NumberMaker.java b/src/main/java/sehee/util/numbermaker/NumberMaker.java new file mode 100644 index 0000000..c9e36eb --- /dev/null +++ b/src/main/java/sehee/util/numbermaker/NumberMaker.java @@ -0,0 +1,9 @@ +package sehee.util.numbermaker; + +public interface NumberMaker { + + int make(); + + int[] makeAllUnique(); + +} diff --git a/src/main/java/sehee/util/numbermaker/RandomNumberMaker.java b/src/main/java/sehee/util/numbermaker/RandomNumberMaker.java new file mode 100644 index 0000000..d7885d6 --- /dev/null +++ b/src/main/java/sehee/util/numbermaker/RandomNumberMaker.java @@ -0,0 +1,43 @@ +package sehee.util.numbermaker; + +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; + +import java.util.Random; + +// package-private +public class RandomNumberMaker implements NumberMaker { + + private final Random random; + + public RandomNumberMaker(Random random) { + this.random = random; + } + + public int make() { + return random.nextInt(9) + 1; + } + + public int[] makeAllUnique() { + boolean[] isExist = new boolean[10]; + isExist[0] = true; + + int[] randomNumbers = new int[ANSWER_LENGTH]; + int count = 0; + while (count < randomNumbers.length) { + count = makeAndCountUnique(isExist, randomNumbers, count); + } + + return randomNumbers; + } + + private int makeAndCountUnique(boolean[] isExist, int[] randomNumbers, int count) { + int randomNumber = this.make(); // 1~9 + if (!isExist[randomNumber]) { // 모두 다른 숫자 + isExist[randomNumber] = true; + randomNumbers[count++] = randomNumber; + } + + return count; + } + +} diff --git a/src/test/java/sehee/answer/AnswerTest.java b/src/test/java/sehee/answer/AnswerTest.java new file mode 100644 index 0000000..e230b69 --- /dev/null +++ b/src/test/java/sehee/answer/AnswerTest.java @@ -0,0 +1,182 @@ +package sehee.answer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; +import static sehee.util.constant.NumberBaseballGameConstant.BALL; +import static sehee.util.constant.NumberBaseballGameConstant.NOTHING; +import static sehee.util.constant.NumberBaseballGameConstant.STRIKE; +import static sehee.util.constant.NumberBaseballGameMessage.ANSWER_LENGTH_EXCEPTION_MESSAGE; +import static sehee.util.constant.NumberBaseballGameMessage.DUPLICATED_EXCEPTION_MESSAGE; + +import org.assertj.core.api.ThrowableAssert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import sehee.testutil.stub.NumberMakerStub; + +class AnswerTest { + + private AnswerFactory answerFactory; + private NumberMakerStub numberMaker; + + @BeforeEach + void setup() { + numberMaker = new NumberMakerStub(); + answerFactory = new AnswerFactory(numberMaker); + } + + @Nested + class MakeTest { + + @Test + @DisplayName("numberMaker를 통해 자동으로 Answer를 생성할 수 있다.") + void successAutoMake() { + // given + int[] answerNumbers = new int[] {1, 2, 3}; + numberMaker.setNumbers(answerNumbers); + + // when + Answer autoMadeAnswer = answerFactory.make(); + + // then + assertThat(autoMadeAnswer).extracting("numbers") + .isEqualTo(answerNumbers); + } + + @Test + @DisplayName("Answer를 수동으로 생성할 수 있다.") + void successInputMake() { + // given + int[] numbers = new int[] {1, 2, 3}; + + // when + Answer answer = answerFactory.make(numbers); + + // then + assertThat(answer).extracting("numbers") + .isEqualTo(numbers); + } + + @Test + @DisplayName("input 길이가 " + ANSWER_LENGTH + "과 밎지 않아 Answer를 수동으로 생성하는 데에 실패한다.") + void failInputMakeByLength() { + // given + int[] numbers = new int[] {1, 2, 3, 4}; + + // when + ThrowableAssert.ThrowingCallable make = () -> answerFactory.make(numbers); + + // then + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(make) + .withMessage(ANSWER_LENGTH_EXCEPTION_MESSAGE); + } + + @Test + @DisplayName("중복된 숫자가 있어 Answer를 수동으로 생성하는 데에 실패한다.") + void failInputMakeByDuplicated() { + // given + int[] numbers = new int[] {1, 3, 3}; + + // when + ThrowableAssert.ThrowingCallable make = () -> answerFactory.make(numbers); + + // then + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(make) + .withMessage(DUPLICATED_EXCEPTION_MESSAGE); + } + + } + + @Nested + class MatchTest { + + @Test + @DisplayName("컴퓨터 설정값과 사용자 입력값이 모두 같은 경우 3스트라이크 결과가 나온다.") + void successMatchThreeStrike() { + // given + int[] numbers = new int[] {1, 2, 3}; + Answer computerAnswer = answerFactory.make(numbers); + Answer userAnswer = answerFactory.make(numbers); + + // when + Hint matchResult = computerAnswer.match(userAnswer); + + // then + assertThat(matchResult.isThreeStrike()).isTrue(); + assertThat(matchResult.toString()).isEqualTo(ANSWER_LENGTH + STRIKE); + } + + @ParameterizedTest(name = "[{index}] {0}개의 숫자가 같은 위치에서 값이 일치하는 경우({0}스트라이크)") + @MethodSource("sehee.testutil.source.AnswerSourceProvider#provideStrikeCase") + @DisplayName("같은 위치의 숫자값이 같은 경우를 합한 값이 스트라이크이다.") + void successMatchStrike(int strikeCount, int[] computerNumbers, int[] userNumbers) { + // given + Answer computerAnswer = answerFactory.make(computerNumbers); + Answer userAnswer = answerFactory.make(userNumbers); + + // when + Hint matchResult = computerAnswer.match(userAnswer); + + // then + assertThat(matchResult.toString()).isEqualTo(strikeCount + STRIKE); + } + + @ParameterizedTest(name = "[{index}] {0}개의 숫자가 다른 위치에서 값이 일치하는 경우({0}볼)") + @MethodSource("sehee.testutil.source.AnswerSourceProvider#provideBallCase") + @DisplayName("다른 위치의 숫자값이 같은 경우를 합한 값이 볼이다.") + void successMatchBall(int ballCount, int[] computerNumbers, int[] userNumbers) { + // given + Answer computerAnswer = answerFactory.make(computerNumbers); + Answer userAnswer = answerFactory.make(userNumbers); + + // when + Hint matchResult = computerAnswer.match(userAnswer); + + // then + assertThat(matchResult.isThreeStrike()).isFalse(); + assertThat(matchResult.toString()).isEqualTo(ballCount + BALL); + } + + @ParameterizedTest(name = "[{index}] {0}볼 {1}스트라이크인 경우") + @MethodSource("sehee.testutil.source.AnswerSourceProvider#provideBallAndStrikeCase") + @DisplayName("볼과 스트라이크가 동시에 발견될 수 있다.") + void successMatchBall(int ballCount, int strikeCount, int[] computerNumbers, int[] userNumbers) { + // given + Answer computerAnswer = answerFactory.make(computerNumbers); + Answer userAnswer = answerFactory.make(userNumbers); + + // when + Hint matchResult = computerAnswer.match(userAnswer); + + // then + assertThat(matchResult.isThreeStrike()).isFalse(); + assertThat(matchResult.toString()).isEqualTo(ballCount + BALL + " " + strikeCount + STRIKE); + } + + @Test + @DisplayName("컴퓨터 설정값과 사용자 입력값이 다른 경우 낫싱 결과가 나온다.") + void successMatchNothing() { + // given + int[] computerNumbers = new int[] {1, 2, 3}; + Answer computerAnswer = answerFactory.make(computerNumbers); + + int[] userNumbers = new int[] {4, 5, 6}; + Answer userAnswer = answerFactory.make(userNumbers); + + // when + Hint matchResult = computerAnswer.match(userAnswer); + + // then + assertThat(matchResult.isThreeStrike()).isFalse(); + assertThat(matchResult.toString()).isEqualTo(NOTHING); + } + + } + +} diff --git a/src/test/java/sehee/game/NumberBaseballGameTest.java b/src/test/java/sehee/game/NumberBaseballGameTest.java new file mode 100644 index 0000000..dd49782 --- /dev/null +++ b/src/test/java/sehee/game/NumberBaseballGameTest.java @@ -0,0 +1,55 @@ +package sehee.game; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static sehee.util.constant.NumberBaseballGameMessage.GAME_OVER_MESSAGE; + +import org.assertj.core.api.ThrowableAssert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import sehee.answer.AnswerFactory; +import sehee.exception.ExceptionHandler; +import sehee.testutil.stub.NumberMakerStub; +import sehee.testutil.stub.PrinterStub; +import sehee.testutil.stub.ReaderStub; + +class NumberBaseballGameTest { + + private NumberBaseballGame game; + private ReaderStub reader; + private PrinterStub printer; + private NumberMakerStub numberMaker; + + @BeforeEach + void setup() { + // IO + reader = new ReaderStub(); + printer = new PrinterStub(); + + // Exception + ExceptionHandler exceptionHandler = new ExceptionHandler(printer); + + // Set Game + numberMaker = new NumberMakerStub(); + AnswerFactory answerFactory = new AnswerFactory(numberMaker); + game = new NumberBaseballGame(reader, printer, answerFactory, exceptionHandler); + } + + @Test + @DisplayName("숫자 야구 게임을 시작하고 컴퓨터 설정값과 입력값이 일치하는 경우 정상적으로 종료된다.") + void successGameOver() { + // given + int[] answerNumber = new int[] {1, 2, 3}; + numberMaker.setNumbers(answerNumber); // 컴퓨터 설정값 + reader.setNumbers(answerNumber); // 사용자 입력값 + + // when + ThrowableAssert.ThrowingCallable gameOver = () -> game.play(); + + // then + assertThatNoException().isThrownBy(gameOver); + assertThat(printer.getLatestMessage()).isEqualTo(GAME_OVER_MESSAGE); + } + +} diff --git a/src/test/java/sehee/game/player/GamePlayerTest.java b/src/test/java/sehee/game/player/GamePlayerTest.java new file mode 100644 index 0000000..4a96a45 --- /dev/null +++ b/src/test/java/sehee/game/player/GamePlayerTest.java @@ -0,0 +1,53 @@ +package sehee.game.player; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static sehee.util.constant.GamePlayerMessage.OFF_MESSAGE; +import static sehee.util.constant.NumberBaseballGameConstant.END_NUMBER; + +import org.assertj.core.api.ThrowableAssert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import sehee.exception.ExceptionHandler; +import sehee.testutil.stub.GameStub; +import sehee.testutil.stub.PrinterStub; +import sehee.testutil.stub.ReaderStub; + +class GamePlayerTest { + + private GamePlayer gamePlayer; + private ReaderStub reader; + private PrinterStub printer; + + @BeforeEach + void setup() { + // IO + reader = new ReaderStub(); + printer = new PrinterStub(); + + // Exception + ExceptionHandler exceptionHandler = new ExceptionHandler(printer); + + // Set Game + GameStub game = new GameStub(printer); + + // Play Game! + gamePlayer = new GamePlayer(reader, printer, game, exceptionHandler); + } + + @Test + @DisplayName("GamePlayer를 시작하고 " + END_NUMBER + "를 누르면 게임을 정상적으로 종료할 수 있다.") + void successOff() { + // given + reader.setOneNumber(END_NUMBER); // 사용자 입력값 종료로 설정 + + // when + ThrowableAssert.ThrowingCallable on = () -> gamePlayer.on(); + + // then + assertThatNoException().isThrownBy(on); + assertThat(printer.getLatestMessage()).isEqualTo(OFF_MESSAGE); + } + +} diff --git a/src/test/java/sehee/testutil/source/AnswerSourceProvider.java b/src/test/java/sehee/testutil/source/AnswerSourceProvider.java new file mode 100644 index 0000000..91ff613 --- /dev/null +++ b/src/test/java/sehee/testutil/source/AnswerSourceProvider.java @@ -0,0 +1,31 @@ +package sehee.testutil.source; + +import java.util.stream.Stream; +import org.junit.jupiter.params.provider.Arguments; + +public final class AnswerSourceProvider { + + public static Stream provideStrikeCase() { + return Stream.of( + Arguments.of(1, new int[] {1, 2, 3}, new int[] {1, 4, 5}), + Arguments.of(2, new int[] {1, 2, 3}, new int[] {1, 2, 4}), + Arguments.of(3, new int[] {1, 2, 3}, new int[] {1, 2, 3}) + ); + } + + public static Stream provideBallCase() { + return Stream.of( + Arguments.of(1, new int[] {1, 2, 3}, new int[] {4, 5, 1}), + Arguments.of(2, new int[] {1, 2, 3}, new int[] {4, 1, 2}), + Arguments.of(3, new int[] {1, 2, 3}, new int[] {3, 1, 2}) + ); + } + + public static Stream provideBallAndStrikeCase() { + return Stream.of( + Arguments.of(2, 1, new int[] {1, 2, 3}, new int[] {3, 2, 1}), + Arguments.of(1, 1, new int[] {1, 2, 3}, new int[] {1, 5, 2}) + ); + } + +} diff --git a/src/test/java/sehee/testutil/stub/GameStub.java b/src/test/java/sehee/testutil/stub/GameStub.java new file mode 100644 index 0000000..53c2d7e --- /dev/null +++ b/src/test/java/sehee/testutil/stub/GameStub.java @@ -0,0 +1,20 @@ +package sehee.testutil.stub; + +import sehee.game.Game; + +public class GameStub implements Game { + + public static final String PLAYING_GAME_MESSAGE = "Playing game!"; + + private final PrinterStub printer; + + public GameStub(PrinterStub printer) { + this.printer = printer; + } + + @Override + public void play() { + this.printer.print(PLAYING_GAME_MESSAGE); + } + +} diff --git a/src/test/java/sehee/testutil/stub/NumberMakerStub.java b/src/test/java/sehee/testutil/stub/NumberMakerStub.java new file mode 100644 index 0000000..a33f15d --- /dev/null +++ b/src/test/java/sehee/testutil/stub/NumberMakerStub.java @@ -0,0 +1,28 @@ +package sehee.testutil.stub; + +import sehee.util.numbermaker.NumberMaker; + +public class NumberMakerStub implements NumberMaker { + + private int number; + private int[] numbers; + + public void setNumber(int number) { + this.number = number; + } + + public void setNumbers(int[] numbers) { + this.numbers = numbers; + } + + @Override + public int make() { + return number; + } + + @Override + public int[] makeAllUnique() { + return numbers; + } + +} diff --git a/src/test/java/sehee/testutil/stub/PrinterStub.java b/src/test/java/sehee/testutil/stub/PrinterStub.java new file mode 100644 index 0000000..64019e1 --- /dev/null +++ b/src/test/java/sehee/testutil/stub/PrinterStub.java @@ -0,0 +1,28 @@ +package sehee.testutil.stub; + +import sehee.io.out.Printer; + +public class PrinterStub implements Printer { + + private String latestMessage; + + public String getLatestMessage() { + return latestMessage; + } + + @Override + public void print(String message) { + latestMessage = message; + } + + @Override + public void println(String message) { + latestMessage = message; + } + + @Override + public void println(T object) { + latestMessage = object.toString(); + } + +} diff --git a/src/test/java/sehee/testutil/stub/ReaderStub.java b/src/test/java/sehee/testutil/stub/ReaderStub.java new file mode 100644 index 0000000..208d15d --- /dev/null +++ b/src/test/java/sehee/testutil/stub/ReaderStub.java @@ -0,0 +1,29 @@ +package sehee.testutil.stub; + +import sehee.io.in.Reader; + +public class ReaderStub implements Reader { + + private int oneNumber; + + private int[] numbers; + + public void setOneNumber(int oneNumber) { + this.oneNumber = oneNumber; + } + + public void setNumbers(int[] numbers) { + this.numbers = numbers; + } + + @Override + public int readOneNumber() { + return this.oneNumber; + } + + @Override + public int[] readNumbers() { + return this.numbers; + } + +} diff --git a/src/test/java/sehee/util/numbermaker/RandomNumberMakerTest.java b/src/test/java/sehee/util/numbermaker/RandomNumberMakerTest.java new file mode 100644 index 0000000..eed2f2d --- /dev/null +++ b/src/test/java/sehee/util/numbermaker/RandomNumberMakerTest.java @@ -0,0 +1,57 @@ +package sehee.util.numbermaker; + +import static org.assertj.core.api.Assertions.assertThat; +import static sehee.util.constant.NumberBaseballGameConstant.ANSWER_LENGTH; + +import java.util.Random; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +class RandomNumberMakerTest { + + private RandomNumberMaker numberMaker; + + @BeforeEach + void setup() { + numberMaker = new RandomNumberMaker(new Random()); + } + + @Nested + class MakeTest { + + @Test + @DisplayName("1~9 사이의 1자리 랜덤 숫자를 만들 수 있다.") + void successMake() { + // given, when + int randomNumber = numberMaker.make(); + + // then + assertThat(randomNumber).isBetween(1, 9); + } + + } + + @Nested + class makeAllUnique { + + @Test + @DisplayName("1~9 사이의 랜덤 유니크 숫자를 " + ANSWER_LENGTH + "자로 만들 수 있다.") + void successMakeAllUnique() { + // given, when + int[] randomUniqueNumbers = numberMaker.makeAllUnique(); + + int[] numberExistCount = new int[10]; + for (int number : randomUniqueNumbers) { + numberExistCount[number]++; + } + + // then + assertThat(randomUniqueNumbers).hasSize(ANSWER_LENGTH); + assertThat(numberExistCount).containsAnyOf(0, 1); + } + + } + +}