Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#사다리게임

##1단계
- 4X4 크기의 사다리를 출력한다.
- 가로라인이 겹치지 않게 랜덤으로 줄을 긋는다.

##2단계
-사다리 넓이와 높이를 입력받아, 그 크기의 사다리를 출력한다.

##3단계
-0부터 인덱스 번호를 부여해 사다리 타고 난 후 결과를 출력하낟.

##4단계
-사다리 게임에 참여하는 사람에 이름을 최대 5글자까지 부여할 수 있다. 사다리를 출력할 때 사람 이름도 같이 출력한다.
사람 이름은 쉼표(,)를 기준으로 구분한다.
-개인별 이름을 입력하면 개인별 결과를 출력하고, "all"을 입력하면 전체 참여자의 실행 결과를 출력한다.

##5단계
-리팩토링
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id 'java'
id 'application'
}

group = 'cholog'
Expand Down
Empty file removed src/main/java/.gitkeep
Empty file.
7 changes: 7 additions & 0 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import controller.LadderController;

public class Main {
public static void main(String[] args) {
new LadderController().gameStart();
}
}
76 changes: 76 additions & 0 deletions src/main/java/controller/LadderController.java
Copy link

Choose a reason for hiding this comment

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

run 내부에 있는 로직을 분리해서 작성해보면, run 메서드 자체가 어떤 역할을 하는지 파악하기 쉬울 것 같아요!
오케스트레이션의 역할을 한다고 생각하며 접근해보시면 좋을 것 같네요!

Copy link
Author

Choose a reason for hiding this comment

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

오케스트레이션을 찾아보았는데 명확하게 정리된 블로그나 공식문서를 찾지 못해서요😅 제가 이해한 바로는 현재 run() 메서드가 입력 받기 → 유효성 검증 → 사다리 생성 → 출력 → 게임 진행 같은 전체 흐름을 직접 관리하고 있는데, 각 단계를 메서드로 분리하여 run()은 어떤 순서로 실행되는지만 보여주고 세부 구현은 각 메서드에 위임하는 것이 오케스트레이션 역할을 한다고 생각되는데 맞을까요??

Copy link

Choose a reason for hiding this comment

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

헛 오케스트레이션이 아니라 템플릿 메서드 패턴을 찾는게 올바른 방향인데 제가 잘못 설명을 드렸네요..😅 죄송해요

고은님이 적어주신

각 단계를 메서드로 분리하여 run()은 어떤 순서로 실행되는지만 보여주고 세부 구현은 각 메서드에 위임하는 것
이 내용으로 생각해주시면 될 것 같아요!

아래는 두 개념을 간단하게 정리해봤는데 앞으로 혼동을 느끼시지 않도록 간략하게만 적어봤어요!
참고해주시면 좋을 것 같습니다😄

  • 오케스트레이션: 여러 시스템·서비스의 자동화 태스크를 상위 워크플로로 묶어 의존성, 순서, 분기, 상태, 예외, 보상 트랜잭션까지 중앙에서 관리

  • 템플릿 메서드: 상위 메서드가 알고리즘의 골격과 단계 순서(run)를 정의하고, 각 단계 구현은 하위 메서드/클래스가 담당

Copy link
Author

Choose a reason for hiding this comment

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

넵 감사합니다 !!

Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package controller;

import model.Ladder;
import model.LadderFactory;
import model.LadderGame;
import model.LadderSize;
import model.Line;
import model.Participants;
import model.Results;
import model.BuildLine;
import view.InputView;
import view.OutputView;

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

public class LadderController {
private final LadderFactory factory = new LadderFactory();
private final OutputView outputView = new OutputView();
private final InputView inputView = new InputView();

public void gameStart() {
Participants participants = new Participants(inputView.inputParticipants());
int width = participants.size();

Results results;
while (true) {
results = new Results(inputView.inputResults());
if (participants.size() == results.size()) {
break;
}
outputView.printError("참여자 수와 결과 수가 일치하지 않습니다.");
}

int height;
while (true) {
height = inputView.heightSize();
if (height >= 1) {
break;
}
outputView.printError("높이는 1이상이어야 합니다.");
}

LadderSize size = new LadderSize(width, height);
Ladder ladder = factory.create(size, width);

List<String> lines = new ArrayList<>();
for (Line line : ladder.lines()) {
lines.add(BuildLine.build(line));
}

outputView.printLadder(participants.getNames(), lines, results.getValues());

LadderGame game = new LadderGame(ladder, participants.size());
gameResult(game, participants, results);
}

private void gameResult(LadderGame game, Participants participants, Results results) {
while (true) {
String queryName = inputView.inputQueryName();

if ("all".equals(queryName)) {
outputView.printAllResults(game.playAll(participants, results));
break;
}

if (!participants.contains(queryName)) {
outputView.printError("존재하지 않는 이름입니다.");
continue;
}

String result = game.getResult(queryName, participants, results);
outputView.printSingleResult(queryName, result);
}
}
}
20 changes: 20 additions & 0 deletions src/main/java/model/BuildLine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package model;

import java.util.Objects;

public final class BuildLine {

public static final int LADDER_LINE = 5;

public static String build(Line line) {
Objects.requireNonNull(line);
StringBuilder b = new StringBuilder();
for (Point p : line.points()) {
b.append("|");
String fill = p.isConnected() ? "-".repeat(LADDER_LINE) : " ".repeat(LADDER_LINE);
b.append(fill);
}
b.append("|");
return b.toString();
}
}
16 changes: 16 additions & 0 deletions src/main/java/model/Ladder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package model;

