JAVA 기초 정리/JAVA

7. 연습문제 : 행맨 게임

SummerEda 2019. 12. 19. 10:13
연습 문제

/*

행맨(Hang Man)

 *

 * 게임방법:

 *                   1. 임의로 영단어를 선택한 후 자릿수를 표시한다. ex> START => _ _ _ _ _

*                   2. 입력 가능한 횟수를 설정한다. (횟수 설정 가능 범위 validation 체크)

*                   3. 각각의 자리에 들어갈 알파벳들을 하나씩 입력한다. (알파벳 설정 가능 범위 validation 체크)

*                   4. 입력한 알파벳이 단어에 존재하지 않을 경우 입력 가능한 횟수가 줄어들고,

 *                        존재할 경우 횟수는 줄어들지 않고 빈칸이 채워진다. ex> START => _ T _ _ T

*                   5. 이전에 입력했던 값을 다시 입력했을경우 중복 validation 체크

*                   6. 입력 가능한 횟수 안에 모든 알파벳을 찾아내면 성공그렇치 않으면 실패

 

첨부 자료를 이용하세요
  • 랜덤 알파벳 들어가있는 파일

word.txt
0.22MB

 

풀이
import java.util.*;

import java.io.*;



public class hangexample {

	   int HIDDENCHAR; // 숨기는 글자 개수를 사용자에게서 입력 받음

	   StringBuffer hiddenWord; // 숨긴 글자를 가진 단어

	   String newWord; // 게임을 위해 선정된 단어

	   Scanner scanner; // 키 입력

	   int failCount; // 틀린 횟수

	   

	   public hangexample() { 

	      scanner = new Scanner(System.in);

	   }





	   public void run() {

	      System.out.println("행맨(Hang Man) 게임 시작");



	      Words words = new Words("D:\\workspace\\java\\word.txt"); // 단어 선택하는 객체 생성      

	      while(true) {

	         while (true) {

	            newWord = words.getRandomWord(); // 랜덤한 단어 선택

	               break;

	         }

	         if(newWord == null) break; // 단어 선택에 문제가 있는 경우 프로그램 종료

	         makeHidden(); // 글자를 숨긴 단어 만들기

	         go(); // 게임 진행

//	            break;

	      }

	   }

	   



	   void makeHidden()

	   {

	      hiddenWord = new StringBuffer(newWord);

	      Random r = new Random();

	      

	      for(int k=0; k<100; k++) {

	         int index = r.nextInt(newWord.length());

	         char c = newWord.charAt(index);

	         for(int i=0; i<newWord.length(); i++) {

	            if(hiddenWord.charAt(i) == c)

	               hiddenWord.setCharAt(i,'-');

	         }

	      }

	   }

	   

	   // 5 번 틀리면 실패



	   void go() {

	      failCount=0;

	      char key;

	      do {

	         if(failCount == 5) {

	            System.out.println("실패 하였습니다.");

	            System.out.println();

	             break;

				}

		     System.out.println(newWord + "=>");

	         System.out.println(hiddenWord);

	         System.out.print(">>");

	         String text = scanner.next();

	         key =  text.charAt(0);

	         

	      }while(!complete(key));

	      

       	if(failCount < 5) {

	       System.out.println("성공 하였습니다.");	

           System.out.println();

       	}

	      

	   }

	   

	   // 사용자가 입력한 문자 key가 숨긴 글자와 일치하는지 검사하고 일치하면 true를 리턴한다.

	   // 그리고 나서 hiddenWord의 '-'문자를 key 문자로 변경

	   boolean complete(char key) {

	      boolean hit = false;

	      for(int i=0; i<newWord.length(); i++) {

	         if(hiddenWord.charAt(i) == '-' && newWord.charAt(i) == key) {

	            hiddenWord.setCharAt(i, key);

	            hit = true;

	         }

	      }



	      if(!hit)

	         failCount++;



	      for(int i=0; i<newWord.length(); i++) {

	         if(hiddenWord.charAt(i) == '-')

	            return false;

	      }

	      return true;

	   }



	   public static void main(String[] args) {

		   hangexample app = new hangexample();

	      app.run();

	   }



	}



	// words.txt 파일을 읽고 파일에서 랜덤하게 단어를 추출하는 클래스

	class Words {

	   final int WORDMAX = 20000; // words.txt파일에 들어 있는 총 단어의 개수

	   private String fileName; // 단어 파일 이름. 현재는 words.txt

	   private Random r = new Random(); // 난수 발생기

	   

	   public Words(String fileName) {

	      this.fileName = fileName;

	   }

	   

	   public String getRandomWord() {

	      // 파일을 읽기 위한 BufferedReader 객체를 생성한다.

	      BufferedReader in = null;      

	      try {

	         // 파일을 열고 파일을 읽기 위한 BufferedReader 객체 생성

	         in = new BufferedReader(new FileReader(fileName));

	      }

	      catch(FileNotFoundException e) {

	         System.out.println("file not found error");

	         System.exit(0);

	      }

	      int n = r.nextInt(WORDMAX); // 랜덤한 라인 번호 생성. n 번째 단어를 게임에 사용

	      return readWord(in, n); // in 파일에서 n 번째 라인의 단어를 읽어서 리턴

	   }

	   

	   // in 파일에서 n 번째 라인의 단어를 읽어 리턴하는 메소드

	   private String readWord(BufferedReader in, int n) {

	      String line=null; // 한 라인을 저장할 문자열 객체. 한 라인에는 하나의 단어만 있음

	        try {

	         while (n>0) {

	            line = in.readLine(); // 파일에서 한 라인(한 단어)를 읽는다.

	            if(line == null) // eof를 만나면 문제 발생. 루프 종료

	               break;

	            n--;

	         }

	      } catch (IOException e) {

	         System.exit(0);

	      }

	      return line; // n 번째 라인의 단어 리턴

	   }

	}

 

결과