[Java] Lv3. 단어 맞추기 게임

Yuri·2024년 12월 12일

Java

목록 보기
7/13

🍀 본격적으로 시작해 볼까요?

문제

단어를 주어진 기회 안에 맞추는 게임을 만들어보세요

  1. 컴퓨터가 랜덤으로 영어단어를 선택합니다.
    1. 영어단어의 자리수를 알려줍니다.
    2. ex ) PICTURE = 7자리 ⇒ _ _ _ _ _ _ _
  2. 사용자는 A 부터 Z 까지의 알파벳 중에서 하나를 입력합니다.
    1. 입력값이 A-Z 사이의 알파벳이 아니라면 다시 입력을 받습니다
    2. 입력값이 한 글자가 아니라면 다시 입력을 받습니다
    3. 이미 입력했던 알파벳이라면 다시 입력을 받습니다.
    4. 입력값이 정답에 포함된 알파벳일 경우 해당 알파벳이 들어간 자리를 전부 보여주고, 다시 입력을 받습니다.
      1. ex ) 정답이 eyes 인 경우에 E 를 입력했을 때
        1. _ _ _ _ → E _ E _
    5. 입력값이 정답에 포함되지 않은 알파벳일 경우 기회가 하나 차감되고, 다시 입력을 받습니다.
  3. 사용자가 9번 틀리면 게임오버됩니다.
  4. 게임오버 되기 전에 영어단어의 모든 자리를 알아내면 플레이어의 승리입니다.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Hangman {
    private static List<String> words = List.of(
            "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"
    );


    private static boolean validOfInput(String input, List<String> history) {
        boolean valid = false;
        // 2-1. 입력값이 A-Z 사이의 알파벳이 아니라면 다시 입력을 받습니다.
        if (!(65 <= input.charAt(0) && input.charAt(0) <= 90)) {
            valid = true;
        }
        // 2-2. 입력값이 한 글자가 아니라면 다시 입력을 받습니다.
        if (input.length() != 1) {
            valid = true;
        }
        // 2-3. 이미 입력했던 알파벳이라면 다시 입력을 받습니다.
        if (history.contains(input)) {
            valid = true;
        }
        if (valid) {
            System.out.println("잘못 입력하였습니다. 다시 입력해주세요.");
        }
        return valid;
    }

    private static List<Integer> findIndexes(String input, String word) {
        List<Integer> indexes = new ArrayList<>();
        int index = word.indexOf(input);
        while(index != -1) {
            indexes.add(index);
            index = word.indexOf(input, index + 1);
        }
        return indexes;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 9; // 기회 카운트
        List<String> history = new ArrayList<>(); // 사용자 입력 알파벳 이력

        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());

        String word = words.get(rand.nextInt(words.size())); // 랜덤 단어 선택
        word = word.toUpperCase(); // 단어 대문자 변환

        List<String> answer = new ArrayList<>(); // 정답 입력
        for (int i = 0; i < word.length(); i++) {
            answer.add("_");
        }

        while (count > 0) {
            System.out.println(answer);
            System.out.println("현재 남은기회: " + count);
            System.out.print("A-Z 중 하나를 입력해주세요: ");
            String input = scanner.nextLine().toUpperCase();

            if(validOfInput(input, history)) {
                continue;
            }

            history.add(input); // 입력받은 알파벳 이력 저장
            // 2-4. 입력값이 정답에 포함된 알파벳일 경우 해당 알파벳이 들어간 자리를 전부 보여주고 다시 입력을 받습니다.
            if (word.contains(input)) {
                // answer 입력칸 치환
                List<Integer> indexes = findIndexes(input, word);
                for (Integer index : indexes) {
                    answer.set(index, input);
                }
                if(!answer.contains("_")) {
                    System.out.println("정답입니다! " + answer);
                    return;
                }
            } else {
                // 2-5. 입력값이 정답에 포함되지 않은 알파벳일 경우 기회가 하나 차감되고, 다시 입력을 받습니다.
                System.out.println("정답에 포함된 알파벳이 아닙니다. 기회가 1 차감됩니다.");
                count--;
            }
        }

        System.out.println("모든 기회가 소진되었습니다. 게임오버");
    }
}

결과

2) 입력 조건 체크

3) 사용자가 9번 틀린 경우

4) 모든 단어를 알아낸 경우

profile
안녕하세요 :)

0개의 댓글