2011. 5. 27. 13:22

자바(Java)의 `Random 클래스`로 구현한 숫자 맞추기 야구 게임

예전에 C 언어로 만들었었던 숫자 맞추기 일명 야구 게임의 코딩 내용을 그대로 가져 와서 자바의 형식으로 변형시킨 프로그램. 난수를 발생시키는 Random 클래스와 콘솔에서 값을 입력받는 Scanner 클래스에 IOExeption을 사용했는데 이걸 import하게 되면 main() 메써드에서 반드시 throws IOException을 명시해야 합니다.

  1: import java.util.* ; 
  2: import java.io.IOException ; 
  3:  
  4: public class NumberGuessGame { 
  5:  public static void main(String[] args) throws IOException { 
  6:   Random random = new Random() ; 
  7:   Scanner input = new Scanner(System.in) ; 
  8:  
  9:   int i = 0, tryCount, gameCount = 0; 
 10:   int strike = 0, ball = 0 ; 
 11:   int scoreCheck = 0, totalGameScore = 0, again ; 
 12:  
 13:    int[] problem= new int[3] ; 
 14:    int[] guess = new int[3] ; //problem:컴퓨터가 만든 숫자, guess:본인이 생각한 숫자 
 15:  
 16:   double gameAverage = 0.0 ;  // 평균 점수를 내기 위한 변수 
 17:  
 18:   System.out.println("\n이건 야구 게임이야. 내가 생각한 숫자를 맞추는 거지.\n") ; 
 19:   System.out.println("1~9까지 세자리 숫자 불러봐. 기회는 11번. 0하고 중복은 안돼~\n") ; 
 20:  
 21:   // 난수 발생. 0~9까지 중복없는 숫자 3개 생성 
 22:   do { 
 23:    problem[0] = random.nextInt(10) ; 
 24:        if(problem[0] == 0) { 
 25:            problem[0] += 1 ; 
 26:        } 
 27:          
 28:    do { 
 29:     problem[1] = random.nextInt(10) ; 
 30:         if(problem[1] == 0) { 
 31:             problem[1] += 1 ; 
 32:         } 
 33:    } while (problem[1] == problem[0]); 
 34:              
 35:    do { 
 36:     problem[2] = random.nextInt(10) ; 
 37:         if(problem[2] == 0) { 
 38:             problem[2] += 1 ; 
 39:         } 
 40:     } while (problem[2] == problem[0] || problem[2] == problem[1]) ;     
 41:  
 42:    //시도 횟수를 초기화 한다. 
 43:    tryCount = 0 ; 
 44:  
 45:    gameCount++ ; 
 46:  
 47:    do { 
 48:     tryCount++ ; 
 49:  
 50:     do { 
 51:      System.out.printf("\n게임회수 : %d, 시도회수 : %d ->  
 52:                            생각한 3자리 숫자 불러봐 : ", gameCount , tryCount) ; 
 53:  
 54:      //숫자 3개를 입력받는다. 
 55:      guess[0] = input.nextInt() ; 
 56:      guess[1] = input.nextInt() ; 
 57:      guess[2] = input.nextInt() ; 
 58:      
 59:      if (guess[0] == 0 || guess[1] == 0 || guess[2] == 0) 
 60:       System.out.print("\n0은 안된다고 했잖아요. 다시!") ; 
 61:  
 62:      else if (guess[0] == guess[1] || guess[1] == guess[2] ||  
 63:               guess[2] == guess[0]) 
 64:       System.out.print("\n중복 안된다니깐요. 다시!") ; 
 65:  
 66:      else if (guess[0] > 9 || guess[1] > 9 || guess[2] > 9) 
 67:       System.out.print("\n1~9까지랬잖아요. 다시!") ; 
 68:     } while (guess[0] == guess[1] || guess[1] == guess[2] ||  
 69:              guess[2] == guess[0] || guess[0] == 0 || guess[1] == 0 ||  
 70:              guess[2] == 0 || guess[0] > 9 || guess[0] > 9 || guess[0] > 9); 
 71:  
 72:     i = strike = ball = 0 ; 
 73:  
 74:     //스트라이크와 볼을 판별하는 알고리즘 부분. 
 75:     while (i < 3) { 
 76:      if(guess[i] == problem[i]) strike++ ; 
 77:      else if (guess[(i + 1) % 3] == problem[i]) ball++ ; 
 78:      else if (guess[(i + 2) % 3] == problem[i]) ball++ ; 
 79:      i++ ; 
 80:     } 
 81:  
 82:     //플레이어에게 알려준다. 맨 위 do~while 문의 끝이다. 
 83:     System.out.printf("\n[%d Strike %d Ball]", strike, ball) ; 
 84:    } while (strike < 3 && tryCount < 11) ; 
 85:  
 86:    //시도횟수에 따라 성적이 나온다. 
 87:    System.out.print("\n\n") ; 
 88:  
 89:    if (tryCount <= 2) { 
 90:      System.out.print("대단해요~~ !!") ; 
 91:    } 
 92:  
 93:    else if (tryCount <= 5) { 
 94:      System.out.print("아주 좋아요 !")  ; 
 95:    } 
 96:  
 97:    else if (tryCount <= 9) { 
 98:     System.out.print("굿~.") ; 
 99:    } 
100:  
101:    else if (strike == 3) { 
102:     System.out.print("스트라이크 3개") ; 
103:    } 
104:  
105:    //뭐, 아래는 별 설명이 없어도... 
106:    if (strike == 3) { 
107:     System.out.printf("\n자긴 내가 생각한 수를 %d번 만에 맞췄어, 베이비~ 쪽\n",  
108:                            tryCount) ; 
109:    } 
110:     
111:    else { 
112:     System.out.print("오, 예~ 자긴 내가 생각한 수를 맞추지 못했어, 내가 이겼어.\n") ; 
113:     System.out.printf("내가 생각한 수는 %d %d %d야.\n",  
114:                                 problem[0], problem[1], problem[2]) ; 
115:     System.out.print("자기 ..... 못맞췄구나~ 이걸 어째...원래는 0점이지만,\n") ; 
116:     System.out.print("그래도 내가 인정이 있자나~, 기본점수는 줄께 너무 걱정마....\n") ;           
117:    } 
118:  
119:    totalGameScore += scoreCheck = 100 - --tryCount * 8 ; //.... ??  걍~ 패쑤~~.   
120:  
121:    System.out.printf("자기 점수는 %d점이야. 우~\n", tryCount) ; 
122:    System.out.print("\n게임 또 할꺼야 자기? (Y/N) ") ; 
123:      
124:    again = System.in.read() ; 
125:   } while (again != 'n') ; 
126:  
127:   gameAverage = totalGameScore / gameCount ; 
128:  
129:   System.out.printf("\n\n자기 평균점수 나왔다. %.1f점이네.\n", gameAverage) ; 
130:   System.out.println("자기 내 생각 많이 하고 행복해~.") ; 
131:  } 
132: }

C 언어로 만든 숫자 맞추기 일명 야구게임