본문 바로가기
java/예제&실습

[명품자바] 8장 오픈챌린지

by unhyepnhj 2024. 6. 25.

행맨 게임 만들기

 

25143개의 영단어를 가진 words.txt 파일을 읽고(명품자바 학습자료 사이트에서 다운 가능) 사용자 모르게 단어 하나를 선택

이 단어에서 2개의 글자를 숨긴 다음 화면에 출력하여 사용자가 단어를 맞추게 하는 게임

한 단어에 대해 5번 틀리면 프로그램 종료

 

words.txt 파일의 모든 단어를 읽어 다음의 스트링 벡터에 저장

words.txt 파일에는 한 라인에 하나의 영어 단어가 들어 있으며, Scanner를 이용하여 한 라인씩 읽어 저장

Vector<String> wordVector = new Vector<String>();

Scanner scanner = new Scanner(new FileReader("words.txt"));
while(scanner.hasNext()){
	String word = scanner.nextLine();
    wordVector.add(word);
}

이걸 사용하라네요

 

Word 클래스

package openChallenge08;
import java.util.*;
import java.io.*;

public class Word {
	Random r=new Random();
	
	//words.txt에서 단어 읽고 벡터에 저장
	public void makeVector(Vector<String> wordVector) {
		try {
			Scanner scanner=new Scanner(new FileReader("c:\\Temp\\words.txt"));
			while(scanner.hasNext()) {
				String word=scanner.nextLine();
				wordVector.add(word);
			}
		}
		catch(IOException e) {
			System.out.println("파일을 찾을 수 없습니다.");
		}
	}
	
	//단어 선택
	public String chooseWord(Vector<String> wordVector) {
		int vIndex=r.nextInt(wordVector.size());
		
		return wordVector.get(vIndex);	//vIndex번째의 요소를 리턴
	}
	
	//빈칸 만들기
	public String makeBlank(String word, int n1, int n2) {
		StringBuffer str=new StringBuffer(word);
		word=str.replace(n1, n1+1, "_").toString();
		word=str.replace(n2, n2+1, "_").toString();

		return word;
	}
}

makeBlank() 메소드에 StringBuilder를 사용해도 된다(조금 더 간단할 듯)

StringBuilder가 교재에 나온 적이 없는 것 같아 StringBuffer를 사용했다

public String makeBlank(String word, int n1, int n2) {
		StringBuilder str = new StringBuilder(word);
		str.setCharAt(n1, '_');
		str.setCharAt(n2, '_');
		return str.toString();
}

StringBuilder 사용하면 이렇게 쓸 수 있음

 

Game 클래스

package openChallenge08;
import java.util.*;

public class Game {
	String originalWord;
	String wordWithBlanks;
	boolean isCorrect;
	int errorCount;
	
	public Game(String originalWord, String wordWithBlanks, int n1, int n2) {
		this.originalWord=originalWord;
		this.wordWithBlanks=wordWithBlanks;
		this.isCorrect=false;
		this.errorCount=0;
	}
	
	public String compare(String originalWord, String wordWithBlanks, String input, int n1, int n2) {;
		StringBuffer sb=new StringBuffer(wordWithBlanks);
		
		if(originalWord.charAt(n1)==input.charAt(0)) 
			wordWithBlanks=sb.replace(n1, n1+1, input).toString();
		else if(originalWord.charAt(n2)==input.charAt(0))
			wordWithBlanks=sb.replace(n2, n2+1, input).toString();
		else
			errorCount++;	//오류

		return wordWithBlanks;
	}
	
	public boolean isCorrect(String revisedWord) {
		
		if(revisedWord.contains("_")==false) isCorrect=true;	//문자열에 더 이상 빈칸이 없을 경우
		return isCorrect;
	}
	
	public int getErrorCount() {
		return errorCount;
	}
}

 

Main 클래스

package openChallenge08;
import java.io.*;
import java.util.*;

public class Main {
	
	public void run() {
		Vector<String> wordVector=new Vector<>();		//단어 저장 벡터
		Scanner scanner=new Scanner(System.in);
		Word w=new Word();
		
		while(true){	
			int n1, n2;
			while(true) {
			
				w.makeVector(wordVector);
				String originalWord=w.chooseWord(wordVector);
				System.out.println("지금부터 단어 맞추기 게임을 시작합니다.");
				do {
					n1=(int)(Math.random()*originalWord.length());
					n2=(int)(Math.random()*originalWord.length());
				}while(n1==n2);
				//빈칸 인덱스
				
				String wordWithBlank = w.makeBlank(originalWord, n1, n2);	//빈칸 뚫기
				String revisedWord=wordWithBlank;	//시작 전
				Game g=new Game(originalWord, wordWithBlank, n1, n2);
				
				while(true) {
					if(g.getErrorCount()==5) {	//실패
						System.out.println("5번 실패하였습니다.");
						System.out.println("정답: "+originalWord);
						break;
					}
					else if(revisedWord.equals(originalWord)){	//정답
						System.out.println("정답입니다.");
						break;
					}
					else {	//맞추는 중
						System.out.println(revisedWord);	//문제 출력
						
						System.out.print(">> ");
						String input=scanner.next();

						revisedWord=g.compare(originalWord, revisedWord, input, n1, n2);	//빈칸 비교하고 난 문자열
					}
				}//답 입력 반복문
				System.out.print("Next(y/n)?>> ");
				String ifContinue=scanner.next();
				if(ifContinue.equals("n")) {
					System.out.println("종료합니다.");
					return;
				}
				else
					break;
			}//문제 출력 반복문
		}
	}
	public static void main(String[] args) {
		Main main=new Main();
		main.run();
	}
}

 

>> 실행

'java > 예제&실습' 카테고리의 다른 글

[명품자바] 7장 실습문제(5~9)  (0) 2024.07.01
[명품자바] 6장 실습문제  (0) 2024.06.27
[명품자바] 7장 오픈챌린지  (0) 2024.06.20
[명품자바] 6장 오픈챌린지  (0) 2024.06.19
[명품자바] 5장 오픈챌린지  (0) 2024.06.19