From 74784ac2a1aca55a491c59e3ffb0be8d22275557 Mon Sep 17 00:00:00 2001 From: BoRamSon <> Date: Wed, 1 Nov 2023 23:29:44 +0900 Subject: [PATCH] =?UTF-8?q?Add:=20=EB=AA=A8=EB=93=A0=20=EA=B8=B0=EB=8A=A5?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80,=20Car.js=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/App.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++-- src/Car.js | 20 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 src/Car.js diff --git a/src/App.js b/src/App.js index c38b30d5b..7be516dbf 100644 --- a/src/App.js +++ b/src/App.js @@ -1,5 +1,52 @@ +import Car from './Car.js'; class App { - async play() {} + async play() { + try { + const carNames = await this.inputCarNames(); + const round = await this.inputRound(); + + const cars = carNames.map((name) => new Car(name)); + + console.log('\n실행 결과'); + for (let i = 0; i < round; i++) { + cars.forEach((car) => car.move()); + this.printStatus(cars); + console.log(); + } + + const winners = this.getWinners(cars); + this.printWinners(winners); + } catch (error) { + console.error(error.message); + } + } + + async inputCarNames() { + const input = await Console.readLineAsync( + '경주할 자동차 이름을 입력하세요.\n' + ); + return input.split(',').map((name) => name.trim()); + } + + async inputRound() { + const input = await Console.readLineAsync('시도할 횟수는 몇 회인가요?\n'); + return Number(input); + } + + printStatus(cars) { + cars.forEach((car) => { + console.log(`${car.name} : ${'-'.repeat(car.position)}`); + }); + } + + getWinners(cars) { + const maxPosition = Math.max(...cars.map((car) => car.position)); + return cars.filter((car) => car.position === maxPosition).map((car) => car.name); + } + + printWinners(winners) { + console.log(`최종 우승자 : ${winners.join(', ')}`); + } } -export default App; +export default App; \ No newline at end of file diff --git a/src/Car.js b/src/Car.js new file mode 100644 index 000000000..82f2a4849 --- /dev/null +++ b/src/Car.js @@ -0,0 +1,20 @@ +export default class Car { + constructor(name) { + this.validateName(name); + this.name = name; + this.position = 0; + } + + validateName(name) { + if (name.length === 0 || name.length > 5) { + throw new Error('[ERROR] 자동차 이름은 1자 이상, 5자 이하만 가능합니다.'); + } + } + + move() { + const randomNumber = Random.pickNumberInRange(0, 9); + if (randomNumber >= 4) { + this.position++; + } + } + } \ No newline at end of file