import java.util.List;
import java.util.Objects;

public class Ladder {
private final List<Line> lines;

public Ladder(List<Line> lines) {
this.lines = Objects.requireNonNull(lines);
}

public List<Line> lines() {
return lines;
}
}
33 changes: 33 additions & 0 deletions src/main/java/model/LadderFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package model;

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

public class LadderFactory {
private final Random random = new Random();

public Ladder create(LadderSize size, int width) {
List<Line> lines = new ArrayList<>();
for (int i = 0; i < size.height(); i++) {
lines.add(createLine(width));
}
return new Ladder(lines);
}

private Line createLine(int width) {
int pointsCount = width - 1;
List<Point> points = new ArrayList<>();
boolean prevConnected = false;

for (int i = 0; i < pointsCount; i++) {
boolean connect = false;
if (!prevConnected) {
connect = random.nextBoolean();
}
points.add(new Point(connect));
prevConnected = connect;
}
return new Line(points);
}
}
53 changes: 53 additions & 0 deletions src/main/java/model/LadderGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package model;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class LadderGame {
private final Ladder ladder;

public LadderGame(Ladder ladder, int width) {
this.ladder = ladder;
}

public Map<String, String> playAll(Participants participants, Results results) {
Map<String, String> allResults = new LinkedHashMap<>();
for (int i = 0; i < participants.size(); i++) {
int finalPosition = play(i);
allResults.put(participants.get(i), results.get(finalPosition));
}
return allResults;
}

public String getResult(String name, Participants participants, Results results) {
int startIndex = participants.indexOf(name);
int finalPosition = play(startIndex);
return results.get(finalPosition);
}

public int play(int startPosition) {
int currentPosition = startPosition;
List<Line> lines = ladder.lines();

for (Line line : lines) {
currentPosition = moveOnLine(currentPosition, line);
}

return currentPosition;
}

private int moveOnLine(int position, Line line) {
List<Point> points = line.points();

if (position > 0 && points.get(position - 1).isConnected()) {
return position - 1;
}

if (position < points.size() && points.get(position).isConnected()) {
return position + 1;
}

return position;
}
}
22 changes: 22 additions & 0 deletions src/main/java/model/LadderSize.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package model;

public class LadderSize {
private final int height;
private final int width;

public LadderSize(int width, int height) {
validateHeight(height);
this.height = height;
this.width = width;
}

private void validateHeight(int height) {
if (height <= 0) {
throw new IllegalArgumentException("사다리 높이는 1 이상이어야 합니다.");
}
}

public int height() {
return height;
}
}
16 changes: 16 additions & 0 deletions src/main/java/model/Line.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package model;

import java.util.List;
import java.util.Objects;

public class Line {
private final List<Point> points;

public Line(List<Point> points) {
this.points = Objects.requireNonNull(points);
}

public List<Point> points() {
return points;
}
}
39 changes: 39 additions & 0 deletions src/main/java/model/Participants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package model;

import java.util.List;
import java.util.Objects;

public class Participants {
private final List<String> names;

public Participants(List<String> names) {
validateNames(names);
this.names = Objects.requireNonNull(names);
}

private void validateNames(List<String> names) {
if (names == null || names.isEmpty()) {
throw new IllegalArgumentException("참여자는 최소 1명 이상이어야 합니다.");
}
}

public int size() {
return names.size();
}

public boolean contains(String name) {
return names.contains(name);
}

public int indexOf(String name) {
return names.indexOf(name);
}

public String get(int index) {
return names.get(index);
}

public List<String> getNames() {
return names;
}
}
13 changes: 13 additions & 0 deletions src/main/java/model/Point.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package model;

public class Point {
private final boolean connected;

public Point(boolean connected) {
this.connected = connected;
}

public boolean isConnected() {
return connected;
}
}
25 changes: 25 additions & 0 deletions src/main/java/model/Results.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package model;


import java.util.List;
import java.util.Objects;

public class Results {
private final List<String> values;

public Results(List<String> values) {
this.values = Objects.requireNonNull(values);
}

public int size() {
return values.size();
}

public String get(int index) {
return values.get(index);
}

public List<String> getValues() {
return values;
}
}
34 changes: 34 additions & 0 deletions src/main/java/view/InputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package view;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class InputView {
Scanner scanner = new Scanner(System.in);

public List<String> inputParticipants() {
System.out.println("참여할 사람 이름을 입력하세요. (이름은 쉼표(,)로 구분하세요)");
String input = scanner.nextLine();
return Arrays.asList(input.split(",\\s*"));
}

public List<String> inputResults() {
System.out.println("실행 결과를 입력하세요. (결과는 쉼표(,)로 구분하세요)");
String input = scanner.nextLine();
return Arrays.asList(input.split(",\\s*"));
}

public int heightSize() {
System.out.println("최대 사다리 높이는 몇 개인가요?");
int height = scanner.nextInt();
scanner.nextLine();
return height;
}

public String inputQueryName() {
System.out.println();
System.out.println("결과를 보고 싶은 사람은?--all을 입력하면 전체 결과를 확인하고 종료됩니다.");
return scanner.nextLine().trim();
}
}
Loading