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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
# javascript-racingcar-precourse

#### 1. 입력
- 사용자에게 자동차 이름 입력받기
- 자동차 이름은 5자 이하
- 잘못된 입력 시 [ERROR] 메시지 출력 후 프로그램 종료

#### 2. 자동차 객체 생성
- 입력받은 이름으로 Car 객체 리스트 생성
- 각 자동차는 이름과 위치(position=0)를 가진다

#### 3. 게임 진행
- 시도 횟수만큼 반복하며 모든 자동차를 전진 또는 정지
- 전진 조건: Random.pickNumberInRange(0, 9) 값이 4 이상이면 position +1

#### 4. 실행 결과 출력
- 매 라운드마다 이름 : `-` 형식으로 각 자동차 상태 출력
- 라운드마다 `-` 추가

#### 5. 우승자 판별 및 출력
- 가장 멀리 간 자동차의 위치(position) 계산
- 공동 우승자 발생 시 쉼표(,)로 구분하여 출력
- 출력 예시: `최종 우승자 : pobi, jun`
24 changes: 22 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
import { Console } from "@woowacourse/mission-utils";
import InputView from "./view/InputView.js";
import OutputView from "./view/OutputView.js";
import CarRacing from "./service/CarRacing.js";

class App {
async run() {}
async run() {
try {
const names = await InputView.readCarNames();
const tryCount = await InputView.readTryCount();

const game = new CarRacing(names, tryCount);
const winners = await game.start();

OutputView.printWinners(winners);
} catch (error) {
Console.print(error.message);

//애플리케이션 종료 및 예외 처리 기능 테스트
throw error;
}
}
}

export default App;
export default App;
16 changes: 16 additions & 0 deletions src/model/Car.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Car {
constructor(name) {
this.name = name;
this.position = 0;
}

move() {
this.position += 1;
}

getPositionMark() {
return "-".repeat(this.position);
}
}

export default Car;
31 changes: 31 additions & 0 deletions src/service/CarRacing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Random } from "@woowacourse/mission-utils";
import OutputView from "../view/OutputView.js";
import Car from "../model/Car.js";

class CarRacing {
constructor(names, tryCount) {
this.cars = names.map((name) => new Car(name));
this.tryCount = tryCount;
}

async start() {
OutputView.printResultTitle();

for (let i = 0; i < this.tryCount; i++) {
this.cars.forEach((car) => {
const random = Random.pickNumberInRange(0, 9);
if (random >= 4) car.move();
});
OutputView.printRound(this.cars);
}

return this.getWinners();
}

getWinners() {
const maxPosition = Math.max(...this.cars.map((car) => car.position));
return this.cars.filter((car) => car.position === maxPosition).map((car) => car.name);
}
}

export default CarRacing;
20 changes: 20 additions & 0 deletions src/utils/Validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Validator {
static validateCarNames(names) {
if (!names || names.length === 0) {
throw new Error("[ERROR] 자동차 이름을 입력해야 합니다.");
}
names.forEach((name) => {
if (name.length === 0 || name.length > 5) {
throw new Error("[ERROR] 자동차 이름은 1~5자여야 합니다.");
}
});
}

static validateTryCount(value) {
if (isNaN(value) || Number(value) <= 0) {
throw new Error("[ERROR] 시도 횟수는 1 이상의 숫자여야 합니다.");
}
}
}

export default Validator;
21 changes: 21 additions & 0 deletions src/view/InputView.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Console } from "@woowacourse/mission-utils";
import Validator from "../utils/Validator.js";

const InputView = {
async readCarNames() {
const input = await Console.readLineAsync(
"경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)\n"
);
const names = input.split(",").map((name) => name.trim());
Validator.validateCarNames(names);
return names;
},

async readTryCount() {
const input = await Console.readLineAsync("시도할 횟수는 몇 회인가요?\n");
Validator.validateTryCount(input);
return Number(input);
},
};

export default InputView;
20 changes: 20 additions & 0 deletions src/view/OutputView.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Console } from "@woowacourse/mission-utils";

const OutputView = {
printResultTitle() {
Console.print("\n실행 결과");
},

printRound(cars) {
cars.forEach((car) => {
Console.print(`${car.name} : ${car.getPositionMark()}`);
});
Console.print(""); // 줄바꿈
},

printWinners(winners) {
Console.print(`최종 우승자 : ${winners.join(", ")}`);
},
};

export default OutputView;