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

[2단계 - 사다리 게임 실행] 테오(최우성) 미션 제출합니다. #194

Merged
merged 27 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
23bd55e
feat: 리스트 미션 및 테스트코드 구현
woosung1223 Feb 21, 2023
b2ee1c0
docs: 기능 목록 추가
woosung1223 Feb 21, 2023
d202412
feat: 사다리 게임 실행 결과 입력 기능 생성
woosung1223 Feb 21, 2023
1ad9b1d
feat: 결과를 보고 싶은 사람을 입력하는 기능 생성
woosung1223 Feb 21, 2023
f99315f
feat: 사다리의 한 곳이 어디로 이어지는지 반환하는 기능 생성
woosung1223 Feb 22, 2023
c39ea9f
chore: 메서드명을 이해하기 쉽도록 변경
woosung1223 Feb 22, 2023
dd4edb2
feat: 플레이어 별 사다리 게임 결과를 생성하는 기능 구현
woosung1223 Feb 22, 2023
6947697
feat: 게임 결과를 반환하는 기능 생성
woosung1223 Feb 22, 2023
0c6d138
feat: 사다리 게임 흐름 제어 기능 생성
woosung1223 Feb 22, 2023
03463f7
fix: testInstance를 클래스 단위로 변경
woosung1223 Feb 22, 2023
ecdf925
refactor: 예외 발생 테스트의 경우 assertThatThrownBy 사용
woosung1223 Feb 22, 2023
e76f02f
refactor: exception 패키지를 도메인 패키지 하위로 이동
woosung1223 Feb 22, 2023
a3cea2e
refactor: View단에서 예외 메세지를 생성하도록 변경
woosung1223 Feb 23, 2023
0b18961
chore: 메소드 및 프로퍼티 네이밍을 이해하기 쉽도록 변경
woosung1223 Feb 23, 2023
6999cc1
docs: 기능 목록 및 고민사항 작성
woosung1223 Feb 23, 2023
c9b7894
chore: 클래스명 변경에 따른 메소드 및 프로퍼티명 변경
woosung1223 Feb 27, 2023
effa549
chore: 메소드 네이밍이 단일 책임을 가지도록 수정
woosung1223 Feb 27, 2023
fcac921
refactor: 예외 발생 시 사용자에게 보여질 행위를 담당하는 객체 생성
woosung1223 Feb 27, 2023
b7f40b9
refactor: 모든 예외를 RuntimeException으로 Catch하도록 변경
woosung1223 Feb 27, 2023
e7e85b5
refactor: 의존관계를 명확히 하기 위해 View 비static화
woosung1223 Feb 27, 2023
6ce9d4d
fix: Runtime 예외도 catch 하도록 수정
woosung1223 Feb 27, 2023
ba83dc4
refactor: 원시값이 의미를 가지도록 상수화
woosung1223 Feb 27, 2023
579279d
refactor: 메소드 분리 및 PREFIX 삽입 자동화
woosung1223 Feb 27, 2023
0ca2daa
docs: 고민사항 추가 기재
woosung1223 Feb 27, 2023
55774b5
refactor: 메소드 네이밍 수정
woosung1223 Feb 27, 2023
9ff6259
refactor: 변수명을 이해하기 쉽도록 변경
woosung1223 Feb 27, 2023
8acc87f
refactor: 플레이어 객체와 플레이어 이름 객체 통합
woosung1223 Feb 27, 2023
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
40 changes: 34 additions & 6 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,39 @@
### UI

- 입력
- [x] 참여할 사람 이름 입력 문구
- [x] 최대 사다리 높이 입력 문구
- [x] 참여할 사람 이름 입력
- [x] 최대 사다리 높이 입력
- [x] 사다리 게임 실행 결과 입력
- [x] 결과를 보고 싶은 사람 입력


- 출력
- [x] `실행 결과` 출력
- [x] 참여자 목록 출력
- [x] 사다리 게임 결과 출력
- [x] 개인 별 결과 출력
- [x] 전체 결과 출력


### 기능
- **플레이어**
- [x] 플레이어의 이름을 최소 1자, 최대 5자까지 입력받을 수 있다.
- [x] 플레이어는 최소 2명 이상 참여해야 한다.
- [x] 플레이어 벌 사다리 게임 결과를 저장한다.


