Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java baseball game 김태근 #5

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat : 야구게임 구현
geunskoo committed Oct 3, 2022
commit 775aae95d8cac15f2d9da1267a031979a34dc70a
Binary file not shown.
Binary file not shown.
Binary file modified java_baseball_game/.gradle/7.4/fileHashes/fileHashes.bin
Binary file not shown.
Binary file modified java_baseball_game/.gradle/7.4/fileHashes/fileHashes.lock
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified java_baseball_game/.gradle/file-system.probe
Binary file not shown.
2 changes: 1 addition & 1 deletion java_baseball_game/.idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions java_baseball_game/.idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion java_baseball_game/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified java_baseball_game/build/classes/java/main/com/taegeun/Main.class
Binary file not shown.
Binary file modified java_baseball_game/build/classes/java/main/com/taegeun/Player.class
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
18 changes: 18 additions & 0 deletions java_baseball_game/src/main/java/com/taegeun/Computer.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
package com.taegeun;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Computer {
List<Integer> comNum = new ArrayList<>();
public List<Integer> randNum() {
int num;
Random random = new Random();

while (true) {
if (comNum.size() == 3) break;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이처럼 종료 조건이 명확할 때는, true 대신 종료 조건을 명시하는 것이 가능하지 않을까요?

num = random.nextInt(9)+1;
if (!comNum.contains(num)){
comNum.add(num);
}
}
return comNum;
}
}
58 changes: 58 additions & 0 deletions java_baseball_game/src/main/java/com/taegeun/GameEngine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.taegeun;

import java.util.ArrayList;
import java.util.List;

public class GameEngine {

private List<Integer> playerNum = new ArrayList<>();
private List<Integer> comNum = new ArrayList<>();
public void setComNum(List<Integer> comNum) {
this.comNum = comNum;
}
public void setPlayerNum(List<Integer> playerNum){
this.playerNum = playerNum;
}

public int checkStrike() {
int total=0;
for (int i=0; i<playerNum.size(); i++){
if (playerNum.get(i) == comNum.get(i)){
Copy link
Contributor

@shkisme shkisme Oct 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

== 대신에 값 자체를 비교하는 equals() 메서드를 사용해보는 것은 어떨까요?
아래 블로그 주소의 관련 글을 참고해보세요!
https://velog.io/@sorzzzzy/TILJava-equals-vs

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오우.. 링크까지 감사합니다 !!
주어진 메서드를 더 잘 활용하는 연습을 해야겠습니다😅

total++;
}
}
return total;
}
public int checkBall() {
int total=0;
for (int i=0; i<playerNum.size(); i++){
if (playerNum.get(i) != comNum.get(i) && comNum.contains(playerNum.get(i))){
total++;
}
}
return total;
}
public boolean continueGame(){
if (checkStrike()!=3){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

contineGame 메서드는 아래와 같이 코드를 작성할 수 있을 것 같습니다!

public boolean continueGame(){
        return checkStrike() != 3;
    }

return true;
}
else{
return false;
}
}
public void printScore() {
int ball = checkBall();
int strike = checkStrike();
if (ball !=0){
System.out.print(ball + "볼 ");
}
if (strike !=0){
System.out.print(strike + "스트라이크");
}
if (ball==0 && strike==0){
System.out.print("낫싱");
}
System.out.println();
}
}

