-
Notifications
You must be signed in to change notification settings - Fork 39
[그리디] 황혜림 사다리 미션 제출합니다. #46
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
Open
HyerimH
wants to merge
23
commits into
next-step:hyerimh
Choose a base branch
from
HyerimH:main
base: hyerimh
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
d406e4e
[기능추가][1-3단계] 기본 로직 추가
HyerimH 02e4f1b
feat: 4단계 input 로직 추가
HyerimH 822b951
feat: 4단계 실행 결과 클래스 추가
HyerimH b8890c3
feat: 4단계 플레이어 관련 클래스 추가
HyerimH a9280b9
feat: Enum 클래스 Point 추가
HyerimH 5f22466
feat: 사다리 게임 전체 제어 로직 추가
HyerimH 68a877d
feat: Ladder 객체 추가
HyerimH ea15772
feat: Line 객체 추가
HyerimH 8c3d375
readme 추가
HyerimH b072ff6
feat: Position 객체 추가
HyerimH de6ab68
feat: LadderHeight 객체 추가
HyerimH 17e5f24
feat: 4단계 출력 로직 추가
HyerimH 8ede05c
feat: test 코드 추가
HyerimH 840dbf5
feat: TestLadderGenerator 추가
HyerimH f2d5016
refactor: 결과판단 controller로 이동
HyerimH 02d33d5
feat: name 검증 코드 추가
HyerimH 8decdbf
feat: 플레이어 존재 예외 처리 추가
HyerimH e2ee985
feat: 결과 출력문 추가
HyerimH 17c809c
feat: 사다리 출력 보완
HyerimH 3c75d42
refactor: 방어적 복사 보완
HyerimH 85a2870
refactor: 피드백 반영
HyerimH e68fb11
refactor: 함수형 인터페이스 적용
HyerimH 51598a8
refactor: 불필요 로직 삭제
HyerimH File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# 사다리 게임(Ladder Game) | ||
|
||
## 🎯 게임 개요 | ||
|
||
이 게임은 참여 인원과 실행 결과를 입력하여 개인별 결과를 출력해주는 사다리 게임입니다! | ||
|
||
## 📌 게임 진행 방식 | ||
|
||
- **참여 인원 입력**: 참여 인원의 이름을 입력해주세요. (이름은 쉼표(,)를 기준으로 구분하고 최대 5글자) | ||
- **실행 결과 입력**: 원하는 실행 결과를 입력해주세요. (쉼표(,)를 기준으로 구분, 예시-꽝, 5000 등) | ||
- **사다리 높이 입력**: 원하는 사다리 높이를 입력해주세요. | ||
- **전체 결과 발표**: 전체 사다리 결과가 나옵니다. | ||
- **지목 결과 발표**: 지목한 사람의 실행 결과를 확인합니다. (예-tommy or all) | ||
|
||
## 🚀 실행 방법 | ||
|
||
1. 프로그램을 실행합니다. | ||
2. 참여 인원과 실행 결과를 입력합니다. | ||
3. 사다리 높이를 입력해 사다리를 만듭니다. | ||
4. 궁금한 사람의 이름을 지목하여 그 결과를 확인하세요! 🎉 | ||
|
||
## 🛠 주요 기능 | ||
|
||
- **사다리 생성**: 원하는 높이의 사다리 생성. | ||
- **결과 계산**: 각 인원의 사다리 타기 결과 계산. | ||
|
||
## ✅ 체크리스트 | ||
|
||
### 요구사항 | ||
- [v] 게임 개요 및 진행 방식 정리 | ||
- [v] 필요한 기능 도출 (입력, 번호 생성, 결과 처리) | ||
|
||
### 리팩토링 | ||
- [v] enum 클래스 이용 | ||
- [v] 매직 넘버 제거 | ||
- [v] indent depth 1까지 허용 | ||
- [v] 일급 컬렉션 사용 | ||
- [v] 함수형 문법 사용 | ||
- [v] 모든 엔티티 작게 유지 | ||
|
||
### 테스트 | ||
- [v] 정상 입력값에 대한 동작 확인 | ||
- [v] 잘못된 입력값 처리 테스트 | ||
- [v] 사다리 생성 동작 확인 | ||
- [v] 결과값 확인 | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import controller.LadderController; | ||
import util.RandomLadderGenerator; | ||
import view.InputView; | ||
import view.OutputView; | ||
|
||
public class Application { | ||
|
||
public static void main(String[] args) { | ||
InputView inputView = new InputView(); | ||
OutputView outputView = new OutputView(); | ||
RandomLadderGenerator generator = new RandomLadderGenerator(); | ||
LadderController controller = new LadderController(inputView, outputView, generator); | ||
controller.run(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package controller; | ||
|
||
import static view.InputView.INPUT_EXCEPTION_MESSAGE; | ||
|
||
import java.util.Map; | ||
import java.util.stream.Collectors; | ||
import model.goal.Goal; | ||
import model.goal.Goals; | ||
import model.ladder.Ladder; | ||
import model.LadderGame; | ||
import model.ladder.LadderHeight; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import model.player.Player; | ||
import model.player.PlayerName; | ||
import model.player.Players; | ||
import model.player.Position; | ||
import util.LadderGenerator; | ||
import view.InputView; | ||
import view.OutputView; | ||
|
||
public class LadderController { | ||
|
||
private final InputView inputView; | ||
private final OutputView outputView; | ||
private final LadderGenerator generator; | ||
|
||
public LadderController(InputView inputView, OutputView outputView, LadderGenerator generator) { | ||
this.inputView = inputView; | ||
this.outputView = outputView; | ||
this.generator = generator; | ||
} | ||
|
||
public void run() { | ||
Players players = createPlayers(); | ||
Goals goals = createGoals(players); | ||
LadderHeight height = createLadderHeight(players.size()); | ||
Ladder ladder = Ladder.of(players, height, generator); | ||
LadderGame game = new LadderGame(ladder); | ||
Map<Player, Goal> results = game.play(players, goals); | ||
outputView.printLadder(ladder, players, goals); | ||
showResults(players, results); | ||
} | ||
|
||
private Players createPlayers() { | ||
try { | ||
List<String> rawNames = inputView.inputPlayers(); | ||
return Players.from(rawNames); | ||
} catch (IllegalArgumentException e) { | ||
outputView.printErrorMessage(e.getMessage()); | ||
return createPlayers(); | ||
} | ||
} | ||
|
||
private Goals createGoals(Players players) { | ||
try { | ||
List<String> rawGoals = inputView.inputGoals(); | ||
return Goals.from(rawGoals, players.size()); | ||
} catch (IllegalArgumentException e) { | ||
outputView.printErrorMessage(e.getMessage()); | ||
return createGoals(players); | ||
} | ||
} | ||
|
||
private LadderHeight createLadderHeight(int playerCount) { | ||
try { | ||
int height = inputView.inputLadderHeight(); | ||
return new LadderHeight(height, playerCount); | ||
} catch (IllegalArgumentException e) { | ||
outputView.printErrorMessage(e.getMessage()); | ||
return createLadderHeight(playerCount); | ||
} | ||
} | ||
|
||
private void showResults(Players players, Map<Player, Goal> results) { | ||
String input = inputView.inputPlayerForResult(); | ||
while (!input.isBlank()) { | ||
input = processResultInput(input, players, results); | ||
} | ||
} | ||
|
||
private String processResultInput(String input, Players players, Map<Player, Goal> results) { | ||
try { | ||
selectResult(input, players, results); | ||
return inputView.inputPlayerForResult(); | ||
} catch (IllegalArgumentException e) { | ||
outputView.printErrorMessage(e.getMessage()); | ||
return inputView.inputPlayerForResult(); | ||
} | ||
} | ||
|
||
private void selectResult(String input, Players players, Map<Player, Goal> results) { | ||
if (input.equals("all")) { | ||
outputView.printAllResults(results); | ||
return; | ||
} | ||
players.validateContainsPlayer(input); | ||
outputView.printSingleResult(input, players, results); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package model; | ||
|
||
import java.util.Map; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.IntStream; | ||
import model.ladder.Ladder; | ||
import model.player.Position; | ||
import model.goal.Goal; | ||
import model.goal.Goals; | ||
import model.player.Player; | ||
import model.player.Players; | ||
|
||
public class LadderGame { | ||
|
||
private final Ladder ladder; | ||
|
||
public LadderGame(Ladder ladder) { | ||
this.ladder = ladder; | ||
} | ||
|
||
public Map<Player, Goal> play(Players players, Goals goals) { | ||
return IntStream.range(0, players.size()) | ||
.boxed() | ||
.collect(Collectors.toMap( | ||
players::getPlayerAt, | ||
index -> goals.getGoalAt(ladder.getGoalsPosition(new Position(index)).getValue()) | ||
)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package model.goal; | ||
|
||
public class Goal { | ||
|
||
private final int MAXINUM_GOAL_LENGTH = 5; | ||
private final String goal; | ||
|
||
public Goal(String goal) { | ||
validateGoal(goal); | ||
this.goal = goal; | ||
} | ||
|
||
private void validateGoal(String goal) { | ||
if (goal == null || goal.isBlank() || goal.length() > MAXINUM_GOAL_LENGTH) { | ||
throw new IllegalArgumentException("실행 결과는 1~5글자여야 합니다."); | ||
} | ||
|
||
} | ||
|
||
public String getGoal() { | ||
return goal; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package model.goal; | ||
|
||
import java.util.List; | ||
|
||
public class Goals { | ||
|
||
private final List<Goal> goals; | ||
|
||
public Goals(List<Goal> goals, int playerCount) { | ||
validateGoals(goals, playerCount); | ||
this.goals = List.copyOf(goals); | ||
|
||
} | ||
|
||
public static Goals from(List<String> rawGoals, int playerCount) { | ||
List<Goal> goalList = rawGoals.stream() | ||
.map(Goal::new) | ||
.toList(); | ||
return new Goals(goalList, playerCount); | ||
} | ||
|
||
private void validateGoals(List<Goal> goals, int playerCount) { | ||
if (goals.size() != playerCount) { | ||
throw new IllegalArgumentException("실행 결과 수와 참여자 수는 같아야 합니다."); | ||
} | ||
} | ||
|
||
public Goal getGoalAt(int index) { | ||
if (index < 0 || index >= goals.size()) { | ||
throw new IllegalArgumentException("유효하지 않은 인덱스입니다: " + index); | ||
} | ||
return goals.get(index); | ||
} | ||
|
||
public List<Goal> getGoals() { | ||
return List.copyOf(goals); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package model.ladder; | ||
|
||
import java.util.List; | ||
import model.player.Position; | ||
|
||
public enum Direction { | ||
|
||
// 현재 위치의 오른쪽에 사다리 연결이 있을 경우 오른쪽 이동 | ||
RIGHT( | ||
(position, points) -> position.getValue() < points.size() | ||
&& points.get(position.getValue()).isConnected(), | ||
Position::moveToRight | ||
), | ||
// 현재 위치의 왼쪽에 사다리 연결이 있을 경우 왼쪽 이동 | ||
LEFT( | ||
(position, points) -> position.getValue() > 0 | ||
&& points.get(position.getValue() - 1).isConnected(), | ||
Position::moveToLeft | ||
), | ||
// 그 외의 경우, 현재 위치에 그대로 머무름 | ||
STAY( | ||
(position, points) -> true, | ||
position -> position | ||
); | ||
|
||
private final MoveStrategy strategy; | ||
private final PositionChanger changer; | ||
|
||
Direction(MoveStrategy strategy, PositionChanger changer) { | ||
this.strategy = strategy; | ||
this.changer = changer; | ||
} | ||
|
||
public boolean isMovable(Position position, List<Point> points) { | ||
return strategy.isMovable(position, points); | ||
} | ||
|
||
public Position move(Position position) { | ||
return changer.move(position); | ||
} | ||
|
||
@FunctionalInterface | ||
interface MoveStrategy { // 지금 이 방향으로 움직일 수 있는가? | ||
boolean isMovable(Position position, List<Point> points); | ||
} | ||
|
||
@FunctionalInterface | ||
interface PositionChanger { // 이동했을 때 Position 어디인가? | ||
Position move(Position position); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package model.ladder; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.IntStream; | ||
import model.player.Players; | ||
import model.player.Position; | ||
import util.LadderGenerator; | ||
|
||
public class Ladder { | ||
|
||
private final LadderHeight height; | ||
private final List<Line> lines; | ||
|
||
public Ladder(LadderHeight height, List<Line> lines) { | ||
this.height = height; | ||
this.lines = lines; | ||
} | ||
|
||
public static Ladder of(Players players, LadderHeight height, LadderGenerator ladderGenerator) { | ||
List<Line> lines = new ArrayList<>(); | ||
Ladder ladder = new Ladder(height, lines); | ||
ladder.addLines(players.size(), ladderGenerator); | ||
return ladder; | ||
} | ||
|
||
private void addLines(int playersCount, LadderGenerator ladderGenerator) { | ||
for (int i = 0; i < getLadderHeight(); i++) { | ||
lines.add(Line.create(playersCount, ladderGenerator)); | ||
} | ||
if (isLadderNotConnected(playersCount)) { | ||
lines.clear(); | ||
addLines(playersCount, ladderGenerator); | ||
} | ||
} | ||
|
||
// Line이 최소 한 번 연결되었는지 검증 | ||
private boolean isLadderNotConnected(int playersCount) { | ||
Boolean[] isConnectedAt = getLadderConnectionStatus(playersCount); | ||
return Arrays.stream(isConnectedAt) | ||
.collect(Collectors.toSet()) | ||
.size() != 1; | ||
} | ||
|
||
// 전체 Line별 연결 상태 확인 | ||
private Boolean[] getLadderConnectionStatus(int playersCount) { | ||
int width = playersCount - 1; | ||
Boolean[] isConnectedAt = new Boolean[width]; | ||
Arrays.fill(isConnectedAt, false); | ||
lines.forEach(line -> getLineConnectionStatus(isConnectedAt, line)); | ||
return isConnectedAt; | ||
} | ||
|
||
// 특정 Line의 연결 상태 확인 | ||
private void getLineConnectionStatus(Boolean[] isConnectedAt, Line line) { | ||
IntStream.range(0, line.getLadderWidth()) | ||
.forEach(i -> getPointConnectionStatus(isConnectedAt, line, i)); | ||
} | ||
|
||
// 특정 Line의 특정 Point 연결 상태 확인 | ||
private void getPointConnectionStatus(Boolean[] isConnectedAt, Line line, int i) { | ||
if (line.getPoints().get(i).isConnected()) { | ||
isConnectedAt[i] = true; | ||
} | ||
} | ||
|
||
public int getLadderHeight() { | ||
return height.getLadderHeight(); | ||
} | ||
|
||
public int getLadderWidth(Players players) { | ||
return players.size(); | ||
} | ||
|
||
public Position getGoalsPosition(Position start) { | ||
Position current = start; | ||
for (Line line : lines) { | ||
current = line.move(current); | ||
} | ||
return current; | ||
} | ||
|
||
public List<Line> getLines() { | ||
return List.copyOf(lines); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이렇게 이동하는 것도 함수형 인터페이스를 활용해서 작성해 주셨군요!
수정해 보는게 쉽지 않으셨을텐데 고생하셨습니다!! 👏