- **사다리**
- [x] 사다리 높이 입력을 통해 사다리를 생성한다.
- [x] 사다리 발판을 랜덤으로 생성한다.
- [x] 만약 만드려는 사다리 발판의 왼쪽에 발판이 있는 경우 해당 위치의 발판은 만들지 않는다.
- [x] 사다리의 한 곳이 어디로 이어지는지 반환한다.


- **사다리 게임**
- [x] 플레이어 별로 게임 결과를 생성한다.
- [x] 게임 결과를 반환한다.
- [x] 특정 플레이어의 게임 결과를 반환한다.
- [x] 전체 플레이어의 게임 결과를 반환한다.

### 예외 사항
- **플레이어**
Expand All @@ -31,6 +47,9 @@
- [x] 사다리의 높이가 `(플레이어 수) - 1`이상이 아닌 경우 예외가 발생한다.


- **사다리 게임**
- [x] 없는 플레이어의 결과를 보고싶을 때 예외가 발생한다.

---

### 1단계 변경사항
Expand All @@ -42,17 +61,26 @@
- [x] Line, Ladder 객체가 스스로 상태를 관리하도록 변경

### 1단계 고민사항
- [ ] Block의 status 필드가 랜덤 값만을 위한 필드였기에 제거했는데, <br>
- [x] Block의 status 필드가 랜덤 값만을 위한 필드였기에 제거했는데, <br>
따라서 ***랜덤하게 Block을 가져오려면*** Blocks.values() 에서 가져와야 했음. <br>
매번 Blocks.values()로 접근할 바에, RandomBlockGenerator에 캐싱함! 괜찮은 방법인가? <br>
<br>
- [ ] 서브웨이가 말해주신 것처럼, 시스템이 핵심 ***도메인 로직 - Maker 로직*** 으로 분리되어 있다. <br>

- [x] 서브웨이가 말해주신 것처럼, 시스템이 핵심 ***도메인 로직 - Maker 로직*** 으로 분리되어 있다. <br>
즉, 사다리 게임의 규칙을 어기는 Line, Ladder가 언제든지 탄생할 수 있다는 점도 문제이고, 핵심 도메인 객체가 <br>
스스로 상태를 관리하지 못하는 것도 문제이다. 그러면 Builder 안의 로직을 Line, Ladder 안으로 옮기면 안되나? <br>
왜 난 Builder를 만들었을까 생각해보니, 랜덤이 포함되어 있기 때문이다. 랜덤을 핵심 도메인 객체가 다뤄서는 테스트가 어렵고 <br>
결국 랜덤 값을 외부에서 주입받는 형태가 되어야 하는데 .. 핵심 도메인 객체가 프로퍼티나 파라미터로 BlockGenerator를 받는 것도 <br>
이상한 구조가 아닐까? <br>
<br>



---
### 2단계 고민사항
- [ ] Player의 역할이 너무 빈약하지는 않은가? 객체 분리를 떠나서.
- [ ] players가 책임이 늘어남에 따라 일급 컬렉션에서 벗어남. 요구사항을 벗어나게 되었음.
- [ ] 프로퍼티는 가능한 없는 것이 좋은가? LadderGameController에서 LadderGame을 프로퍼티로 가지면서
의존성 주입을 받을지, 아니면 그냥 파라미터로 계속 Passing 할지 고민.
- [ ] try - catch 안에 if, while 등 넣으면 들여쓰기가 2를 넘어가기에 안되는걸까? 규칙에 매몰된 것은 아닐까?
- [ ] "all"에 관한 처리는 어떻게 할까? 컨트롤러에서 원시값 문자열을 그대로 다루는게 맞을까?
- [ ] 직접적인 setter는 아니지만, Players에서 게임 기록을 저장하는 부분이 setter와 동일하다고 볼 수 있지 않을까?
- [ ] commit log에 누구나 이해할 수 있게 기술적인 정보는 전혀 남기지 않음. 이런 방식이 괜찮은가?
50 changes: 41 additions & 9 deletions src/main/java/ladder/controller/LadderGameController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package ladder.controller;

import ladder.domain.rule.RandomBlockGenerator;
import ladder.domain.game.LadderGame;
import ladder.domain.rule.RandomStoolGenerator;
import ladder.domain.ladder.Ladder;
import ladder.domain.player.Players;
import ladder.exception.CustomException;
import ladder.domain.exception.CustomException;
import ladder.view.InputView;
import ladder.view.OutputView;