54 changes: 52 additions & 2 deletions java_baseball_game/src/main/java/com/taegeun/GameManager.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,56 @@
package com.taegeun;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GameManager {
Player player = new Player();
Computer com = new Computer();
private List<Integer> playerNum = new ArrayList<>();
private List<Integer> comNum = new ArrayList<>();
public void generateGame(){
Computer com = new Computer();
// 컴퓨터 숫자 생성.
comNum = com.randNum();
}
public void gameStart(){
GameEngine gameEngine = new GameEngine();
gameEngine.setComNum(comNum);

while(true){
//플레이어 숫자 입력
Player player = new Player();
try{
playerNum = player.inputNum();
}catch (Exception e){
System.out.println("잘못된 입력입니다.");
System.exit(0);
}

gameEngine.setPlayerNum(playerNum);
gameEngine.printScore();
if (!gameEngine.continueGame()) {
System.out.println("3개의 숫자를 모두 맞히셨습니다! 게임 종료");
break;
}
}
}
public boolean resumeGame(){
System.out.println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();

switch (choice) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 switch 문을 사용하신 이유가 있을까요?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자료구조 수업에서 switch구문이 확장성면에서 좋다고해서 수정해보았습니다. 하하😋

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

생각해보니, 확장의 여지가 없는 것 같기도 합니다🥲

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조건이 여러가지인 경우에는, (아니면 조건에 따라서 다른 종류의 객체를 반환해야 할때...) switch 문이 여러개의 if-else문 보다 깔끔하고 확장성 있지만, 이처럼 조건식이 몇 가지 없을 때는 단순하게 표현하는 것도 좋다고 생각합니다!
물론 이건 개인적인 성향이니 참고만 하시면 좋을 것 같아요!😊

case 1:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이런 경우에는 Enum을 활용해서 코드를 작성하시면 좋습니다! 딱 읽었을 때, 1 이 어떤 의미인지 한눈에 파악하기 어렵기 때문입니다!
자주 사용하는 중요한 상수들은 Enum으로 표현해보세요! ㅎㅎ

public enum GameSignal {
  RESTART(1), END(2);

  int signal;

  GameSignal(int signal) {
    this.signal = signal;
  }
  // add getter...
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하...! enum을 통해서 와... 신기합니다
감사합니다 수정하겠습니다.

return true;
default:
return false;
}

}
public List<Integer> getPlayerNum(){
return playerNum;
}
public List<Integer> getComNum(){
return comNum;
}
}
21 changes: 19 additions & 2 deletions java_baseball_game/src/main/java/com/taegeun/Main.java
Original file line number Diff line number Diff line change
@@ -2,7 +2,24 @@

public class Main {
public static void main(String[] args){
GameManager gameManager = new GameManager();
gameManager.start();
while (true){
GameManager gameManager = new GameManager();

gameManager.generateGame();
System.out.println(gameManager.getComNum());
gameManager.gameStart();

if (!gameManager.resumeGame()){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resumeGame() 메서드는 boolean 타입을 반환하고 있습니다.
이런 경우에는 is~ ( ex. isResumeGame)과 같이 네이밍을 하는 것은 어떨까요?
아래는 자바 메서드 네이밍에 관해 잘 작성되있는 글입니다!
https://tecoble.techcourse.co.kr/post/2020-04-26-Method-Naming/

네이밍이 진짜 제일 힘든거 같습니다...😂

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메서드 네이밍에 조금 더 신경써야함을 크게 느꼈습니다...! 😨
링크 감사합니다!

break;
}

}



Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

소개해드렸던 formatter를 사용해보시는게 좋을 것 같습니다! 포메터 적용을 하지 않으면, 수정사항이 띄어쓰기까지 반영되면서 나중에 변경사항을 확인할 때 불편하다는 단점이 있습니다.
https://withhamit.tistory.com/411

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵!! 수정해서 반영하겠습니다.!!





}
}
18 changes: 13 additions & 5 deletions java_baseball_game/src/main/java/com/taegeun/Player.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package com.taegeun;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Player {
int myNum;
public int inputNum(){
List<Integer> myNum = new ArrayList<>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

긴 이름에 대한 거부감이 있으시겠지만, 필드나 메서드 네이밍을 할 때는 축약 없이 하면 좋을 것 같습니다! myNum 대신 myNumberList 이렇게 네이밍을 하시면 좋을 것 같습니다!

public List<Integer> inputNum(){
int num;
Scanner sc = new Scanner(System.in);
System.out.print("숫자를 입력해주세요 : ");
myNum = sc.nextInt();
num = sc.nextInt();

if (Integer.toString(myNum).length() != 3){
throw new IllegalArgumentException("3자리수가 아닙니다.");
myNum.add((num/100)%10);
myNum.add((num/10)%10);
myNum.add(num%10);

if (myNum.get(0) == 0) {

throw new IllegalArgumentException("3자리 수를 입력하세요!");
}

return myNum;