diff --git a/README.md b/README.md index e078fd4..c7763c1 100644 --- a/README.md +++ b/README.md @@ -1 +1,13 @@ # javascript-racingcar-precourse + +# 기능구현 +1. 자동차 선수 구현 +2. 자동차 게임 실행 +3. 예외 처리 + +# 예외 처리 +1. 자동차 이름 + 1-1. 5자를 초과하는 경우 + 1-2. 이름이 공백인 경우 + 1-3. 중복되는는 이름이 존재하는 경우 +2. 이동 입력이 잘못된 경우 \ No newline at end of file diff --git a/src/App.js b/src/App.js index 091aa0a..48b84f0 100644 --- a/src/App.js +++ b/src/App.js @@ -1,5 +1,98 @@ +import { Console, Random } from "@woowacourse/mission-utils"; + +class Car { + constructor(name) { + if (name.length < 1) { + //이름은 최소 1자 이상입니다. + throw new Error("[ERROR]"); + } + if (name.length > 5) { + //이름은 5자 이하만 가능합니다. + throw new Error("[ERROR]"); + } + this.name = name; + this.position = 0; + } + move() { + const randomNumber = Random.pickNumberInRange(0, 9); + if (randomNumber >= 4) { + this.position++; + } + } + get nowPosition() { + return "-".repeat(this.position); + } +} + +class RacingGame { + constructor(carNames, counts) { + const nameArray = carNames.split(",").map((name) => name.trim()); + + const nameCheck = new Set(nameArray); + if (nameCheck.size !== nameArray.length) { + throw new Error( + //중복된 이름이 있습니다. 모든 자동차 이름은 고유해야 합니다. + "[ERROR]" + ); + } + + this.cars = nameArray.map((name) => new Car(name)); + this.counts = counts; + } + + playRound() { + this.cars.forEach((car) => { + car.move(); + Console.print(`${car.name} : ${car.nowPosition}`); + }); + } + + async delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + async gameStart() { + for (let i = 0; i < this.counts; i++) { + Console.print(`\n${i + 1}차 시도`); + this.playRound(); + await this.delay(1000); + } + } + + get winner() { + const maxPosition = Math.max(...this.cars.map((car) => car.position)); + const winners = this.cars.filter((car) => car.position === maxPosition); + return winners.map((winner) => winner.name).join(", "); + } +} + class App { - async run() {} + async run() { + try { + const cars = await Console.readLineAsync( + `경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분) \n` + ); + if (!cars) { + //이름이 입력되지 않았습니다. + throw new Error("[ERROR]"); + } + const inputCounts = await Console.readLineAsync( + "시도할 회수는 몇회인가요?" + ); + if (inputCounts < 1) { + //최소 1회 이상 시도해야 합니다. + throw new Error("[ERROR]"); + } + const counts = parseInt(inputCounts); + + const game = new RacingGame(cars, counts); + await game.gameStart(); + + Console.print("최종 우승자 : " + game.winner); + } catch (error) { + throw error; + } + } } export default App;