Expand All @@ -13,10 +14,21 @@
public class LadderGameController {

public void run() {
try {
LadderGame ladderGame = initLadderGame();

ladderGame.letPlayersToGoDown();
showLadder(ladderGame);
startGameResultLoop(ladderGame);
} catch (CustomException e) {
OutputView.printErrorMessage(e);
}
}

private LadderGame initLadderGame() {
Players players = initPlayers();
Ladder ladder = initLadder(players.size());

showResult(players, ladder);
return initLadderGame(players, ladder);
}

private Players initPlayers() {
Expand All @@ -32,23 +44,43 @@ private Players initPlayers() {
private Ladder initLadder(int playerNumber) {
try {
final int height = InputView.inputLadderHeight();
return new Ladder(playerNumber, height, new RandomBlockGenerator());
return new Ladder(playerNumber, height, new RandomStoolGenerator());
} catch (CustomException e) {
OutputView.printErrorMessage(e);
return initLadder(playerNumber);
}
}

private void showResult(Players players, Ladder ladder) {
List<String> playersName = mapPlayersToPlayersName(players);
private LadderGame initLadderGame(Players players, Ladder ladder) {
try {
List<String> destinations = InputView.inputLadderDestination();
return new LadderGame(players, ladder, destinations);
} catch (CustomException e) {
OutputView.printErrorMessage(e);
return initLadderGame(players, ladder);
}
}

private void showLadder(LadderGame ladderGame) {
OutputView.printGameResultHeader();
OutputView.printPlayersName(playersName);
OutputView.printLadder(ladder);
OutputView.printWithFormat(mapPlayersToPlayersName(ladderGame.getPlayers()));
OutputView.printLadder(ladderGame.getLadder());
OutputView.printWithFormat(ladderGame.getDestinations());
}

private List<String> mapPlayersToPlayersName(Players players) {
return players.getPlayers().stream()
.map(player -> player.getPlayerName().getName())
.collect(Collectors.toUnmodifiableList());
}

private void startGameResultLoop(LadderGame ladderGame) {
String playerName = InputView.inputPlayerWhoNeedsGameResult();

while (!playerName.equals("all")) {
OutputView.printOneGameResult(ladderGame.getOneLadderGameResult(playerName));
playerName = InputView.inputPlayerWhoNeedsGameResult();
}
OutputView.printAllGameResult(ladderGame.getAllLadderGameResult());
}
}
4 changes: 4 additions & 0 deletions src/main/java/ladder/domain/exception/CustomException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class CustomException extends RuntimeException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class LadderLengthException extends CustomException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class NoSuchPlayerException extends CustomException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class NotIntegerException extends CustomException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class PlayerNameLengthException extends CustomException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ladder.domain.exception;

public class PlayerNumberException extends CustomException {
}
54 changes: 54 additions & 0 deletions src/main/java/ladder/domain/game/LadderGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package ladder.domain.game;

import ladder.domain.ladder.Ladder;
import ladder.domain.player.Player;
import ladder.domain.player.Players;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LadderGame {

private final Players players;
private final Ladder ladder;
private final List<String> destinations;

public LadderGame(Players players, Ladder ladder, List<String> destinations) {
this.players = players;
this.ladder = ladder;
this.destinations = List.copyOf(destinations);
}

public void letPlayersToGoDown() {
List<String> gameRecord = new ArrayList<>();
int location = 0;

for (int i = 0; i < players.size(); i++) {
int finalDestination = ladder.getDestinationOf(location++);
String gameResultForOneLocation = destinations.get(finalDestination);
gameRecord.add(gameResultForOneLocation);
}
players.recordGameResult(gameRecord);
}

public Map<Player, String> getAllLadderGameResult() {
return players.getAllGameRecords();
}

public Map.Entry<Player, String> getOneLadderGameResult(String playerName) {
return players.getGameRecordFor(playerName);
}

public Players getPlayers() {
return players;
}

public Ladder getLadder() {
return ladder;
}

public List<String> getDestinations() {
return List.copyOf(destinations);
}
}
20 changes: 14 additions & 6 deletions src/main/java/ladder/domain/ladder/Ladder.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
package ladder.domain.ladder;

import ladder.domain.rule.BlockGenerator;
import ladder.exception.LadderLengthException;
import ladder.domain.rule.StoolGenerator;
import ladder.domain.exception.LadderLengthException;

import java.util.ArrayList;
import java.util.List;

public class Ladder {

private final BlockGenerator blockGenerator;
private final StoolGenerator stoolGenerator;
private final List<Line> lines;

public Ladder(final int playerNumber, final int height, final BlockGenerator blockGenerator) {
public Ladder(final int playerNumber, final int height, final StoolGenerator stoolGenerator) {
validateLadderLength(playerNumber, height);
this.blockGenerator = blockGenerator;
this.stoolGenerator = stoolGenerator;
this.lines = generateEachLines(playerNumber, height);
}

Expand All @@ -27,11 +27,19 @@ private List<Line> generateEachLines(final int playerNumber, final int height) {
List<Line> lines = new ArrayList<>();

for (int i = 0; i < height; i++) {
lines.add(new Line(playerNumber, blockGenerator));
lines.add(new Line(playerNumber, stoolGenerator));
}
return lines;
}

public int getDestinationOf(int startingLocation) {
int currentLocation = startingLocation;
for (Line line : lines) {
currentLocation = line.goDownAndGetLocation(currentLocation);
}
return currentLocation;
}

public List<Line> getLines() {
return List.copyOf(lines);
}
Expand Down
64 changes: 45 additions & 19 deletions src/main/java/ladder/domain/ladder/Line.java
Original file line number Diff line number Diff line change
@@ -1,38 +1,64 @@
package ladder.domain.ladder;

import ladder.domain.rule.BlockGenerator;
import ladder.domain.rule.StoolGenerator;

import java.util.List;
import java.util.Stack;

public class Line {

private final BlockGenerator blockGenerator;
private final List<Block> blocks;
private final StoolGenerator stoolGenerator;
private final List<Stool> stools;

public Line(final int playerNumber, final BlockGenerator blockGenerator) {
this.blockGenerator = blockGenerator;
this.blocks = makeBlocks(playerNumber - 1);
public Line(final int playerNumber, final StoolGenerator stoolGenerator) {
this.stoolGenerator = stoolGenerator;
this.stools = makeBlocks(playerNumber - 1);
}

private List<Block> makeBlocks(final int blockCount) {
Stack<Block> temporaryBlocks = new Stack<>();
temporaryBlocks.push(blockGenerator.generate());
while (temporaryBlocks.size() != blockCount) {
Block block = generateBlock(temporaryBlocks.peek());
temporaryBlocks.push(block);
private List<Stool> makeBlocks(final int blockCount) {
Stack<Stool> temporaryStools = new Stack<>();
temporaryStools.push(stoolGenerator.generate());
while (temporaryStools.size() != blockCount) {
Stool stool = generateBlock(temporaryStools.peek());
temporaryStools.push(stool);
}
return List.copyOf(temporaryBlocks);
return List.copyOf(temporaryStools);
}

private Block generateBlock(final Block previousBlock) {
if (previousBlock.isExistBlock()) {
return Block.EMPTY;
private Stool generateBlock(final Stool previousStool) {
if (previousStool.isExistBlock()) {
return Stool.EMPTY;
}
return blockGenerator.generate();
return stoolGenerator.generate();
}

public List<Block> getBlocks() {
return List.copyOf(blocks);
public int goDownAndGetLocation(final int currentLocation) {

Choose a reason for hiding this comment

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

함수 이름에서 2개의 역할을 하도록 네이밍이 되어있는데, 하나의 역할을 하도록 만드는 것이 좋지 않을까요~?

int newLocation = currentLocation;
if (hasWayToGo(currentLocation)) {
newLocation = getUpdatedLocation(currentLocation);
}
return newLocation;
}

private boolean hasWayToGo(final int location) {
return isStoolExistAt(location - 1) || isStoolExistAt(location);
}

private boolean isStoolExistAt(final int location) {
if (location < 0 || location >= stools.size()) {
return false;
}
return stools.get(location) == Stool.EXIST;
}

private int getUpdatedLocation(final int location) {
if (isStoolExistAt(location)) {
return location + 1;
}
return location - 1;
}

public List<Stool> getStools() {
return List.copyOf(stools);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package ladder.domain.ladder;

public enum Block {
public enum Stool {

EMPTY,
EXIST;

public boolean isExistBlock() {
return this == Block.EXIST;
return this == Stool.EXIST;
}
}
Loading