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

[부산대 BE_장진영] 미션 제출합니다. #143

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
42d88b1
Update README.md
ddglackrp May 5, 2024
baa9b21
Add Computer class
ddglackrp May 5, 2024
f1e7865
Feat "Computer 클래스 멤버 변수 초기화 기능 추가"
ddglackrp May 5, 2024
e55bc72
Feat "재게임 시 3자리 숫자 재생성 로직 추가"
ddglackrp May 5, 2024
34b3e39
Feat "getter setter 기능 추가"
ddglackrp May 5, 2024
7caf33c
Feat "BaseBallGame 클래스 추가"
ddglackrp May 5, 2024
ea4b0a5
Feat "스트라이크 개수 확인 로직 추가"
ddglackrp May 5, 2024
249be99
Feat "볼 개수 확인 로직 추가"
ddglackrp May 5, 2024
741123a
Feat "스트라이크, 볼 정보 출력 로직 추가"
ddglackrp May 5, 2024
97975d6
Feat "Application 추가"
ddglackrp May 5, 2024
eba2a7e
Update "README.md"
ddglackrp May 5, 2024
6697507
Chore "의존성 추가"
ddglackrp May 5, 2024
9091b6f
Test "BaseBallGame Test 추가"
ddglackrp May 5, 2024
0db15dc
Refactor "checkNumberValid 리팩토링"
May 5, 2024
18d416d
Feat "Add GameCondition class"
May 5, 2024
38b961d
Refactor "BaseBallGameService 리팩토링 진행"
May 5, 2024
242d92d
Refactor "Application 리팩토링 진행"
May 5, 2024
e801de5
Test "입력 유효성 테스트 추가"
May 5, 2024
822cda4
Refactor "checkNumberValid 로직 수정"
May 5, 2024
e94181b
Test "inputValidTest 로직 수정"
May 5, 2024
955dcf4
Refactor "Application 클래스 구조 변경"
May 5, 2024
0f39121
Test "Application 클래스 Test 로직 추가"
May 5, 2024
f6cf723
Refactor "Application 클래스 try - catch 로직 변경"
May 5, 2024
a6051f2
Test "컴퓨터 (상대방) 테스트 추가"
May 6, 2024
edc93c4
Refactoring "Application class exception handler 추가"
May 6, 2024
93764d1
Test "Application Test 코드 로직 변경"
May 6, 2024
b03e1c2
Chore "build.gradle 설정 변경"
May 6, 2024
10b11e4
Chore "build.gradle 설정 변경"
May 6, 2024
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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
# java-baseball-precourse
# java-baseball-precourse

## 구현 기능 목록
- 상대방 (컴퓨터) 클래스
- 컴퓨터 클래스를 생성할 때 랜덤 3자리 수 생성
- 사용자가 다시 게임을 진행할 때 랜덤 3자리 수 다시 생성
- BaseBallGame (게임 진행 로직) 클래스
- 스트라이크 개수 체크하는 함수
- 볼 개수 체크하는 함수
- 스트라이크, 볼, 낫싱 정보 출력하는 함수
- main 클래스
- 게임 진행 로직
- BaseBallGame 클래스 Test 추가
- Main Test 추가
7 changes: 7 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,10 @@ dependencies {
test {
useJUnitPlatform()
}

/*
아래 설정을 추가해 주지 않으면 제 pc에서는 실행이 되지 않아서 추가했습니다.
*/
tasks.withType(JavaCompile){
options.encoding = "UTF-8"
}
98 changes: 98 additions & 0 deletions src/main/java/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import computer.Computer;
import game.BaseBallGameService;
import game.GameCondition;

import java.util.Scanner;

public class Application {

private final Computer computer;
private final BaseBallGameService gameService;
private final GameCondition gameCondition;

public Application(Computer computer, BaseBallGameService gameService, GameCondition gameCondition) {
this.computer = computer;
this.gameService = gameService;
this.gameCondition = gameCondition;
}

public Computer getComputer() {
return computer;
}

private boolean inputValidCheck(String clientNumber) {
try{
gameService.checkNumberValid(clientNumber);
return true;
}
catch (IllegalArgumentException e){
System.out.println(e.getMessage());
return false;
}
}

private void printGameInfo(int strike, int ball) {
if(strike == 3){
System.out.println("3개의 숫자를 모두 맞히셨습니다! 게임 종료");
gameCondition.changeCollectAnswer(true);
}else{
String info = gameService.printGameInfo(strike, ball);
System.out.println(info);
}
}

private void checkRestartGame(String continueGame){
try{
if("1".equals(continueGame)){
computer.reGenerateNumber();
gameCondition.changeCollectAnswer(false);
}
else if("2".equals(continueGame)){
gameCondition.changePlayGame(false);
}
else{
throw new IllegalArgumentException("입력이 1과 2가 아닙니다. 애플리케이션을 종료합니다.");
}
}
catch (IllegalArgumentException e){
System.out.println(e.getMessage());
gameCondition.changePlayGame(false);
}
}
public void start(){
Scanner scanner = new Scanner(System.in);

while(gameCondition.canPlayGame()){
System.out.print("숫자를 입력해 주세요 : ");
String clientNumber = scanner.nextLine();

if (!inputValidCheck(clientNumber)) {
scanner.close();
break;
}

int strike = gameService.checkStrike(computer.getNumber(), clientNumber);
int ball = gameService.checkBall(computer.getNumber(), clientNumber);

printGameInfo(strike, ball);

if(gameCondition.canCollectAnswer()){
System.out.println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.");
String continueGame = scanner.nextLine();
checkRestartGame(continueGame);
}
}
scanner.close();
System.out.println("안녕히 가세요.");
}

public static void main(String[] args) {
Computer computer = new Computer();
BaseBallGameService gameService = new BaseBallGameService();
GameCondition gameCondition = new GameCondition();

Application app = new Application(computer, gameService, gameCondition);
app.start();
}

}
45 changes: 45 additions & 0 deletions src/main/java/computer/Computer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package computer;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Computer {

private String number;

public Computer() {
number = createBaseballNumber();
}

private String createBaseballNumber(){
Random random = new Random();
Set<Integer> numbers = new HashSet<>();

while(numbers.size() < 3){
int randomNumber = random.nextInt(9) + 1;
numbers.add(randomNumber);
}

String createNumber = "";
for (Integer num : numbers) {
createNumber += num;
}

return createNumber;
}

public void reGenerateNumber(){
number = createBaseballNumber();
}


public String getNumber() {
return number;
}

public void changeNumber(String number){
this.number = number;
}

}
63 changes: 63 additions & 0 deletions src/main/java/game/BaseBallGameService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package game;

public class BaseBallGameService {

public int checkStrike(String computerNumber, String userNumber){
int strike = 0;

for(int i=0; i<3; i++){
if(computerNumber.charAt(i) == userNumber.charAt(i)){
strike++;
}
}

return strike;
}

public int checkBall(String computerNumber, String userNumber){
int ball = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i != j && computerNumber.charAt(i) == userNumber.charAt(j)) {
ball++;
}
}
}
return ball;
}

