code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋Š” ํ•œ ๊ฐ€์ง€ ์ฑ…์ž„๋งŒ ๊ฐ–๋„๋ก ํ•˜๋Š” ๊ฒŒ ์ข‹์•„์š”! randomNumber ํ•จ์ˆ˜์—์„œ๋Š” ์ค‘๋ณต๋˜์ง€ ์•Š๋Š” ๋‚œ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ์ธ๋ฐ, randomNumber ๋ณ€์ˆ˜์— ๋žœ๋ค๊ฐ’์„ ๋„ฃ๋Š” ํ–‰์œ„๋Š” ๊ทธ ์ฑ…์ž„๊ณผ๋Š” ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”. `let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER);` ๋ฅผ ๋‹ค๋ฅธ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?? ๐Ÿ˜„ [์ฐธ๊ณ ์ž๋ฃŒ](https://inpa.tistory.com/entry/OOP-%F0%9F%92%A0-%EC%95%84%EC%A3%BC-%EC%89%BD%EA%B2%8C-%EC%9D%B4%ED%95%B4%ED%95%98%EB%8A%94-SRP-%EB%8B%A8%EC%9D%BC-%EC%B1%85%EC%9E%84-%EC%9B%90%EC%B9%99)
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
while๋ฌธ ํ˜ธ์ถœ ์ด์ „์— randomNumber์— ์œ ์˜๋ฏธํ•œ ๊ฐ’์„ ๋„ฃ๊ธฐ ์œ„ํ•ด์„œ ๋žœ๋ค๊ฐ’์„ ์ƒ์„ฑํ•˜์—ฌ ๋ฏธ๋ฆฌ ๋„ฃ์–ด์ฃผ๊ณ  while์„ ํ˜ธ์ถœํ•œ ๊ฒƒ ๊ฐ™๋„ค์š”. ํ•˜์ง€๋งŒ ์ด๋ ‡๊ฒŒ ๋˜๋ฉด randomNumber์˜ ์ดˆ๊ธฐํ™”์‹์— ๋Œ€ํ•ด์„œ ์ฝ”๋“œ ์ค‘๋ณต์ด ์ผ์–ด๋‚˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค! do .. while ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ์ฝ”๋“œ ์ค‘๋ณต์„ ์—†์•จ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”?? ๐Ÿ˜
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
newRow๋Š” HTML ์š”์†Œ์ธ ๊ฒƒ ๊ฐ™์€๋ฐ $๋ฅผ ๋ถ™์—ฌ์ฃผ๋Š”๊ฒŒ ๋งž์ง€ ์•Š์„๊นŒ์š”?? ๐Ÿค” ์ €๋„ ์ด๋ถ€๋ถ„์€ ํ™•์‹คํ•˜์ง€ ์•Š์œผ๋‹ˆ ์ง์ ‘ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! [์ฐธ๊ณ ์ž๋ฃŒ](https://choseongho93.tistory.com/213)
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
์ด ๋ถ€๋ถ„๋“ค๋„ HTML ์š”์†Œ์ธ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
์ฝ”๋“œ์˜ ๊ฐ„๊ฒฐํ•จ์„ ์œ„ํ•ด ์ข‹์€ ๋ฐฉ๋ฒ•์ด ๋  ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ํ•œ ํ–‰์—์„œ๋Š” ํ•˜๋‚˜์˜ ๋ณ€๊ฒฝ๋งŒ์ด ์ผ์–ด๋‚˜์•ผ ํ•œ๋‹ค๋Š” ๋ง์„ ๋“ค์€ ์ ์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ![image](https://user-images.githubusercontent.com/21010656/232725189-43544081-34d5-4f12-9bcb-b13548a0c97d.png)
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
๊ฒฝ๊ณ ๋ฌธ์˜ ๋‚ด์šฉ์ด ๊ฒน์น˜๋Š”๋ฐ, ๊ฒฝ๊ณ ๋ฌธ์„ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜๊ฑฐ๋‚˜ ๊ฒฝ๊ณ ๋ฌธ ๋‚ด์šฉ์„ ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด๋กœ ์ •์˜ํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜€
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
๋ณ€๊ฒฝํ•  innerText ๋‚ด์šฉ์€ ๋ณ€์ˆ˜๋ฅผ ๊ฐ–๋Š” ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”?? ๐Ÿ˜ƒ [์ฐธ๊ณ ์ž๋ฃŒ](https://www.delftstack.com/ko/howto/javascript/javascript-variable-in-string/)
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
``` score[0] -> ball score[1] -> strike ``` ์ธ ๊ฒƒ ๊ฐ™์€๋ฐ, ์ด๋ ‡๊ฒŒ ๋งค์ง ๋„˜๋ฒ„๋ฅผ ํ†ตํ•ด ์ž‘์„ฑํ•˜๊ฒŒ ๋˜๋ฉด ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์ด ์ฝ”๋“œ๋ฅผ ๋ณด์•˜์„ ๋•Œ ์ธ๋ฑ์Šค ๋ณ„ ์—ญํ• ์— ๋Œ€ํ•ด ํ•ด์„ํ•˜๊ธฐ ํž˜๋“ค ๊ฒƒ ๊ฐ™์•„์š”! ์ธ๋ฑ์Šค์ธ 0๊ณผ 1์„ ๊ฐ๊ฐ ์ƒ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
![image](https://user-images.githubusercontent.com/21010656/232728861-7e7a068f-0d8d-4eaa-b1b0-ce69689ffdc0.png) ๊นƒํ—ˆ๋ธŒ์—์„œ `No newline at end of file`๋ผ๋Š” ์—๋Ÿฌ๊ฐ€ ๋‚˜ํƒ€๋‚˜๋„ค์š”! ์ด๋Ÿฐ ์—๋Ÿฌ๋Š” ์™œ ๋‚˜ํƒ€๋‚˜๋Š” ๊ฑธ๊นŒ์š”?? [์ฐธ๊ณ ์ž๋ฃŒ](https://velog.io/@jesop/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%BD%94%EB%93%9C-%EB%A7%88%EC%A7%80%EB%A7%89%EC%97%90-%EB%B9%88-%EC%A4%84-%EC%82%BD%EC%9E%85%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0)
@@ -0,0 +1,29 @@ +.container{ + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; +} + +.btn-group, .input-content, .table-content{ + display: flex; + justify-content: center; + align-items: center; + margin: 10px; +} + +table{ + width: 500px; + border: 1px solid black; +} + +th, td{ + border: 1px solid black; + text-align: center; +} + +div input{ + margin-left: 5px; + margin-right: 5px; +} \ No newline at end of file
Unknown
์˜ค ์ด๋Ÿฐ ๋ฐฉ๋ฒ•๋„ ์žˆ๊ตฐ์š”...!! ๐Ÿ˜ฎ
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
๋„ต ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Šฆ๊ฒŒ ๋ฆฌ๋ทฐ๋‹ฌ์•„์„œ ์ •๋ง ์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค...
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
์•„ํ•˜ ์•Œ๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
์ฐธ๊ณ ์ž๋ฃŒ ์ž˜ ์ฝ์–ด๋ดค์Šต๋‹ˆ๋‹ค! SRP์— ๋Œ€ํ•ด ์ข€ ๋” ๊ณต๋ถ€๊ฐ€ ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™๋„ค์š”. ์ฐธ๊ณ ์ž๋ฃŒ๋ฅผ ์ฝ์œผ๋ฉด์„œ ์ข€ ํ—ท๊ฐˆ๋ ธ๋˜ ๋ถ€๋ถ„์ด ์žˆ๋Š”๋ฐ "์‘์ง‘๋„๋ฅผ ๋†’๊ฒŒ, ๊ฒฐํ•ฉ๋„๋Š” ๋‚ฎ๊ฒŒ" ๋ผ๋Š” ๋ฌธ์žฅ์—์„œ ์‘์ง‘๋„์™€ ๊ฒฐํ•ฉ๋„์˜ ์ฐจ์ด์— ๋Œ€ํ•ด ์กฐ๊ธˆ ํ—ท๊ฐˆ๋ฆฝ๋‹ˆ๋‹ค. ์‘์ง‘๋„๋Š” ํ•จ์ˆ˜ ์•ˆ์— ๊ตฌ์„ฑ์š”์†Œ๋“ค์˜ ์—ฐ๊ด€๋œ ์ •๋„, ๊ฒฐํ•ฉ๋„๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ํ•จ์ˆ˜๊ฐ„์˜ ์—ฐ๊ด€๋œ ์ •๋„๋กœ ํ•ด์„ํ–ˆ๋Š”๋ฐ ์ด๊ฒŒ ๋งž๋Š” ํ•ด์„์ธ์ง€ ์•Œ๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
function getRandomNumber()๋กœ ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์ค‘๋ณต์„ ํ”ผํ•˜๋„๋ก ์ˆ˜์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
์ฃผ๋กœ ๋งŽ์€ ์‚ฌ๋žŒ๋“ค์ด ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š”์ง€ ์•„๋‹ˆ๋ฉด ์ œ๊ฐ€ ํ•„์š”๋กœ ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์จ์•ผ ํ•˜๋Š”๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ์˜ˆ๋ฅผ ๋“ค์–ด existingNumber๋Š” ๋ฐฐ์—ด์ด๊ธฐ ๋•Œ๋ฌธ์— includesํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ randomNumber๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€ ์ฐพ์•˜๋Š”๋ฐ, ๋งŒ์•ฝ ์ด ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์ด ์ž์ฃผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„์„œ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํ•ด์•ผ ํ•˜๋Š”์ง€ ๋ฌป๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
do .. while ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ์ค‘๋ณต ์—†์• ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค!! do .. while ๋ฌธ์„ ์ƒ๊ฐ ๋ชปํ–ˆ๋„ค์š”..
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
$๋ฅผ ๋ถ™์ด๋Š” ๊ฒƒ์ด ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,96 @@ +const MAX_RANDOM_NUMBER = 9; +const MIN_RANDOM_NUMBER = 1; +const $inputNumber = document.querySelector('.input-number'); +const $gameTable = document.querySelector(".game-table"); + +let answer; + +function inputDigit(numberOfDigit){ + $gameTable.innerHTML = "<tr><td>์ˆœ์„œ</td><td>์ˆซ์ž</td><td>๊ฒฐ๊ณผ</td></tr>"; + if(numberOfDigit === "3์ž๋ฆฌ"){ + answer = randomNumber(3); + } else if(numberOfDigit === "4์ž๋ฆฌ"){ + answer = randomNumber(4); + } else if(numberOfDigit === "5์ž๋ฆฌ"){ + answer = randomNumber(5); + } +} + +function randomNumber(numberOfDigit){ + let result = 0; + let existingNumbers = []; + for (step = 0; step < numberOfDigit; step++) { + let randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + while (existingNumbers.includes(randomNumber)){ + randomNumber = Math.floor(Math.random() * (MAX_RANDOM_NUMBER - MIN_RANDOM_NUMBER) + MIN_RANDOM_NUMBER); + } + existingNumbers.push(randomNumber); + } + + let weight = 1; + for(j = 0; j < numberOfDigit; j++){ + result += existingNumbers[j] * weight; + weight *= 10; + } + + console.log(result); + return result; +} + +let index = 1; +function addValue(){ + const newRow = $gameTable.insertRow(); + const pitchResult = checkBallAndStrike(answer); + const convertedAnswer = answer.toString(); + + let isValid = 0; + if($inputNumber.value.length === convertedAnswer.length){ + for(let i = 0; i < $inputNumber.value.length; i++){ + for(let j = 0; j < $inputNumber.value.length; j++){ + if(i !== j){ + if($inputNumber.value[i] === $inputNumber.value[j]){ + isValid = 1; + } + } + } + } + if(isValid === 0){ + const turn = newRow.insertCell(0); + const number = newRow.insertCell(1); + const result = newRow.insertCell(2); + turn.innerText = `${index++}`; + number.innerText = `${$inputNumber.value}` + if(pitchResult[1] === convertedAnswer.length){ + result.innerText = `O.K.`; + } else{ + result.innerText = `B: ${pitchResult[0]}, S: ${pitchResult[1]}`; + } + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + + } else{ + alert("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + +} + +function checkBallAndStrike(answer){ + const convertedAnswer = answer.toString(); + const convertedInputNumber = $inputNumber.value.toString(); + let k = 0; + let score = [0, 0]; + while(k < convertedAnswer.length){ + if(convertedAnswer[k] === convertedInputNumber[k]){ + score[1] += 1; + } else{ + for(let item of convertedAnswer){ + if(item === convertedInputNumber[k]){ + score[0] += 1; + } + } + } + k += 1; + } + return score; +} \ No newline at end of file
JavaScript
๊ทธ๋Ÿฌ๋ฉด index๊ฐ’์„ turn์— ๋„ฃ๋Š” ๊ฒƒ, index๊ฐ€ 1์”ฉ ์ฆ๊ฐ€ ํ•˜๋Š” ๊ฒƒ ๋‘ ๊ฐœ๋ฅผ ๋‚˜๋ˆ„๋„๋ก ์ˆ˜์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,42 @@ +package racingcar.domain; + +import racingcar.exception.CarNameLengthException; + +public class Car { + + private static final int CAR_NAME_LENGTH = 5; + private static final int MOVABLE_MIN_NUMBER = 4; + private final String name; + private int position = 0; + + public Car(String name) { + validate(name); + this.name = name; + } + + private void validate(String name) { + validateLength(name); + } + + private void validateLength(String name) { + if (name.length() > CAR_NAME_LENGTH) { + throw new CarNameLengthException(); + } + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + final int number = carMoveNumberGenerator.generate(); + + if (number >= MOVABLE_MIN_NUMBER) { + position++; + } + } + + public String getName() { + return name; + } + + public int getPosition() { + return position; + } +}
Java
์ปจ๋ฒค์…˜์— ๋”ฐ๋ผ์„œ ์ƒ์ˆ˜์™€ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋ฅผ ์ƒˆ ์ค„๋กœ ๊ตฌ๋ถ„ํ•ด์ฃผ์‹œ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!!
@@ -0,0 +1,71 @@ +package racingcar.domain; + +import racingcar.exception.CarsDuplicatedNameException; +import racingcar.exception.CarsMaxScoreBlankException; + +import java.util.*; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DELIMITER = ","; + private static final String DUPLICATED_DELIMITER_REGEX = ",+"; + private final List<Car> cars; + + private Cars(List<Car> cars) { + this.cars = Collections.unmodifiableList(cars); + } + + public static Cars createCarNameByWord(String input) { + List<Car> cars = new ArrayList<>(); + String[] words = divideWord(input); + validate(words); + + for (String carName : words) { + cars.add(new Car(carName)); + } + return new Cars(cars); + } + + private static void validate(String[] words) { + validateDuplicatedWord(words); + } + + private static void validateDuplicatedWord(String[] words) { + Set<String> uniqueWord = new HashSet<>(); + for (String word : words) { + if (!uniqueWord.add(word)) { + throw new CarsDuplicatedNameException(); + } + } + } + + private static String[] divideWord(String word) { + return word.replaceAll(DUPLICATED_DELIMITER_REGEX, DELIMITER).split(DELIMITER); + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + for (Car car : cars) { + car.move(carMoveNumberGenerator); + } + } + + public Winner findWinner() { + int maxScore = findMaxScore(); + return new Winner(cars.stream() + .filter(car -> (car.getPosition() == maxScore)) + .map(Car::getName) + .collect(Collectors.toList())); + } + + private int findMaxScore() { + return cars.stream() + .max(Comparator.comparingInt(Car::getPosition)) + .map(Car::getPosition) + .orElseThrow(CarsMaxScoreBlankException::new); + } + + public List<Car> getCars() { + return cars; + } +}
Java
๋ถˆ๋ณ€ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค ๋•Œ ์ƒ์„ฑ์ž ๋‹จ๊ณ„์—์„œ๋Š” ๋ฐฉ์–ด์  ๋ณต์‚ฌ๋ฅผ ๊ณ ๋ คํ•ด์ฃผ์‹œ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!! - [๋ฐฉ์–ด์  ๋ณต์‚ฌ์™€ Unmodifiable Collections](https://tecoble.techcourse.co.kr/post/2021-04-26-defensive-copy-vs-unmodifiable/)
@@ -0,0 +1,16 @@ +package racingcar.domain; + +import java.util.List; + +public class Winner { + + private final List<String> winner; + + public Winner(List<String> winner) { + this.winner = winner; + } + + public List<String> getWinner() { + return winner; + } +}
Java
๋ฆฌ์ŠคํŠธ์˜ ๋„ค์ด๋ฐ์€ ๋ณต์ˆ˜ํ˜•์ด ๋” ์ ์ ˆํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! `Winner` ํด๋ž˜์Šค ์ž์ฒด๋„ ์Šน๋ฆฌ์ž๋“ค์˜ ์ด๋ฆ„์„ ๋‹ด๊ณ ์žˆ๋Š” ์ผ๊ธ‰ ์ปฌ๋ ‰์…˜์ด๊ธฐ ๋•Œ๋ฌธ์— `Winners` ๋ผ๋Š” ๋„ค์ด๋ฐ์„ ๋” ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,54 @@ +package racingcar.view; + +import racingcar.domain.Car; +import racingcar.domain.Cars; +import racingcar.domain.Winner; + +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class OutputView { + + private static final String MESSAGE_INPUT_CAR_NAME = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String MESSAGE_INPUT_TRY = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + private static final String MESSAGE_RESULT = "์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String MOVE_MARK = "-"; + private static final String JOIN_NAME_AND_POSITION = " : "; + private static final String WINNER_DELIMITER = ","; + private static final String MESSAGE_WINNER_PREFIX = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String MESSAGE_WINNER_SUFFIX = ""; + + public void printInputCarName() { + System.out.println(MESSAGE_INPUT_CAR_NAME); + } + + public void printExceptionMessage(IllegalArgumentException exceptionMessage) { + System.out.println(exceptionMessage.getMessage()); + } + + public void printInputTry() { + System.out.println(MESSAGE_INPUT_TRY); + } + + public void printBlank() { + System.out.println(); + } + + public void printResult(Cars cars) { + System.out.println(MESSAGE_RESULT); + for(Car car : cars.getCars()){ + System.out.println(car.getName() + JOIN_NAME_AND_POSITION + convertMoveMark(car.getPosition())); + } + printBlank(); + } + + private String convertMoveMark(int position) { + return Stream.generate(() -> MOVE_MARK).limit(position).collect(Collectors.joining()); + } + + public void printWinner(Winner winner) { + String message = winner.getWinner().stream() + .collect(Collectors.joining(WINNER_DELIMITER, MESSAGE_WINNER_PREFIX, MESSAGE_WINNER_SUFFIX)); + System.out.println(message); + } +}
Java
String์—์„œ ์ œ๊ณตํ•˜๋Š” `repeat()` ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด๋ณด์‹œ๋Š” ๊ฒƒ๋„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,71 @@ +package racingcar.domain; + +import racingcar.exception.CarsDuplicatedNameException; +import racingcar.exception.CarsMaxScoreBlankException; + +import java.util.*; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DELIMITER = ","; + private static final String DUPLICATED_DELIMITER_REGEX = ",+"; + private final List<Car> cars; + + private Cars(List<Car> cars) { + this.cars = Collections.unmodifiableList(cars); + } + + public static Cars createCarNameByWord(String input) { + List<Car> cars = new ArrayList<>(); + String[] words = divideWord(input); + validate(words); + + for (String carName : words) { + cars.add(new Car(carName)); + } + return new Cars(cars); + } + + private static void validate(String[] words) { + validateDuplicatedWord(words); + } + + private static void validateDuplicatedWord(String[] words) { + Set<String> uniqueWord = new HashSet<>(); + for (String word : words) { + if (!uniqueWord.add(word)) { + throw new CarsDuplicatedNameException(); + } + } + } + + private static String[] divideWord(String word) { + return word.replaceAll(DUPLICATED_DELIMITER_REGEX, DELIMITER).split(DELIMITER); + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + for (Car car : cars) { + car.move(carMoveNumberGenerator); + } + } + + public Winner findWinner() { + int maxScore = findMaxScore(); + return new Winner(cars.stream() + .filter(car -> (car.getPosition() == maxScore)) + .map(Car::getName) + .collect(Collectors.toList())); + } + + private int findMaxScore() { + return cars.stream() + .max(Comparator.comparingInt(Car::getPosition)) + .map(Car::getPosition) + .orElseThrow(CarsMaxScoreBlankException::new); + } + + public List<Car> getCars() { + return cars; + } +}
Java
`CarMoveNumberGenerator` ๋ฅผ `Car` ๊ฐ์ฒด๊นŒ์ง€ ๋„˜๊ฒจ์ฃผ์ง€ ์•Š์•„๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๊ทธ๋Ÿฌ๋ฉด `car.move()` ๋ฉ”์„œ๋“œ๋ฅผ ํ…Œ์ŠคํŠธํ•˜๊ธฐ๋„ ํ›จ์”ฌ ๊ฐ„ํŽธํ•ด์งˆ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public class RacingCarGame { + + private final Cars cars; + + public RacingCarGame(Cars cars) { + this.cars = cars; + } + + public void move() { + cars.move(new CarRandomMoveNumberGenerator()); + } + + public Winner findWinner() { + return cars.findWinner(); + } + + public Cars getCars() { + return cars; + } +}
Java
`RacingCarGame` ํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ๋“ค์ด ๋Œ€๋ถ€๋ถ„ `Cars` ํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์šฉ๋„๋กœ๋งŒ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ ๊ฐ™์•„์š”! `RacingCarGame` ํด๋ž˜์Šค๊ฐ€ ์ •๋ง ํ•„์š”ํ•œ์ง€, ์•„๋‹ˆ๋ฉด ์–ด๋–ค ์‹์œผ๋กœ `RacingCarGame` ๋งŒ์˜ ์ƒˆ๋กœ์šด ์ฑ…์ž„์„ ๋ถ€์—ฌํ•  ์ˆ˜ ์žˆ์„ ์ง€ ์ƒ๊ฐํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!!
@@ -0,0 +1,47 @@ +package racingcar.domain; + +import racingcar.exception.TryCommandNumberException; +import racingcar.exception.TryCommandRangeException; + +public class TryCommand { + + private static final int MIN_TRY = 1; + private static final int MAX_TRY = 100000; + private int tryCount; + + private TryCommand(int tryCount) { + this.tryCount = tryCount; + } + + public static TryCommand createTryCommandByString(String input) { + int number = convertInt(input); + validate(number); + return new TryCommand(number); + } + + private static void validate(int number) { + validateRange(number); + } + + private static void validateRange(int number) { + if(number < MIN_TRY || number > MAX_TRY) { + throw new TryCommandRangeException(MIN_TRY, MAX_TRY); + } + } + + private static int convertInt(String input) { + try{ + return Integer.parseInt(input); + }catch (NumberFormatException exception) { + throw new TryCommandNumberException(); + } + } + + public boolean tryMove() { + if(tryCount > 0) { + tryCount--; + return true; + } + return false; + } +}
Java
๊ฐ’ ๊ฐ์ฒด์˜ ๋‚ด๋ถ€ ์ƒํƒœ๋ฅผ `final` ๋กœ ์„ ์–ธํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋”๋ผ๊ตฌ์š”! ์ฐธ๊ณ ํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! - [Value Object, Reference Obejct](http://aeternum.egloos.com/v/1111257)
@@ -0,0 +1,71 @@ +package racingcar.domain; + +import racingcar.exception.CarsDuplicatedNameException; +import racingcar.exception.CarsMaxScoreBlankException; + +import java.util.*; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DELIMITER = ","; + private static final String DUPLICATED_DELIMITER_REGEX = ",+"; + private final List<Car> cars; + + private Cars(List<Car> cars) { + this.cars = Collections.unmodifiableList(cars); + } + + public static Cars createCarNameByWord(String input) { + List<Car> cars = new ArrayList<>(); + String[] words = divideWord(input); + validate(words); + + for (String carName : words) { + cars.add(new Car(carName)); + } + return new Cars(cars); + } + + private static void validate(String[] words) { + validateDuplicatedWord(words); + } + + private static void validateDuplicatedWord(String[] words) { + Set<String> uniqueWord = new HashSet<>(); + for (String word : words) { + if (!uniqueWord.add(word)) { + throw new CarsDuplicatedNameException(); + } + } + } + + private static String[] divideWord(String word) { + return word.replaceAll(DUPLICATED_DELIMITER_REGEX, DELIMITER).split(DELIMITER); + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + for (Car car : cars) { + car.move(carMoveNumberGenerator); + } + } + + public Winner findWinner() { + int maxScore = findMaxScore(); + return new Winner(cars.stream() + .filter(car -> (car.getPosition() == maxScore)) + .map(Car::getName) + .collect(Collectors.toList())); + } + + private int findMaxScore() { + return cars.stream() + .max(Comparator.comparingInt(Car::getPosition)) + .map(Car::getPosition) + .orElseThrow(CarsMaxScoreBlankException::new); + } + + public List<Car> getCars() { + return cars; + } +}
Java
์ŠคํŠธ๋ฆผ์œผ๋กœ ๋กœ์ง์„ ๋ฐ”๊พธ์‹œ๋ฉด ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ์„ ์–ธํ•˜์ง€ ์•Š๊ณ  ๋” ๊น”๋”ํ•˜๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,10 @@ +package racingcar.exception; + +public class CarNameLengthException extends IllegalArgumentException{ + + private static final String EXCEPTION_MESSAGE_CAR_NAME_LENGTH = "[ERROR] ์ž๋™์ฐจ์ด๋ฆ„์€ 5๊ธ€์ž ์ดํ•˜์ž…๋‹ˆ๋‹ค"; + + public CarNameLengthException() { + super(EXCEPTION_MESSAGE_CAR_NAME_LENGTH); + } +}
Java
ํŠน๋ณ„ํžˆ ์ปค์Šคํ…€ ์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?? ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,42 @@ +package racingcar.domain; + +import racingcar.exception.CarNameLengthException; + +public class Car { + + private static final int CAR_NAME_LENGTH = 5; + private static final int MOVABLE_MIN_NUMBER = 4; + private final String name; + private int position = 0; + + public Car(String name) { + validate(name); + this.name = name; + } + + private void validate(String name) { + validateLength(name); + } + + private void validateLength(String name) { + if (name.length() > CAR_NAME_LENGTH) { + throw new CarNameLengthException(); + } + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + final int number = carMoveNumberGenerator.generate(); + + if (number >= MOVABLE_MIN_NUMBER) { + position++; + } + } + + public String getName() { + return name; + } + + public int getPosition() { + return position; + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋†“์น˜๊ณ ์žˆ๋˜ ๋ถ€๋ถ„์ด๋„ค์š”..
@@ -0,0 +1,71 @@ +package racingcar.domain; + +import racingcar.exception.CarsDuplicatedNameException; +import racingcar.exception.CarsMaxScoreBlankException; + +import java.util.*; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DELIMITER = ","; + private static final String DUPLICATED_DELIMITER_REGEX = ",+"; + private final List<Car> cars; + + private Cars(List<Car> cars) { + this.cars = Collections.unmodifiableList(cars); + } + + public static Cars createCarNameByWord(String input) { + List<Car> cars = new ArrayList<>(); + String[] words = divideWord(input); + validate(words); + + for (String carName : words) { + cars.add(new Car(carName)); + } + return new Cars(cars); + } + + private static void validate(String[] words) { + validateDuplicatedWord(words); + } + + private static void validateDuplicatedWord(String[] words) { + Set<String> uniqueWord = new HashSet<>(); + for (String word : words) { + if (!uniqueWord.add(word)) { + throw new CarsDuplicatedNameException(); + } + } + } + + private static String[] divideWord(String word) { + return word.replaceAll(DUPLICATED_DELIMITER_REGEX, DELIMITER).split(DELIMITER); + } + + public void move(CarMoveNumberGenerator carMoveNumberGenerator) { + for (Car car : cars) { + car.move(carMoveNumberGenerator); + } + } + + public Winner findWinner() { + int maxScore = findMaxScore(); + return new Winner(cars.stream() + .filter(car -> (car.getPosition() == maxScore)) + .map(Car::getName) + .collect(Collectors.toList())); + } + + private int findMaxScore() { + return cars.stream() + .max(Comparator.comparingInt(Car::getPosition)) + .map(Car::getPosition) + .orElseThrow(CarsMaxScoreBlankException::new); + } + + public List<Car> getCars() { + return cars; + } +}
Java
์˜ค... ์ข‹์€๊ธ€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋ฐฉ์–ด์ ๋ณต์‚ฌ๋Š” ์ฒ˜์Œ ์ ‘ํ•ด๋ณด๋Š” ๊ฐœ๋…์ด๋„ค์š”!
@@ -0,0 +1,54 @@ +package racingcar.view; + +import racingcar.domain.Car; +import racingcar.domain.Cars; +import racingcar.domain.Winner; + +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class OutputView { + + private static final String MESSAGE_INPUT_CAR_NAME = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String MESSAGE_INPUT_TRY = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + private static final String MESSAGE_RESULT = "์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String MOVE_MARK = "-"; + private static final String JOIN_NAME_AND_POSITION = " : "; + private static final String WINNER_DELIMITER = ","; + private static final String MESSAGE_WINNER_PREFIX = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String MESSAGE_WINNER_SUFFIX = ""; + + public void printInputCarName() { + System.out.println(MESSAGE_INPUT_CAR_NAME); + } + + public void printExceptionMessage(IllegalArgumentException exceptionMessage) { + System.out.println(exceptionMessage.getMessage()); + } + + public void printInputTry() { + System.out.println(MESSAGE_INPUT_TRY); + } + + public void printBlank() { + System.out.println(); + } + + public void printResult(Cars cars) { + System.out.println(MESSAGE_RESULT); + for(Car car : cars.getCars()){ + System.out.println(car.getName() + JOIN_NAME_AND_POSITION + convertMoveMark(car.getPosition())); + } + printBlank(); + } + + private String convertMoveMark(int position) { + return Stream.generate(() -> MOVE_MARK).limit(position).collect(Collectors.joining()); + } + + public void printWinner(Winner winner) { + String message = winner.getWinner().stream() + .collect(Collectors.joining(WINNER_DELIMITER, MESSAGE_WINNER_PREFIX, MESSAGE_WINNER_SUFFIX)); + System.out.println(message); + } +}
Java
์ด๋Ÿฐ,, ์ŠคํŠธ๋ฆผ์„ ๋„ˆ๋ฌด ๋‚จ๋ฐœํ–ˆ๋„ค์š”.. `repeat()` ๋ผ๋Š” ์ข‹์€ ํ•จ์ˆ˜๊ฐ€ ์žˆ๋Š”๋ฐ ๋ง์ด์ฃ  ใ… 
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public class RacingCarGame { + + private final Cars cars; + + public RacingCarGame(Cars cars) { + this.cars = cars; + } + + public void move() { + cars.move(new CarRandomMoveNumberGenerator()); + } + + public Winner findWinner() { + return cars.findWinner(); + } + + public Cars getCars() { + return cars; + } +}
Java
์›๋ž˜ `RacingCarGame` ์—์„œ ์‹œ๋„ํšŸ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ ์žˆ์–ด์„œ `Cars` ๋ฅผ ์‹œ๋„ํšŸ์ˆ˜๋งŒํผ ์›€์ง์ด๋Š” ๋กœ์ง์ด์žˆ์—ˆ๋Š”๋ฐ controller ์ชฝ์œผ๋กœ ํ•ด๋‹น ๋กœ์ง์„ ์˜ฎ๊ธฐ๋Š”๋ฐ”๋žŒ์— ์“ธ๋ชจ์—†๋Š” ํด๋ž˜์Šค๊ฐ€ ๋˜์—ˆ๋„ค์š”.. ์ข‹์€ ์ง€์  ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค..!
@@ -0,0 +1,47 @@ +package racingcar.domain; + +import racingcar.exception.TryCommandNumberException; +import racingcar.exception.TryCommandRangeException; + +public class TryCommand { + + private static final int MIN_TRY = 1; + private static final int MAX_TRY = 100000; + private int tryCount; + + private TryCommand(int tryCount) { + this.tryCount = tryCount; + } + + public static TryCommand createTryCommandByString(String input) { + int number = convertInt(input); + validate(number); + return new TryCommand(number); + } + + private static void validate(int number) { + validateRange(number); + } + + private static void validateRange(int number) { + if(number < MIN_TRY || number > MAX_TRY) { + throw new TryCommandRangeException(MIN_TRY, MAX_TRY); + } + } + + private static int convertInt(String input) { + try{ + return Integer.parseInt(input); + }catch (NumberFormatException exception) { + throw new TryCommandNumberException(); + } + } + + public boolean tryMove() { + if(tryCount > 0) { + tryCount--; + return true; + } + return false; + } +}
Java
๋ถˆ๋ณ€์œผ๋กœ ํ•ด๋„ ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์—ˆ๊ตฐ์š”.. DDD ์—์„œ ๋‚˜์˜ค๋Š” ๊ฐœ๋…์ด๋ผ MVC ์—๋Š” ์–ด๋–ป๊ฒŒ ์ ์šฉํ• ์ง€๋Š” ๊ณ ๋ฏผ์„ ํ•ด๋ด์•ผ๊ฒ ๋„ค์š”.. ์ข‹์€๊ธ€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,10 @@ +package racingcar.exception; + +public class CarNameLengthException extends IllegalArgumentException{ + + private static final String EXCEPTION_MESSAGE_CAR_NAME_LENGTH = "[ERROR] ์ž๋™์ฐจ์ด๋ฆ„์€ 5๊ธ€์ž ์ดํ•˜์ž…๋‹ˆ๋‹ค"; + + public CarNameLengthException() { + super(EXCEPTION_MESSAGE_CAR_NAME_LENGTH); + } +}
Java
[์ปค์Šคํ…€์˜ˆ์™ธ](https://tecoble.techcourse.co.kr/post/2020-08-17-custom-exception/) ์ปค์Šคํ…€ ์˜ˆ์™ธ๋“ค์€ ์žฅ๋‹จ์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค! ๊ทธ๋ž˜์„œ ์ •๋‹ต์€ ์—†์ง€๋งŒ ์ œ๊ฐ€ ์‚ฌ์šฉํ•œ ์ด์œ ๋Š” ์ฒซ์งธ๋กœํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ์–ด๋–ค ์˜ˆ์™ธ์ธ์ง€ ๋ฐ”๋กœ ์•Œ ์ˆ˜ ์žˆ๊ณ  ๋‘˜์งธ๋กœ ๋ณดํ†ต ๋„๋ฉ”์ธ ์ฝ”๋“œ๋ฅผ ๋ณผ๋•Œ ์ค‘์š”ํ•œ๊ฒƒ์€ ๊ทธ ๋„๋ฉ”์ธ ์—ญํ• ๊ณผ ๊ด€๋ จ๋œ ๋กœ์ง์ด์ง€, ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•˜๋Š”์ง€๊ฐ€ ์ค‘์š”ํ•œ๊ฒŒ ์•„๋‹ˆ๊ธฐ๋•Œ๋ฌธ์— ์˜ˆ์™ธ๋ฅผ ๋”ฐ๋กœ๋นผ๋‚ด์–ด ์ข€ ๋” ๋ณด๊ธฐ ํŽธํ•œ๊ฒŒ ๋งŒ๋“ค๊ธฐ ์œ„ํ•จ์ž…๋‹ˆ๋‹ค! ์…‹์งธ๋กœ ๋Œ€๋ถ€๋ถ„ Spring MVC ํ”„๋กœ์ ํŠธ์—์„œ๋Š” ์ปค์Šคํ…€ ์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ์— ์—ฐ์Šต์ฐจ์›์—์„œ ์ปค์Šคํ…€ ์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package baseball.util + +// Message +const val PRINT_NOTHING_MESSAGE = "๋‚ซ์‹ฑ" +const val PRINT_STRIKE_MESSAGE = "%d์ŠคํŠธ๋ผ์ดํฌ" +const val PRINT_BALL_MESSAGE = "%d๋ณผ" +const val PRINT_STRIKE_BALL_MESSAGE = "%d๋ณผ %d์ŠคํŠธ๋ผ์ดํฌ" +const val START_GAME_MASSAGE = "์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค." +const val QUIT_GAME_MASSAGE = "3๊ฐœ์˜ ์ˆซ์ž๋ฅผ ๋ชจ๋‘ ๋งžํžˆ์…จ์Šต๋‹ˆ๋‹ค! ๊ฒŒ์ž„ ์ข…๋ฃŒ" +const val SELECT_COMMAND_MESSAGE = "๊ฒŒ์ž„์„ ์ƒˆ๋กœ ์‹œ์ž‘ํ•˜๋ ค๋ฉด 1, ์ข…๋ฃŒํ•˜๋ ค๋ฉด 2๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”." +const val USER_INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”: " +// Error +const val ERROR_INVALID_INPUT_MESSAGE = "์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค" +const val ERROR_INVALID_COMMAND_MESSAGE = "1๊ณผ 2๋งŒ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”." + +// Command +const val RETRY_COMMAND = "1" +const val QUIT_COMMAND = "2" + +// Code +const val END_CODE = 2 +const val PLAYING_CODE = 1 + +// Size, Number +const val MAX_SIZE = 3 +const val MAX_NUMBER = 9 +const val MIN_NUMBER = 1 + +// String +const val EMPTY_STRING = "" + +
Kotlin
util ํด๋”๋ฅผ ์‚ฌ์šฉํ•ด EMPTY_STRING๊ณผ ๊ฐ™์ด ์‚ฌ์†Œํ•œ ๊ฐ’๋“ค๊นŒ์ง€ ์ƒ์ˆ˜ํ™”๋ฅผ ํ•˜์‹  ๋•๋ถ„์— ๊ฐ€๋…์„ฑ์ด ์ข‹๋„ค์š”. ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,59 @@ +package baseball.game + +import baseball.game.service.Game +import baseball.model.AnswerBoard +import baseball.model.Computer +import baseball.util.* +import baseball.view.User +import baseball.view.validator.InputValidator + +class Baseball( + private val user: User, + private val computer: Computer, + private val answerBoard: AnswerBoard, +) : Game { + private var gameState = PLAYING_CODE + private var answer = computer.createAnswer() + + override fun play() { + println(START_GAME_MASSAGE) + process() + } + + // ๊ฒŒ์ž„ ์ง„ํ–‰ + override fun process() { + do { + val userNumber = user.createNumber() + + answerBoard.createResult(answer, userNumber) + println(answerBoard.printResult()) + + finish() + } while (isPlaying()) + } + + private fun isPlaying(): Boolean = gameState != END_CODE + + override fun quit() { + gameState = END_CODE + } + + override fun retry() { + answer = computer.createAnswer() + answerBoard.clearState() + } + + private fun printFinishMessage() = println(QUIT_GAME_MASSAGE + "\n" + SELECT_COMMAND_MESSAGE) + + private fun finish() { + if (answerBoard.isThreeStrike()) { + printFinishMessage() + when (InputValidator.validateUserCommand(readLine()!!)) { + RETRY_COMMAND -> retry() + QUIT_COMMAND -> quit() + } + } + } + +} +
Kotlin
MVC ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•˜์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. Baseball Class๋Š” Controller์˜ ์—ญํ• ์„ ํ•˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, Controller์—์„œ ์ง์ ‘ ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” ์‚ฌ์šฉ์ž์™€ ์ง์ ‘์ ์œผ๋กœ ๋งž๋‹ฟ๋Š” View์—์„œ ์ž…๋ ฅ์„ ๋ฐ›์•„์™€ Controller์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,12 @@ +package baseball.view + +import baseball.util.USER_INPUT_NUMBER_MESSAGE +import baseball.view.validator.InputValidator + +class User { + fun createNumber(): String { + print(USER_INPUT_NUMBER_MESSAGE) + val userNumber = readLine()!! + return InputValidator.validateUserNumber(userNumber) + } +} \ No newline at end of file
Kotlin
์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›์•„์™€ ๊ฒ€์‚ฌ๋œ ๊ฐ’์„ ๋Œ๋ ค๋ณด๋‚ด์ฃผ๋Š” ํ•จ์ˆ˜์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. create๋ผ๋Š” ํ•จ์ˆ˜๋ช…์„ ๋ณด์•˜์„ ๋•Œ ์ €๋Š” "์‚ฌ์šฉ์ž๊ฐ€ ๋ฒˆํ˜ธ๋ฅผ ๋งŒ๋“œ๋‚˜? ์‚ฌ์šฉ์ž๊ฐ€ ๊ธฐ๊ณ„์˜ ์—ญํ• ์„ ํ•˜๋Š” ๊ฒƒ์ธ๊ฐ€?"๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค. input๊ณผ ์–ด์šธ๋ฆฌ๋Š” ํ•จ์ˆ˜๋ช…์ด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ, ์ €๋„ ์ด ๋ถ€๋ถ„์€ ์กฐ๊ธˆ ๊ณ ๋ฏผ๋˜๋Š” ๋ถ€๋ถ„์ด์ง€๋งŒ, MVC ํŒจํ„ด์˜ View์—์„œ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ์™€ ๋ถ„๊ธฐ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋กœ์ง์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ํŒจํ„ด์˜ ๊ทœ์น™์— ๋งž์ง€ ์•Š๋Š”๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package baseball.view.validator + +import baseball.util.* + +object InputValidator { + + fun validateUserNumber(userNumber: String): String { + require(userNumber.length == MAX_SIZE) { ERROR_INVALID_INPUT_MESSAGE } + return userNumber + } + + fun validateUserCommand(command: String): String { + require(command == RETRY_COMMAND || command == QUIT_COMMAND) { ERROR_INVALID_COMMAND_MESSAGE } + return command + } +} +
Kotlin
๋ฏผ์žฌ๋‹˜๊ป˜์„œ ์ €์—๊ฒŒ require์— ๋Œ€ํ•ด ์•Œ๋ ค์ฃผ์…จ์ฃ ..! ์ž˜ ์“ฐ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,59 @@ +package baseball.model + +import baseball.util.* + + +class AnswerBoard { + // ์ƒํƒœ๋ฅผ ๋ชจ๋‘ ์•„์›ƒ์œผ๋กœ ์ดˆ๊ธฐํ™” + private val stateList = MutableList(MAX_SIZE) { BaseballState.OUT } + + + private fun createCount(): Triple<Int, Int, Int> { + var strikeCount = 0 + var ballCount = 0 + var outCount = 0 + + stateList.forEach { state -> + when (state) { + BaseballState.STRIKE -> strikeCount++ + BaseballState.BALL -> ballCount++ + BaseballState.OUT -> outCount++ + } + } + return Triple(strikeCount, ballCount, outCount) + } + + fun createResult(answer: String, userNumber: String) { + answer.forEachIndexed { answerIndex, answerNumber -> + if (answerNumber == userNumber[answerIndex]) { + stateList[answerIndex] = BaseballState.STRIKE + } + if (answerNumber != userNumber[answerIndex] && answer.contains(userNumber[answerIndex])) { + stateList[answerIndex] = BaseballState.BALL + } + if (answerNumber != userNumber[answerIndex] && !answer.contains(userNumber[answerIndex])) { + stateList[answerIndex] = BaseballState.OUT + } + } + } + + fun printResult(): String { + val (strikeCount, ballCount, outCount) = createCount() + var message = EMPTY_STRING + + // ์•„์›ƒ์ผ ๋•Œ ์ถœ๋ ฅ + if (outCount == stateList.size) message = PRINT_NOTHING_MESSAGE + // ์ŠคํŠธ๋ผ์ดํฌ์ผ๋•Œ ์ถœ๋ ฅ + if (ballCount == 0 && strikeCount != 0) message = PRINT_STRIKE_MESSAGE.format(strikeCount) + // ๋ณผ์ผ๋•Œ ์ถœ๋ ฅ + if (ballCount != 0 && strikeCount == 0) message = PRINT_BALL_MESSAGE.format(ballCount) + // ์ŠคํŠธ๋ผ์ดํฌ ๋ณผ์ผ ๋•Œ + if (ballCount != 0 && strikeCount != 0) message = PRINT_STRIKE_BALL_MESSAGE.format(ballCount, strikeCount) + + return message + } + + fun isThreeStrike(): Boolean = stateList.all { state -> state == BaseballState.STRIKE } + + fun clearState() = stateList.replaceAll { BaseballState.OUT } +}
Kotlin
createCount๋ผ๋Š” ํ•จ์ˆ˜๋ช…์€ "๊ฐœ์ˆ˜๋ฅผ **_๋งŒ๋“ ๋‹ค_**"๋ผ๋Š” ์˜๋ฏธ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ•จ์ˆ˜์˜ ์—ญํ• ์€ "์ŠคํŠธ๋ผ์ดํฌ, ๋ณผ, ์•„์›ƒ์˜ ๊ฐœ์ˆ˜๋ฅผ **_์„ผ๋‹ค_**"์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•จ์ˆ˜๋ช…๊ณผ ์„ธ๊ฐ€์ง€์˜ ๊ธฐ๋Šฅ์„ ๋‚˜๋ˆ„๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”? countStrike, countBall, countOut๊ณผ ๊ฐ™์ด์š”!
@@ -0,0 +1,59 @@ +package baseball.model + +import baseball.util.* + + +class AnswerBoard { + // ์ƒํƒœ๋ฅผ ๋ชจ๋‘ ์•„์›ƒ์œผ๋กœ ์ดˆ๊ธฐํ™” + private val stateList = MutableList(MAX_SIZE) { BaseballState.OUT } + + + private fun createCount(): Triple<Int, Int, Int> { + var strikeCount = 0 + var ballCount = 0 + var outCount = 0 + + stateList.forEach { state -> + when (state) { + BaseballState.STRIKE -> strikeCount++ + BaseballState.BALL -> ballCount++ + BaseballState.OUT -> outCount++ + } + } + return Triple(strikeCount, ballCount, outCount) + } + + fun createResult(answer: String, userNumber: String) { + answer.forEachIndexed { answerIndex, answerNumber -> + if (answerNumber == userNumber[answerIndex]) { + stateList[answerIndex] = BaseballState.STRIKE + } + if (answerNumber != userNumber[answerIndex] && answer.contains(userNumber[answerIndex])) { + stateList[answerIndex] = BaseballState.BALL + } + if (answerNumber != userNumber[answerIndex] && !answer.contains(userNumber[answerIndex])) { + stateList[answerIndex] = BaseballState.OUT + } + } + } + + fun printResult(): String { + val (strikeCount, ballCount, outCount) = createCount() + var message = EMPTY_STRING + + // ์•„์›ƒ์ผ ๋•Œ ์ถœ๋ ฅ + if (outCount == stateList.size) message = PRINT_NOTHING_MESSAGE + // ์ŠคํŠธ๋ผ์ดํฌ์ผ๋•Œ ์ถœ๋ ฅ + if (ballCount == 0 && strikeCount != 0) message = PRINT_STRIKE_MESSAGE.format(strikeCount) + // ๋ณผ์ผ๋•Œ ์ถœ๋ ฅ + if (ballCount != 0 && strikeCount == 0) message = PRINT_BALL_MESSAGE.format(ballCount) + // ์ŠคํŠธ๋ผ์ดํฌ ๋ณผ์ผ ๋•Œ + if (ballCount != 0 && strikeCount != 0) message = PRINT_STRIKE_BALL_MESSAGE.format(ballCount, strikeCount) + + return message + } + + fun isThreeStrike(): Boolean = stateList.all { state -> state == BaseballState.STRIKE } + + fun clearState() = stateList.replaceAll { BaseballState.OUT } +}
Kotlin
๋ณ€์ˆ˜๋ช…์ด ๋™์‚ฌ + ๋ช…์‚ฌ๋กœ ํ•œ๋‹ค๋ฉด ํ•จ์ˆ˜๋ช…๊ณผ ๋ถˆ์ผ์น˜ ํ•˜์ง€ ์•Š์„๊นŒ์š” ?!? ์ด๋ฆ„ ์ง“๊ธฐ์—์„œ ์ค‘์š”ํ•œ ๋ช…์‚ฌ๋Š” ์•ž์— ์“ฐ๋Š” ๊ฒƒ์ด ์ข‹๋‹ซ๊ณ  ํ•ฉ๋‹ˆ๋‹ค !! ex) countStrike -> strikeCount
@@ -0,0 +1,12 @@ +package baseball.view + +import baseball.util.USER_INPUT_NUMBER_MESSAGE +import baseball.view.validator.InputValidator + +class User { + fun createNumber(): String { + print(USER_INPUT_NUMBER_MESSAGE) + val userNumber = readLine()!! + return InputValidator.validateUserNumber(userNumber) + } +} \ No newline at end of file
Kotlin
์ด ๋ถ€๋ถ„๋„ ์ง€๊ธˆ๊นŒ์ง€๋„ ๊ณ ๋ฏผ์ด์˜€๋Š”๋ฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ๋”ฐ๋กœ ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค !!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๋ณ€์ˆ˜ ์„ ์–ธํ•  ๋•Œ๋Š” `scope` ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•ด์„œ ํ•ญ์ƒ `const`, `let` ๋“ฑ์˜ ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์ฃผ๋Š”๊ฒŒ ์ข‹์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—ฌ๊ธฐ๋„ ์œ„์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ์— ์ ์ ˆํ•œ ํ‚ค์›Œ๋“œ๊ฐ€ ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๋ฐ˜๋ณต๋ฌธ ์•ˆ์˜ `validType` ์€ ์žฌํ• ๋‹นํ•  ํ•„์š”๋Š” ์—†์–ด ๋ณด์ž…๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด `const` ๊ฐ€ ๋” ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ „์ฒด์ ์œผ๋กœ String.prototype.match ๋ฅผ ๋งŽ์ด ์‚ฌ์šฉํ•˜์…จ๋Š”๋ฐ, Regex ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•ด ๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–ฏ๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
`req.body` ์— ๋‹ค์Œ ํ‚ค๊ฐ’๋“ค ์ค‘ ํ•˜๋‚˜๊ฐ€ ์•„์˜ˆ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ, ๋Ÿฐํƒ€์ž„์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ตฌ์กฐํ™” ํ• ๋‹น ์‹œ์— ์ „์ฒด์ ์œผ๋กœ ์ฃผ์˜ํ•˜๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—ฌ๊ธฐ ๋ฐ˜๋ณต๋ฌธ ๋‚ด์˜ `info` ๋„ ์žฌํ• ๋‹นํ•  ์ผ์€ ์—†์–ด๋ณด์ด๋‹ˆ `const` ๊ฐ€ ๋” ์ ์ ˆํ•ด ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—๋Ÿฌ๋ฅผ ๋˜์ง€๋Š” ๋ถ€๋ถ„์„ ๋ชจ๋“ˆํ™”ํ•˜๊ฒŒ ๋˜๋ฉด ๋” ๋†’์€ ์‚ฌ์šฉ์„ฑ์„ ๊ฐ–๊ฒŒ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ทธ๋ฆฌ๊ณ  ์ง์ ‘ ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์—๋Ÿฌ๋ฅผ `throw` ํ•˜๊ณ , `catch` ๊ตฌ๋ฌธ์—์„œ ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด๋กœ ๊ฑด๋‚ด๋ฉด์„œ ์ตœ์ข…์ ์œผ๋กœ ์—๋Ÿฌ๋ฅผ ํ—จ๋“ค๋งํ•˜๋Š” ํ•จ์ˆ˜์—์„œ ํ•œ๋ฒˆ์— ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ „์ฒด์ ์œผ๋กœ ํ•˜๋‚˜์˜ ์ปจํŠธ๋กค๋Ÿฌ ์•ˆ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ ˆ์ฐจ๋“ค์ด ๋‚˜์—ด๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•จ์ˆ˜ ๋‹จ์œ„๋กœ ๋” ์ชผ๊ฒŒ๊ฒŒ๋˜๋ฉด, ๋‚˜์ค‘์— unit test ์‹œ์—๋„ ๋” ํŽธ๋ฆฌํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฒ€์ฆํ•˜๊ณ  ์žˆ๋Š” ์—ฌ๋Ÿฌ ๋กœ์ง๋“ค๋„, ์ ์ ˆํžˆ Service ์•ˆ์— ๋„ฃ์–ด๋‘˜ ํ•„์š”๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ hash ํ•˜๋Š” ๋ถ€๋ถ„๋„ req, res ๋งŒ ๋‹ค๋ฃจ๊ฒŒ ๋˜๋Š” ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ๋‹ค๋ฃจ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ์–ด์ƒ‰ํ•ด ๋ณด์ด๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค. ์ „๋ฐ˜์ ์œผ๋กœ ์ด ๊ฐ ํ•จ์ˆ˜๊ฐ€ ํ•˜๋‚˜์˜ ๋ช…ํ™•ํ•œ ์ผ๋งŒ ํ•˜๋„๋ก ๊ตฌ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์‘๋‹ต ๊ฐ’๋„ ํด๋ผ์ด์–ธํŠธ์™€์˜ ํ˜‘์•ฝ์— ๋”ฐ๋ผ ์ •ํ•ด์ง„ ํผ์„ ํ•ญ์ƒ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋ชจ๋“ˆํ™”ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์œ ์ง€/๋ณด์ˆ˜์— ๋” ์šฉ์ดํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const middleware = require('../middlewares'); +const { userController } = require('../controllers'); +// Route ๋Š” ์˜ค์ง Controller ์—๋งŒ ์˜์กด ํ•ฉ๋‹ˆ๋‹ค. + +router.post( + '/signup', + [middleware.validateSignUpUserData, middleware.hashPassword], + userController.signUp, +); + +module.exports = router;
JavaScript
์ด ๋ถ€๋ถ„ ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ํ•˜๋‚˜์š”? ํ‚ค๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +const bcrypt = require('bcrypt'); +const { userDao } = require('../dao'); + +const validateEmail = (email) => { + const validEmailRegExp = /\w@\w+\.\w/i; + return validEmailRegExp.test(email); +}; + +const validatePw = (pw) => { + const pwValidation = { + regexUppercase: /[A-Z]/g, + regexLowercase: /[a-z]/g, + regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g, + regexDigit: /[0-9]/g, + }; + const MIN_PW_LENGTH = 8; + const pwLength = pw.length; + + if (pwLength < MIN_PW_LENGTH) return false; + + for (const validType in pwValidation) { + if (!pwValidation[validType].test(pw)) { + return false; + } + } + + return true; +}; + +const hashPassword = async (password) => { + return await bcrypt.hash(password, 10); +}; + +const findUser = async (fields) => { + return await userDao.findUser(fields); +}; + +const createUser = async (userData) => { + return await userDao.createUser(userData); +}; + +module.exports = { + validateEmail, + validatePw, + hashPassword, + findUser, + createUser, +};
JavaScript
์ด๋Ÿฐ ํ•จ์ˆ˜๋Š” ์•„์˜ˆ ๋ชจ๋“ˆํ™”ํ•ด์„œ ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ด ๋ถ€๋ถ„ ์ž‘๋™ ์ž˜ ํ•˜๋‚˜์š”? ํ‚ค ๊ฐ’์ด ์•ˆ ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค! validation ๋กœ์ง์€ ์˜ˆ์ „ ์ œ ์ฝ”๋“œ ๊ธ์–ด์˜ค๋‹ค๊ฐ€ ๋†“์นœ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
ํ”„๋ก ํŠธ๋‹จ์—์„œ ๋ฐ›์€ `req.body`์— ์œ„ ํ‚ค๊ฐ’๋“ค์ด ๋ˆ„๋ฝ๋  ๊ฒฝ์šฐ ๊ทธ ๊ฐ’์ด undefined๋กœ ๋˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ œ๊ฐ€ ๋†“์น˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์ด ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
`RegExp.prototype.test()`๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์›”์š”์ผ์— ๋ง์”€ํ•ด์ฃผ์‹ ๋Œ€๋กœ `return res` ํ˜•ํƒœ๊ฐ€ ์•„๋‹ˆ๋ผ ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ๋ชจ๋“ˆํ™” ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!!!!!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—๋Ÿฌ ํ•ธ๋“ค๋ง๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์‘๋‹ต๋„ ๋ชจ๋“ˆํ™” ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const middleware = require('../middlewares'); +const { userController } = require('../controllers'); +// Route ๋Š” ์˜ค์ง Controller ์—๋งŒ ์˜์กด ํ•ฉ๋‹ˆ๋‹ค. + +router.post( + '/signup', + [middleware.validateSignUpUserData, middleware.hashPassword], + userController.signUp, +); + +module.exports = router;
JavaScript
convention ์ˆ˜์ •ํ•˜๋ ค๋‹ค๊ฐ€ ๋†“์นœ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค... ๊ด€๋ จ๋œ ๋ถ€๋ถ„ ๋ชจ๋‘ ์ˆ˜์ •ํ•˜๊ณ  ํšŒ์›๊ฐ€์ž…๋„ ํ™•์ธํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
dao์™€ services๋กœ ๋ถ„๋ฆฌํ•˜๊ธฐ๋กœ ๊ฒฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ œ๊ฐ€ ์ฐฉ๊ฐํ–ˆ๋„ค์š”! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๋ฏธ๋“ค์›จ์–ด์—์„œ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ•˜๋Š” ๊ฑด๊ฐ€์š”? ์ด ๋ฐฉ๋ฒ•๋„ ๊ต‰์žฅํžˆ ์ฐธ์‹ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์„œ๋น„์Šค๊ฐ€ ์ปค์ง€๊ฒŒ ๋˜๊ฑฐ๋‚˜, ๋ชจ๋…ธ๋ฆฌํฌ๋ฅผ ์ ์šฉํ•œ๋‹ค๊ฑฐ๋‚˜, ๊ธฐํƒ€ ๋‹ค์–‘ํ•œ ๋ฐฉ์‹์œผ๋กœ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ™œ์šฉํ•˜๊ฒŒ ๋  ๊ฒฝ์šฐ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ณดํ†ต util ํ•จ์ˆ˜๋กœ ๋นผ๋‚ด์–ด ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ณตํ†ต ํ•จ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ๋” ๋ณดํŽธ์ ์ด๊ธฐ๋Š” ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
๋‹ค๋ฅธ POST ์—์„œ๋„ ํ•„์ˆ˜์ ์ธ ํ‚ค๊ฐ’๋“ค์„ ํ™•์ธํ•  ์ผ์ด ๋งŽ์ง€ ์•Š์„๊นŒ์š”? ๋ฒ”์šฉ์ ์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” + ํ•„์ˆ˜ body ํ‚ค ๊ฐ’์„ ํ™•์ธํ•˜๋Š” ๊ณตํ†ต ํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +const bcrypt = require('bcrypt'); +const { userDao } = require('../dao'); + +const validateEmail = (email) => { + const validEmailRegExp = /\w@\w+\.\w/i; + return validEmailRegExp.test(email); +}; + +const validatePw = (pw) => { + const pwValidation = { + regexUppercase: /[A-Z]/g, + regexLowercase: /[a-z]/g, + regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g, + regexDigit: /[0-9]/g, + }; + const MIN_PW_LENGTH = 8; + const pwLength = pw.length; + + if (pwLength < MIN_PW_LENGTH) return false; + + for (const validType in pwValidation) { + if (!pwValidation[validType].test(pw)) { + return false; + } + } + + return true; +}; + +const hashPassword = async (password) => { + return await bcrypt.hash(password, 10); +}; + +const findUser = async (fields) => { + return await userDao.findUser(fields); +}; + +const createUser = async (userData) => { + return await userDao.createUser(userData); +}; + +module.exports = { + validateEmail, + validatePw, + hashPassword, + findUser, + createUser, +};
JavaScript
Regex ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•ด์„œ ์กฐ๊ธˆ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? Regex.prototype.test ์ž์ฒด๊ฐ€ boolean ์„ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋˜๋‹ˆ๊นŒ์š”! +test ๋ฉ”์„œ๋“œ๊ฐ€ match ๋ณด๋‹ค ์„ฑ๋Šฅ์ƒ ์šฐ์œ„์— ์žˆ๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜ค...! ๋งค์šฐ ์œ ์šฉํ•œ ํ•จ์ˆ˜๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” month๋ฅผ Request Param์œผ๋กœ
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
์Œ ์—ฌ๋Ÿฌ ์กฐ๊ฑด์œผ๋กœ ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ์„ ๋งŒ๋“œ์‹  ๊ฒƒ ๊ฐ™์€๋ฐ, API๋ฅผ ๋‚˜๋ˆ„์ง€ ๋ง๊ณ , ๊ฒ€์ƒ‰ ๋ชจ๋“ˆ์„ ๋งŒ๋“œ๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,71 @@ +package com.selab.todo.entity; + +import com.selab.todo.common.BaseEntity; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.DayOfWeek; +import java.time.LocalDateTime; +import java.time.Month; +import java.time.Year; + +@Entity(name = "diary") +@Getter +@Table(name = "diary") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Diary extends BaseEntity { + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "title") + private String title; + + @Column(name = "content") + private String content; + + @Column(name = "createdAt") + @CreatedDate + private LocalDateTime createdAt; + + @Column(name = "year") + private Year year; + + @Column(name = "month") + private Month month; + + @Column(name = "day") + private DayOfWeek day; + + @Column(name = "feel") + private String feel; + + + public Diary(String title, String content, String feel, Year year, Month month, DayOfWeek day) { + this.title = title; + this.content = content; + this.feel = feel; + this.year = year; + this.month = month; + this.day = day; + } + + public void update(String title, String content, String feel) { + this.title = title; + this.content = content; + this.feel = feel; + } + + public void feelingUpdate(String feel){ + this.feel = feel; + } +} \ No newline at end of file
Java
enumrated ์ถ”๊ฐ€ํ•ด์•ผ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ์š”?
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
url path์— ๋Œ€ํ•ด ๋‹ค์‹œ ํ•œ๋ฒˆ ๋” ์ ๊ฒ€ ๋ถ€ํƒ๋“œ๋ฆ…๋‹ˆ๋‹ค! rest url ๊ทœ์น™ ํ™•์ธํ•˜๊ธฐ
@@ -0,0 +1,71 @@ +package com.selab.todo.entity; + +import com.selab.todo.common.BaseEntity; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.DayOfWeek; +import java.time.LocalDateTime; +import java.time.Month; +import java.time.Year; + +@Entity(name = "diary") +@Getter +@Table(name = "diary") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Diary extends BaseEntity { + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "title") + private String title; + + @Column(name = "content") + private String content; + + @Column(name = "createdAt") + @CreatedDate + private LocalDateTime createdAt; + + @Column(name = "year") + private Year year; + + @Column(name = "month") + private Month month; + + @Column(name = "day") + private DayOfWeek day; + + @Column(name = "feel") + private String feel; + + + public Diary(String title, String content, String feel, Year year, Month month, DayOfWeek day) { + this.title = title; + this.content = content; + this.feel = feel; + this.year = year; + this.month = month; + this.day = day; + } + + public void update(String title, String content, String feel) { + this.title = title; + this.content = content; + this.feel = feel; + } + + public void feelingUpdate(String feel){ + this.feel = feel; + } +} \ No newline at end of file
Java
LocalDateTime ํ˜น์€ ZoneDateTime๊ณผ ๊ฐ™์€ ์‹œ๊ฐ„์„ ๋‹ค๋ฃจ๋Š” ๊ฐ์ฒด ์‚ฌ์šฉ์„ ํ•˜์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ผ๊นŒ์š”?
@@ -0,0 +1,23 @@ +package com.selab.todo.entity; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity(name = "feeling") +@Getter +@Table(name = "feeling") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Feeling { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "feel") + private String feel; +}
Java
ํ•ด๋‹น ํด๋ž˜์Šค์˜ ์—ญํ• ์€ ๋ฌด์—‡์ผ๊นŒ์š”? id, baseentity ์ •๋„๋Š” ์ถ”๊ฐ€ํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
์ ์šฉํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
default๋Š” ์™œ ํ•„์š”ํ•ด์š”??
@@ -0,0 +1,97 @@ +package com.selab.todo.controller; + +import com.selab.todo.common.dto.PageDto; +import com.selab.todo.common.dto.ResponseDto; +import com.selab.todo.dto.request.diary.DiaryRegisterRequest; +import com.selab.todo.dto.request.diary.DiaryUpdateRequest; +import com.selab.todo.dto.request.feel.FeelingUpdateRequest; +import com.selab.todo.service.DiaryService; +import com.selab.todo.service.FeelingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = {"Diary API"}) +@RestController +@RequestMapping(value = "/api/v1/diaries", produces = MediaType.APPLICATION_JSON_VALUE) +@RequiredArgsConstructor +public class DiaryController { + private final DiaryService diaryService; + private final FeelingService feelingService; + + @ApiOperation(value = "Diary ๋“ฑ๋กํ•˜๊ธฐ") + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/register") + public ResponseEntity<?> register(@RequestBody DiaryRegisterRequest request) { + var response = diaryService.register(request); + return ResponseDto.created(response); + } + + @ApiOperation(value = "Diary ๋‹จ๊ฑด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/{id}") + public ResponseEntity<?> get(@PathVariable Long id) { + var response = diaryService.get(id); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/search-all") + public ResponseEntity<?> getAll( + @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable + ) { + var response = diaryService.getAll(pageable); + return PageDto.ok(response); + } + + @ApiOperation(value = "Diary ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping("/{id}") // @PatchMapping + public ResponseEntity<?> update( + @PathVariable Long id, + @RequestBody DiaryUpdateRequest request + ) { + var response = diaryService.update(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Diary ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/{id}") + public ResponseEntity<Void> delete( + @PathVariable Long id + ) { + diaryService.delete(id); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Diary ์›”๋ณ„ ์‚ญ์ œํ•˜๊ธฐ") + @DeleteMapping("/month/{month}") + public ResponseEntity<Void> monthDelete(@PathVariable int month) { + diaryService.monthDelete(month); + return ResponseDto.noContent(); + } + + @ApiOperation(value = "Feeling ์ˆ˜์ •ํ•˜๊ธฐ") + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/feeling/{id}") + public ResponseEntity<?> updateFeeling(@PathVariable Long id, @RequestBody FeelingUpdateRequest request) { + var response = feelingService.updateFeeling(id, request); + return ResponseDto.ok(response); + } + + @ApiOperation(value = "Feeling ์ „์ฒด ์กฐํšŒํ•˜๊ธฐ") + @GetMapping("/feeling-all") + public ResponseEntity<?> getAllFeeling(@PageableDefault Pageable pageable) { + var response = feelingService.getAllFeeling(pageable); + return PageDto.ok(response); + } +}
Java
REST API - POST : /api/v1/diaries - GET : /api/v1/diaries - GET : /api/v1/diaries/{id} - PUT : /api/v1/diaries/{id} - DELETE : /api/v1/diaries/{id} ์ด ํ˜•ํƒœ ์•„๋‹Œ๊ฐ€์š”? ๊ทธ๋ฆฌ๊ณ  url path์— ์™œ ๋Œ€๋ฌธ์ž๊ฐ€ ๋“ค์–ด๊ฐ€๋Š”๊ฑธ๊นŒ์šฉ?
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Controller๋ฅผ Entry-point๋กœ์จ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ˜„์žฌ์™€ ๊ฐ™์ด ํ•ด๋‹น ๊ฐ’๋“ค์„ ์ด๋ฅผ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ๊ฐ€์ง€๊ฒŒ ๋˜๋ฉด ํ•ด๋‹น ๊ฒŒ์ž„์„ ์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ ๋ถ€์ •ํ•ฉ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ์ง€์—ญ๋ณ€์ˆ˜๋กœ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์—ฌ์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
๋ฉ”์†Œ๋“œ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ๋˜์–ด ์žˆ์–ด์„œ, ๊ฐ€๋…์„ฑ์ด ์ข‹๋„ค์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
DTO๋„ ์ž์‹ ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด์„œ, ์–ด๋–ค ํ–‰์œ„/ํŒ๋‹จ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’์ด Y/N์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋กœ์ง์€ DTO๋กœ ๊ฐ€๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋งŒ ํ•ด๋‹น ๋กœ์ง์ด ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ์‚ฌ์šฉ๋˜๊ฑฐ๋‚˜, ์ด๋ฅผ ํ•˜๋‚˜์˜ ๋„๋ฉ”์ธ ํ–‰์œ„๋กœ ์ •์˜ํ•œ๋‹ค๋ฉด DTO -> Domain์œผ๋กœ ์ „ํ™˜ํ•œ ๋‹ค์Œ ๋„๋ฉ”์ธ์—์„œ ํŒ๋‹จํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ํ˜„์žฌ๋Š” ํ•ด๋‹น ๋ถ€๋ถ„์— ๋Œ€ํ•œ ๋„๋ฉ”์ธ ๋กœ์ง์ด Controller์— ๋‚˜์™€ ์žˆ๊ธฐ์— ์›ํ•˜์‹œ๋Š” ํ˜•ํƒœ๋กœ ํฌ์žฅํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚ ์ถ”๊ฐ€๋กœ ๋„ค์ด๋ฐ์€ ํŒ€๋ฐ”ํŒ€์ด๊ณ  ์‚ฌ๋ฐ”์‚ฌ์ง€๋งŒ, ๊ฐœ์ธ์ ์œผ๋กœ ํ”„๋กœ๊ทธ๋žจ์—๊ฒŒ ๋„˜์–ด์˜จ Input์„ ๋‹ด๋Š” DTO๋Š” Request/์šฐ๋ฆฌ ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”DTO๋Š” Response๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์–ด์š”. response๋กœ ์ž‘์„ฑํ•ด์ฃผ์‹  ๋งฅ๋ฝ์€ ์•Œ๊ฒ ์œผ๋‚˜, Client-Server๊ฐ€ ํ•ญ์ƒ ์œ ๋™์ ์œผ๋กœ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๋‹ค๋ฉด DTO๊ฐ€ ๋งŽ์•„์กŒ์„ ๋•Œ ํ—ท๊ฐˆ๋ฆด ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”๐Ÿ™‚ (์ถ”๊ฐ€๋กœ DTO๋Š” > Dto๋กœ ์ ๊ณ  ์žˆ๊ธดํ•ฉ๋‹ˆ๋‹ค - ์ทจํ–ฅ)
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
`Utils์„ฑ ํด๋ž˜์Šค`๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ์ •๋ง ์œ ํ‹ธ๋ฆฌํ‹ฐํ•œ ๊ฒƒ๋“ค๋งŒ ๊ธฐ๋Šฅ์„ ๋‹ด๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด์—์š”. ํ˜„์žฌ ์œ ํ‹ธ๋กœ์ง์ด Y/N์ด๋ผ๋Š” ์–ด๋–ค ๋ฃฐ์— ๋Œ€ํ•ด์„œ ๋„ˆ๋ฌด ๋งŽ์ด ์•Œ๊ณ  ์žˆ๋Š” ์ƒํƒœ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๋„๋ฉ”์ธ ํ˜น์€ DTO์˜ ๋กœ์ง์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ด๊ณ , Util์—์„œ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด ๊ฒ€์ฆ ๋Œ€์ƒ์ด ๋˜๋Š” Y/N๋„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š”๋‹ค๋ฉด ์กฐ๊ธˆ ๋” ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
LinkedList๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๋Š” ์นด๋“œ๋ฅผ ํ•œ์žฅ์”ฉ ์‚ญ์ œํ•  ๋•Œ ArrayList๊ฐ€ ๋น„ํšจ์œจ์ ์ด๋ผ์„œ ๊ทธ๋ ‡๊ฒŒ ํ•˜์‹ ๊ฑธ๊นŒ์š”? ๐Ÿ‘
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
ํ˜„์žฌ๋Š” ๊ฒฝ๊ธฐ๋„์ค‘์— ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋˜๋ฉด, ํ”„๋กœ๊ทธ๋žจ์ด ์ข…๋ฃŒ๋˜๋Š” ๊ตฌ์กฐ์ธ๋ฐ์š”. ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฒฝ๊ธฐ๋ฅผ ํ•˜๋‹ค, ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋œ๋‹ค๊ณ  ๊ทธ ๊ฒŒ์ž„์ด ๋ฌดํšจ๊ฐ€ ๋˜์ง€ ์•Š๋“ฏ์ด ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ธ ๋ฐฉ๋ฒ•/๊ตฌํ˜„์„ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. (๊ตฌํ˜„์€ ํ•˜์ง€ ์•Š์œผ์…”๋„ ๋ฉ๋‹ˆ๋‹ค) ๋„๋ฉ”์ธ์— ๋Œ€ํ•ด์„œ ์กฐ๊ธˆ ๋” ๋Šฅ๋™์ ์œผ๋กœ ์ดํ•ดํ•˜๋ฉด ์–ด๋–จ๊นŒ ๋ผ๋Š” ์˜๋ฏธ์—์„œ ๋“œ๋ฆฐ ํ”ผ๋“œ๋ฐฑ์ž…๋‹ˆ๋‹ค. (์ฐธ๊ณ ๋กœ ๋ธ”๋ž™์žญ์—์„œ๋Š” ์ฐธ๊ฐ€ ์ธ์›์„ ์ œํ•œํ•˜๊ณ  ์žˆ๋”๋ผ๊ตฌ์š”๐Ÿ™‚)
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
Randomํ•œ ๊ฐ’์„ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด์„œ, ๋ ˆ์ด์‹ฑ์นด์—์„œ ํ–ˆ๋˜ ๋ฐฉ์‹์œผ๋กœ ์ด๋ฅผ ์™ธ๋ถ€์—์„œ ์ฃผ์ž…๋ฐ›๋Š” ํ˜•ํƒœ๋กœ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
์Šคํƒœํ‹ฑํ•˜๊ฒŒ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์‹œ์ž‘๋จ๊ณผ ๋™์‹œ์— ์ƒ๊ธด๋‹ค๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ํ•˜๊ธฐ ์œ„ํ•ด์„œ static { } ํ˜•ํƒœ๋กœ ์ดˆ๊ธฐํ™”๋ฅผ ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
๋ฉ”์†Œ๋“œ์˜ ๋„ค์ด๋ฐ์œผ๋กœ ๋ดค์„ ๋•Œ `Deck` ์„ ๋งŒ๋“ค ๊ฒƒ ๊ฐ™์€๋ฐ, List<Card> ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์ด ์ง๊ด€์ ์œผ๋กœ ์ดํ•ด๋˜์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ๋œธ๊ณผ ๋™์‹œ์— `cardDecks`๋ฅผ ๋งŒ๋“ค๊ณ  ์žˆ์–ด์„œ, ์‚ฌ์šฉํ•œ๋‹ค๋ฉด getter ํ˜•ํƒœ๋กœ ์‚ฌ์šฉํ•ด์•ผํ•˜์ง€ ์•Š์„๊นŒ ์‹ถ๋„ค์š”. ํ˜น์‹œ ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์‚ฌ๋žŒ ์ž…์žฅ์—์„œ๋Š” `์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ํ•ด๋‹น ๊ฐ’(List<Card>)์€ ํ•ญ์ƒ ๊ณ ์ •๋˜์–ด ์žˆ๋‹ค๋ผ๋Š”๊ฑธ ๋ชฐ๋ผ๋„ ๋˜๊ณ  ํ•„์š”ํ•  ๋•Œ ๋‹ฌ๋ผํ•˜๋ฉด ๋œ๋‹ค` ๋А๋‚Œ์œผ๋กœ ์ž‘์„ฑํ•˜์‹ ๊ฑธ๊นŒ์š”? > ์š” ๊ฒฝ์šฐ์—๋„ ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„  ํ•ญ์ƒ ๋ฑ์„ ๋งŒ๋“ค๊ฑฐ๋ผ ์˜ˆ์ƒํ•˜๊ณ  ๋กœ์ง์„ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์œ„ํ—˜ํ•  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,38 @@ +package blackjack.domain.card; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CardTest { + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ฐ™์€ ๊ฐ์ฒด๋กœ ํŒ๋‹จํ•œ๋‹ค") + @Test + void equalsTest() { + //given, when, then + assertThat(new Card(Denomination.TWO, Type.DIAMOND)) + .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND)); + + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardTwoDiamond() { + //given + Card card = new Card(Denomination.TWO, Type.DIAMOND); + + //when, then + assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ"); + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardAceHeart() { + //given + Card card = new Card(Denomination.ACE, Type.HEART); + + //when, then + assertThat(card.toString()).isEqualTo("Aํ•˜ํŠธ"); + } +}
Java
`assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ")` ์ด๋Ÿฐ ๋ฌธ๋ฒ•๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,102 @@ +package blackjack.domain.participant; + +import blackjack.domain.card.Card; +import blackjack.domain.card.Denomination; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Getter +public abstract class Participant { + private static final int DIFFERENCE_OF_ACE_SCORE = 10; + private static final int BLACKJACK = 21; + private static final int ZERO = 0; + private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ„์ด ๋นˆ ์นธ ํ˜น์€ null ๊ฐ’์ด ์•„๋‹Œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."; + private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์€ ๋ฌธ์ž์™€ ์ˆซ์ž๋กœ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + private final String name; + private final List<Card> cards; + + protected Participant(String name) { + validateName(name); + + this.name = name; + this.cards = new ArrayList<>(); + } + + private void validateName(String name) { + validateNullOrEmpty(name); + validateAlphaNumeric(name); + } + + private void validateNullOrEmpty(String name) { + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY); + } + } + + private void validateAlphaNumeric(String name) { + if (!StringUtils.isAlphanumericSpace(name)) { + throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS); + } + } + + protected abstract boolean drawable(); + + public void receiveCard(Card card) { + cards.add(card); + } + + public int getCardsSum() { + int scoreOfAceAsEleven = sumOfCardsScore(); + int aceCount = getAceCount(); + + while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) { + scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven); + aceCount--; + } + + return scoreOfAceAsEleven; + } + + private int scoreOfAceAsOne(int scoreOfAceAsEleven) { + return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE; + } + + private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) { + return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO; + } + + private int getAceCount() { + return (int) cards.stream() + .filter(Card::isAce) + .count(); + } + + private int sumOfCardsScore() { + return cards.stream() + .map(Card::getDenomination) + .mapToInt(Denomination::getScore) + .sum(); + } + + public boolean isBust() { + return getCardsSum() > BLACKJACK; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Participant that = (Participant) o; + return Objects.equals(name, that.name) && Objects.equals(cards, that.cards); + } + + @Override + public int hashCode() { + return Objects.hash(name, cards); + } +}
Java
ACE์˜ ์ˆ˜๋ฅผ ๊ฒฐ์ •ํ•  ๋•Œ, 1 ๋˜๋Š” 11์ด ๋˜๋Š” ๋กœ์ง์€ Denomination์˜ ์—ญํ• ์ด ์•„๋‹๊นŒ์š”?
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
์žฌ๋ฐŒ๋Š” ์ œ์•ฝ์‚ฌํ•ญ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ˜„์žฌ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๋Š” OutputView ๋กœ์ง์„ ๋‹จ์ˆœํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•จ์ธ ๊ฒƒ ๊ฐ™์•„์š”. ํ™”๋ฉด์— ๋ณด์—ฌ์ฃผ๋Š” ํ˜•ํƒœ๊ฐ€ ๋‹ฌ๋ผ์กŒ์„ ๋•Œ, ๋„๋ฉ”์ธ์„ ์ˆ˜์ •ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์˜์กด๊ด€๊ณ„๊ฐ€ ์ž˜ ๋ชป ์„ค๊ณ„๋œ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ์ด๊ฒผ๋‹ค๊ฐ€, ์•„๋‹ˆ๋ผ `๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ฉ”์†Œ๋“œ`๋‹ˆ๊นŒ ์ด๋ฆ„์„ ๋ณ€๊ฒฝํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ `Rule`์ด ์‚ฌ์šฉ์ž์™€ ๋”œ๋Ÿฌ๋ฅผ ๋ชจ๋‘ ๋ฐ›์•„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”๊ฒŒ ์—ญํ• ์ด ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ์š”? (ํ˜„์žฌ์˜ rule.compare๊ณผ getWinningResult๋ฅผ ํ•ฉ์นœ ๋ฉ”์†Œ๋“œ๋ฅผ Rule์—์„œ ์ œ๊ณตํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?)
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
`๋กœ์ง์ƒ ์—†์„ ์ˆ˜๊ฐ€ ์—†๋‹ค` ๋ผ๋Š” ์ƒ๊ฐ์œผ๋กœ `get`์„ ์‚ฌ์šฉํ•ด์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„์š”. ๋‹ค๋งŒ ์š”๊ฒŒ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” `NullPoint`๊ฐ€ ๋‚ ํ…๋ฐ์š”. ์ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด๊ณ  ์–ด๋–ค ์˜๋ฏธ์ธ์ง€ ์ฐพ๊ธฐ๊ฐ€ ์–ด๋ ค์šธ ๊ฒƒ ๊ฐ™์•„์š”. ์š”๋ ‡๊ฒŒ ์• ๋งคํ•œ ๊ฒฝ์šฐ์— ์ €๋Š” orElseThrow๋ฅผ ํ•œ๋‹ค๊ฑฐ๋‚˜, ๋กœ๊ทธ๋ฅผ ํ†ตํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ ์ž์ฒด๊ฐ€ ์ž˜๋ชป๋˜์—ˆ์Œ์„ ์•Œ๋ ค์ฃผ๋Š” ํ˜•ํƒœ๋กœ ๋‚จ๊ธฐ๋Š” ํŽธ์ด์—์š”.
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์š” ๋กœ์ง๋“ค์ด ์ˆœ์„œ์— ๋”ฐ๋ผ ์˜ํ–ฅ์„ ๋ฐ›์„ ๊ฒƒ ๊ฐ™์•„์š”. `์›๋ž˜๋Š” ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๋ฒ„์ŠคํŠธ์ธ ๊ฒฝ์šฐ ํ•ญ์ƒ ํŒจ๋ฐฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š”๋ฐ ๋ฌด์Šน๋ถ€ Enum์„ ๋งจ ์œ„๋กœ ์˜ฌ๋ฆฌ๋ฉด, ๋น„๊ธด๊ฑฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š” ํ˜•์‹`์œผ๋กœ์—ฌ! ๊ทธ๋ ‡๋‹ค๋ฉด ๊ธฐ์กด `Enum์˜ ์ˆœ์„œ๊ฐ€ ์ค‘์š”ํ•˜๋‹ค`๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ๋“œ๋Ÿฌ๋‚ด๊ฑฐ๋‚˜, ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์ค˜์•ผ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ์‹ค์ˆ˜ํ•  ์—ฌ์ง€๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”ใ…Žใ…Ž(์—ฌ๊ธด ๊ฐ€์žฅ ์ค‘์š”ํ•œ ๋กœ์ง์ด๋‹ˆ๊นŒ ๋”๋”์šฑ์ด์š”!)
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์นœ์ ˆํ•œ ์ฃผ์„ ์ข‹๋„ค์š”. ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” participant์—๊ฒŒ ๊ฐ’์„ ๋น„๊ตํ•˜๋Š” ํ˜•ํƒœ๋กœ ๋ฆฌํŒฉํ† ๋งํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ๋น„๊ตํ•˜๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์•„๋‹ˆ๋ผ, ์–ด๋–ค Rule์ธ์ง€๋ฅผ ์ฐพ๋Š”๊ฑฐ์— ๊ฐ€๊น๋„ค์š”. ์š”๊ฒƒ๋„ ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ ์ˆ˜์ •ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,27 @@ +package blackjack.domain.result; + +import lombok.Getter; + +@Getter +public enum WinningResult { + + WIN("์Šน"), + LOSE("ํŒจ"), + TIE("๋ฌด์Šน๋ถ€"); + + private final String result; + + WinningResult(String result) { + this.result = result; + } + + public WinningResult reverse() { + if (this == WIN) { + return LOSE; + } + if (this == LOSE) { + return WIN; + } + return TIE; + } +}
Java
์š”๊ฑฐ ์ œ๊ฐ€ ์ „์— ํ•  ๋•Œ, ์•ˆ ๋๋˜๊ฑด๋ฐ WinningResult๊ฐ€ WinningResult ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ , ๋ฐ˜๋Œ€๋กœ ์„ ์–ธํ•˜๋ฉด ์•ˆ๋˜๋”๋ผ๊ตฌ์š”. ์™œ ์•ˆ๋˜๋Š”์ง€ ๋ฐ”๋กœ ์ดํ•ด๊ฐ€์‹œ๋ฉด Enum์„ ์ž˜ ์ดํ•ดํ•˜๊ณ  ๊ณ„์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹คใ…‹ใ…‹ใ…‹ ```java WIN("์Šน", LOST) // ์š”๋Ÿฐ์‹์œผ๋กœ์—ฌ ```
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•˜๋„ค์š”. ์„œ๋น„์Šค ๊ฐœ๋ฐœ์ž๋กœ์„œ ํ•ญ์ƒ ์ƒ๊ฐํ•ด์•ผ ํ•  ๋ถ€๋ถ„์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. view๋ฅผ ์ œ์™ธํ•œ ํด๋ž˜์Šค๋ณ€์ˆ˜๋“ค์„ ๋กœ์ปฌ๋ณ€์ˆ˜๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Dto ์ด๋ฆ„์„ DrawCardRequestDto๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  ํŒ๋‹จ๋กœ์ง์„ Dto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค. Dto๊ฐ€ ๊ฐ€์ง„ ๋ฐ์ดํ„ฐ๋งŒ์„ ์ด์šฉํ•œ ๊ฐ„๋‹จํ•œ ๋กœ์ง์€ Dto์—์„œ ์ฒ˜๋ฆฌํ•ด๋„ ๋œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. Dto ์ด๋ฆ„์„ ๋ฐ›์•„์˜จ ๊ฒƒ์ธ์ง€, ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ธ์ง€์— ๋”ฐ๋ผ ํ†ต์ผํ•˜๋ฉด ์ผ๊ด€์„ฑ์ด ์žˆ์–ด ํ—ท๊ฐˆ๋ฆด ์ผ์ด ์—†์–ด์„œ ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
๋กœ์ง์„ DrawCardRequestDto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
๋„ต ๊ทธ๋ ‡์Šต๋‹ˆ๋‹ค.