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 | ์ฝ๋์ ๊ฐ๊ฒฐํจ์ ์ํด ์ข์ ๋ฐฉ๋ฒ์ด ๋ ์๋ ์์ง๋ง, ํ ํ์์๋ ํ๋์ ๋ณ๊ฒฝ๋ง์ด ์ผ์ด๋์ผ ํ๋ค๋ ๋ง์ ๋ค์ ์ ์ด ์๋ ๊ฒ ๊ฐ์์!
 |
@@ -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 | 
๊นํ๋ธ์์ `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 | ๋ต ๊ทธ๋ ์ต๋๋ค. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.