public String printGameInfo(int strike, int ball){
if(strike == 0 && ball == 0){
return "낫싱";
} else if(strike > 0 && ball == 0) {
return strike+"스트라이크";
} else if(strike == 0 && ball > 0){
return ball+"볼";
}
else{
return ball+"볼 "+strike+"스트라이크";
}
}

public boolean checkNumberValid(String number){
if (number.length() != 3) {
throw new IllegalArgumentException("잘못된 입력입니다. 애플리케이션을 종료합니다.");
}

for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);

if (!Character.isDigit(c) || c == '0') {
throw new IllegalArgumentException("잘못된 입력입니다. 애플리케이션을 종료합니다.");
}

long count = number.chars().filter(n -> n == c).count();
if (count > 1){
throw new IllegalArgumentException("잘못된 입력입니다. 애플리케이션을 종료합니다.");
}
}

return true;
}

}
27 changes: 27 additions & 0 deletions src/main/java/game/GameCondition.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package game;

public class GameCondition {
boolean playGame;
boolean collectAnswer;

public GameCondition() {
this.playGame = true;
this.collectAnswer = false;
}

public boolean canPlayGame() {
return playGame;
}

public boolean canCollectAnswer() {
return collectAnswer;
}

public void changeCollectAnswer(boolean collectAnswer){
this.collectAnswer = collectAnswer;
}

public void changePlayGame(boolean playGame){
this.playGame = playGame;
}
}
84 changes: 84 additions & 0 deletions src/test/java/ApplicationTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import computer.Computer;
import game.BaseBallGameService;
import game.GameCondition;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

class ApplicationTest {

private final Application application = new Application(
new Computer(),
new BaseBallGameService(),
new GameCondition()
);

private final InputStream systemIn = System.in;

private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream testOut = new ByteArrayOutputStream();

@BeforeEach
public void setUp() {
System.setOut(new PrintStream(testOut));
}
@AfterEach
public void restoreSystemInput() {
System.setOut(standardOut);
System.setIn(systemIn);
}

@Test
@DisplayName("서로다른 1~9 까지의 3자리 수 입력이 아닌 경우")
void userInvalidInputTest(){
String invalidInput = "a23";
ByteArrayInputStream testIn = new ByteArrayInputStream(invalidInput.getBytes());
System.setIn(testIn);

application.start();

assertTrue(testOut.toString().contains("잘못된 입력입니다. 애플리케이션을 종료합니다."));
assertTrue(testOut.toString().contains("안녕히 가세요."));

}

@Test
@DisplayName("게임이 종료되고 1과 2의 입력이 아닌 경우")
void userInvalidInputTest2(){
application.getComputer().changeNumber("123");
String invalidInput = "123\na\n";
ByteArrayInputStream testIn = new ByteArrayInputStream(invalidInput.getBytes());
System.setIn(testIn);

application.start();
assertTrue(testOut.toString().contains("입력이 1과 2가 아닙니다. 애플리케이션을 종료합니다."));
assertTrue(testOut.toString().contains("안녕히 가세요."));
}

@Test
@DisplayName("게임 정상 흐름 테스트")
void normalFlowTest(){
application.getComputer().changeNumber("123");
String invalidInput = "123\n2\n";
ByteArrayInputStream testIn = new ByteArrayInputStream(invalidInput.getBytes());
System.setIn(testIn);

application.start();

assertTrue(testOut.toString().contains("3개의 숫자를 모두 맞히셨습니다! 게임 종료"));
assertTrue(testOut.toString().contains("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요."));
assertTrue(testOut.toString().contains("안녕히 가세요."));
}

}
31 changes: 31 additions & 0 deletions src/test/java/computer/ComputerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package computer;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.HashSet;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

class ComputerTest {

private final Computer computer = new Computer();

@Test
@DisplayName("컴퓨터 서로다른 3자리 숫자 생성 테스트")
void computerInitTest(){
String number = computer.getNumber();

Set<Integer> numbers = new HashSet<>();

for(int i=0; i<3; i++){
numbers.add(Integer.valueOf(number.charAt(i)));
}

assertThat(numbers.size()).isEqualTo(3);
}

}
Loading