[문제] 단어를 주어진 기회 안에 맞추는 게임을 만들어보세요
1. 컴퓨터가 랜덤으로 영어단어를 선택합니다.
- a. 영어단어의 자리수를 알려줍니다.
- 랜덤한 영어단어를 선택할 수 있게끔 randomText()라는 함수 생성.
public String randomText(){
Random random = new Random();
String[] list = { "airplane",
"apple", "arm", "bakery", "banana", "bank", "bean", "belt", "bicycle", "biography", "blackboard", "boat", "bowl", "broccoli", "bus", "car", "carrot", "chair", "cherry", "cinema",
"class", "classroom", "cloud", "coat", "cucumber", "desk", "dictionary", "dress", "ear", "eye", "fog",
"foot", "fork", "fruits", "hail", "hand", "head", "helicopter", "hospital", "ice", "jacket", "kettle", "knife", "leg", "lettuce", "library",
"magazine", "mango", "melon", "motorcycle", "mouth", "newspaper", "nose", "notebook", "novel",
"onion", "orange", "peach", "pharmacy", "pineapple", "plate", "pot", "potato", "rain", "shirt", "shoe", "shop", "sink", "skateboard", "ski", "skirt", "sky", "snow", "sock",
"spinach", "spoon", "stationary", "stomach", "strawberry", "student", "sun", "supermarket", "sweater", "teacher", "thunderstorm", "tomato", "trousers", "truck", "vegetables", "vehicles", "watermelon", "wind"};
// 랜덤으로 단어 하나 선택
String correct = list[random.nextInt(list.length)];
// 자리 수 출력
System.out.println("_ ".repeat(correct.length()));
return correct;
}
2. 사용자는 A 부터 Z 까지의 알파벳 중에서 하나를 입력합니다.
- a,b,c 모두 가려내는 함수 하나를 만들엇다.
a. 입력값이 A-Z 사이의 알파벳이 아니라면 다시 입력을 받습니다.
b. 입력값이 한 글자가 아니라면 다시 입력을 받습니다.
c. 이미 입력했던 알파벳이라면 다시 입력을 받습니다.
public int checkInput(String word, ArrayList<String> stackWord){
// 글자가 하나면,
if (word.length() != 1) {
System.out.println("글자수가 하나입니다.");
return 1;
}
// 이미 받았던 글자면, 다시 재입력하게.
else if (stackWord.contains(word)) {
System.out.println("이미 입력하신 글자입니다.");
return 1;
}
// 문자만을 받을 것 > 근데 이게 의미가 있나 싶다.. ?
else if (!Character.isLetter(word.charAt(0))){
System.out.println("문자가 아닙니다.");
return 1;
}
// 알파벳이어야 함 !
else if ((word.charAt(0) >= 'a' && word.charAt(0) <= 'z')||(word.charAt(0) >= 'A' && word.charAt(0) <= 'Z')){
return 0;
}
else{
System.out.println("알파벳이 아닙니다.");
return 1;}
}
- d,e 는 아래와 같은 if문을 통해서 설정했다.
d. 입력값이 정답에 포함된 알파벳일 경우 해당 알파벳이 들어간 자리를 전부 보여주고, 다시 입력을 받습니다.
e. 입력값이 정답에 포함되지 않은 알파벳일 경우 기회가 하나 차감되고, 다시 입력을 받습니다.
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Prob03 inst= new Prob03();
// 1. 랜덤한 텍스트 주기.
String rt = inst.randomText();
char[] rtArray = rt.toCharArray();
int count = 0;
while(true){
System.out.println("**********************");
System.out.println("입력값을 입력해주세요 : ");
// 2. 입력 값 받기.
String word = scanner.nextLine();
// 해당 입력이 정상인지 여부를 0과 1로 받기.
int check = inst.checkInput(word,stackWord);
// 입력값이 정상이면, 입력받은 문자열이 어디에 있는지 보여주어야 함.
if (check == 0) {
// 혹시 알파벳이 대문자일 경우를 대비하여, 모두 소문자로 바꾸어 줄 것이다.
String lowerWord= word.toLowerCase();
// 입력받은 글자이기 때문에, 입력받은 stackWord에 넣어준다.
stackWord.add(lowerWord.trim());
if (rt.contains(lowerWord)) { // 정답이라면 해당 문자열 index를 공개.
System.out.printf("%s 가 들어가있습니다. 위치를 알려드리겠습니다.\n", lowerWord);
// 들어갈 경우에는 indexOf를 통해서 문자열 index위치를 반환해야함.
for (int i=0; i < rt.length(); i++) {
if(rtArray[i] == lowerWord.charAt(0)){
System.out.print(lowerWord);
stackCorrect.add(lowerWord);
}
else{
System.out.print("-");
}
}
System.out.println("\n");
}
// 오답이다. -.
else {
count ++;
System.out.println("틀렸습니다. 목숨이 하나 차감됩니다.");
System.out.printf("남은 기회: %d \n", 9-count);
}
}
// 아니면 다시 입력하라 하기
else {
System.out.println("다시입력하세요.");
}
3.사용자가 9번 틀리면 게임오버됩니다.
if (count >= 9) {
System.out.println("** 게임오버 **");
break;
}
4.게임오버 되기 전에 영어단어의 모든 자리를 알아내면 플레이어의 승리입니다.
if(stackCorrect.size()==rt.length()) {
System.out.println("** 모든 단어를 맞추었습니다. **");
System.out.print("단어:");
System.out.println(rt);
break;
}
이런식으로 설정했다.
전체 코드
import java.util.*;
public class Prob03 {
// 입력 받은 아이들.
static ArrayList<String> stackCorrect = new ArrayList<>();
// 입력 받은 정답인 아이들.
static ArrayList<String> stackWord = new ArrayList<>();
// 랜덤한 글자 생성
public String randomText(){
Random random = new Random();
String[] list = { "airplane",
"apple", "arm", "bakery", "banana", "bank", "bean", "belt", "bicycle", "biography", "blackboard", "boat", "bowl", "broccoli", "bus", "car", "carrot", "chair", "cherry", "cinema",
"class", "classroom", "cloud", "coat", "cucumber", "desk", "dictionary", "dress", "ear", "eye", "fog",
"foot", "fork", "fruits", "hail", "hand", "head", "helicopter", "hospital", "ice", "jacket", "kettle", "knife", "leg", "lettuce", "library",
"magazine", "mango", "melon", "motorcycle", "mouth", "newspaper", "nose", "notebook", "novel",
"onion", "orange", "peach", "pharmacy", "pineapple", "plate", "pot", "potato", "rain", "shirt", "shoe", "shop", "sink", "skateboard", "ski", "skirt", "sky", "snow", "sock",
"spinach", "spoon", "stationary", "stomach", "strawberry", "student", "sun", "supermarket", "sweater", "teacher", "thunderstorm", "tomato", "trousers", "truck", "vegetables", "vehicles", "watermelon", "wind"};
// 랜덤으로 단어 하나 선택
String correct = list[random.nextInt(list.length)];
// 자리 수 출력
System.out.println("_ ".repeat(correct.length()));
return correct;
}
// 입력 받은 알파벳이 정상인지 확인
public int checkInput(String word, ArrayList<String> stackWord){
// 글자가 하나면,
if (word.length() != 1) {
System.out.println("글자수가 하나입니다.");
return 1;
}
// 이미 받았던 글자면, 다시 재입력하게.
else if (stackWord.contains(word)) {
System.out.println("이미 입력하신 글자입니다.");
return 1;
}
// 문자만을 받을 것 > 근데 이게 의미가 있나 싶다.. ?
else if (!Character.isLetter(word.charAt(0))){
System.out.println("문자가 아닙니다.");
return 1;
}
// 알파벳이어야 함 !
else if ((word.charAt(0) >= 'a' && word.charAt(0) <= 'z')||(word.charAt(0) >= 'A' && word.charAt(0) <= 'Z')){
return 0;
}
else{
System.out.println("알파벳이 아닙니다.");
return 1;}
}
//
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Prob03 inst= new Prob03();
// 1. 랜덤한 텍스트 주기.
String rt = inst.randomText();
char[] rtArray = rt.toCharArray();
int count = 0;
while(true){
System.out.println("**********************");
System.out.println("입력값을 입력해주세요 : ");
// 2. 입력 값 받기.
String word = scanner.nextLine();
// 해당 입력이 정상인지 여부를 0과 1로 받기.
int check = inst.checkInput(word,stackWord);
// 입력값이 정상이면, 입력받은 문자열이 어디에 있는지 보여주어야 함.
if (check == 0) {
// 혹시 알파벳이 대문자일 경우를 대비하여, 모두 소문자로 바꾸어 줄 것이다.
String lowerWord= word.toLowerCase();
// 입력받은 글자이기 때문에, 입력받은 stackWord에 넣어준다.
stackWord.add(lowerWord.trim());
if (rt.contains(lowerWord)) { // 정답이라면 해당 문자열 index를 공개.
System.out.printf("%s 가 들어가있습니다. 위치를 알려드리겠습니다.\n", lowerWord);
// 들어갈 경우에는 indexOf를 통해서 문자열 index위치를 반환해야함.
for (int i=0; i < rt.length(); i++) {
if(rtArray[i] == lowerWord.charAt(0)){
System.out.print(lowerWord);
stackCorrect.add(lowerWord);
}
else{
System.out.print("-");
}
}
System.out.println("\n");
}
// 오답이다. -.
else {
count ++;
System.out.println("틀렸습니다. 목숨이 하나 차감됩니다.");
System.out.printf("남은 기회: %d \n", 9-count);
}
}
// 아니면 다시 입력하라 하기
else {
System.out.println("다시입력하세요.");
}
if(stackCorrect.size()==rt.length()) {
System.out.println("** 모든 단어를 맞추었습니다. **");
System.out.print("단어:");
System.out.println(rt);
break;
}
if (count >= 9) {
System.out.println("** 게임오버 **");
break;
}
}
}
}
실행창
_ _ _
**********************
입력값을 입력해주세요 :
a
a 가 들어가있습니다. 위치를 알려드리겠습니다.
-a-
**********************
입력값을 입력해주세요 :
c
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 8
**********************
입력값을 입력해주세요 :
n
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 7
**********************
입력값을 입력해주세요 :
w
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 6
**********************
입력값을 입력해주세요 :
c
이미 입력하신 글자입니다.
다시입력하세요.
**********************
입력값을 입력해주세요 :
x
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 5
**********************
입력값을 입력해주세요 :
z
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 4
**********************
입력값을 입력해주세요 :
p
틀렸습니다. 목숨이 하나 차감됩니다.
남은 기회: 3
**********************
입력값을 입력해주세요 :
e
e 가 들어가있습니다. 위치를 알려드리겠습니다.
e--
**********************
입력값을 입력해주세요 :
r
r 가 들어가있습니다. 위치를 알려드리겠습니다.
--r
** 모든 단어를 맞추었습니다. **
단어:ear
Process finished with exit code 0
'백엔드 부트캠프[사전캠프] > 문제풀이' 카테고리의 다른 글
[SQL 달리기반 레벨 2] 📆 날짜별 획득포인트 조회하기 (0) | 2025.01.31 |
---|---|
[내일배움캠프-사전캠프 문제풀이] JAVA 보너스 문제 "가위바위 보" (1) | 2025.01.24 |
[내일배움캠프-사전캠프 문제풀이] JAVA 응용문제 1, 2 (1) | 2025.01.22 |
[내일배움캠프-사전캠프] JAVA 걷기반 (1) | 2025.01.21 |
[내일배움캠프-사전캠프] SQL 단계별 문제 풀이 (0) | 2025.01.21 |