미니

자바 콘솔 -bulls and cows 게임

now0204 2023. 3. 10. 13:57
class Number_exceed_Exception extends Exception {
    String msg;

    Number_exceed_Exception(int a, int b) {
        this.msg = "Error: it's not possible to generate a code with " +
                "a length of " + a + " with " + b + " unique symbols.";
    }

    Number_exceed_Exception() {
    }
}

class Maxinum_number_Exception extends Number_exceed_Exception {

    Maxinum_number_Exception() {
        super.msg = "Error: maximum number of possible symbols in the code is 36 (0-9, a-z).";
    }
}

class InPut_miss_Exception extends Number_exceed_Exception {

    InPut_miss_Exception(String val) {
        super.msg = String.format("Error: \"%s\" isn't a valid number.", val);
    }
}


public class Main {
    static int try_counter = 0;

    public static void main(String[] args) {


        String random_number = createnumber();
        System.out.println("Okay, let's start a game!");
        while (true) {
            System.out.println("Turn " + (++try_counter) + ":");

            String input2 = new Scanner((System.in)).next();
            if (!grade(input2, random_number)) {
                continue;
            }
            System.out.println("Congratulations! You guessed the secret code.");
            break;

        }

    }
    
    private static String createnumber() {

        int[] inputval = makeinput();

        System.out.println(printmaker(inputval[0], inputval[1]));

        StringBuilder result = new StringBuilder(inputval[0]);
        char create_num;
        Random random_num;
        while (result.length() != inputval[0]) {
            random_num = new Random(System.nanoTime());
            create_num = (char) (random_num.nextInt(inputval[1]));

            if (create_num >= 0 && create_num <= 9) create_num += '0';
            else create_num = (char) ((int) create_num - 10 + (int) 'a');

            if (result.length() == 0) {
                if (create_num != '0') {
                    result.append(create_num);
                } else continue;
            }

            if (result.indexOf("" + create_num) >= 0) continue;
            else result.append(create_num);
        }

        return result.toString();
    }

    private static int[] makeinput() {
        int[] inputval = new int[2];
        try {
            Scanner s = new Scanner(System.in);
            System.out.println("Input the length og the secret code");
            String pre_int = s.nextLine();
            if (isalpha(pre_int)) throw new InPut_miss_Exception(pre_int);
            inputval[0] = Integer.parseInt(pre_int);
            System.out.println("Input the number of possible symbols in the code");
            inputval[1] = s.nextInt();
            if (inputval[0] <= 0) throw new InPut_miss_Exception(inputval + "");
            if (inputval[0] > inputval[1]) throw new Number_exceed_Exception(inputval[0], inputval[1]);
            if (inputval[1] > 36) throw new Maxinum_number_Exception();
        } catch (InPut_miss_Exception e1) {
            System.out.println(e1.msg);
            System.exit(-1);
        } catch (Maxinum_number_Exception e2) {
            System.out.println(e2.msg);
            System.exit(-1);
        } catch (Number_exceed_Exception e3) {
            System.out.println(e3.msg);
            System.exit(-1);
        }

        return inputval;
    }

    private static boolean isalpha(String preInt) {
        for (int i = 0; i < preInt.length(); i++) {
            if (preInt.charAt(i) >= 'a' && preInt.charAt(i) <= 'z' || preInt.charAt(i) >= 'A' && preInt.charAt(i) <= 'Z')
                return true;
        }
        return false;
    }

    private static String printmaker(int input, int possibleNum) {
        String result = "the secret is prepared: ";
        for (byte i = 0; i < input; i++) result += "*";
        if (possibleNum < 11)
            result += " (0-" + (possibleNum - 1) + ").";
        else {
            result += " (0-9, a-" + (char) ((possibleNum - 11) + 'a') + ").";
        }
        return result;
    }


    private static boolean grade(String input, String preDifined) {
        int bulls = 0;
        int cows = 0;
        String result = "";

        for (int i = 0; i < preDifined.length(); i++) {
//
            if (input.charAt(i) == preDifined.charAt(i))
                bulls++;
            else if (preDifined.contains("" + input.charAt(i)))
                cows++;

            if (i > 0 && input.charAt(i - 1) == input.charAt(i)) {
                cows = preDifined.contains("" + input.charAt(i - 1)) ? cows - 1 : cows;

            }

        }

        if (cows == 0 && bulls == 0) {
            result = "Grade: None.";
        } else if (cows > 0 && bulls > 0) {
            result += bulls == 1 ? bulls + " bull and " : bulls + " bulls and ";
            result += cows == 1 ? cows + " cow." : cows + " cows.";
        } else if (bulls == 0 || cows == 0) {
            result += (bulls == 0) ? "" : bulls == 1 ? bulls + " bull." : bulls + " bulls.";
            result += (cows == 0) ? "" : cows == 1 ? cows + " cow." : cows + " cows.";

        }
        System.out.println(result);
        System.out.println();

        if (bulls == input.length()) return true;
        return false;
    }
}

 

간단한 콘솔 bulls and cows게임을 만들어 보았다.

게임규칙은 간단하다

 

1. 원하는 secret code의 길이를 입력하고, 조합될 숫자를 입력한다

(코드 길이 및 조합 가능 숫자는 36이 최대이다. 0~9 + a~z)

* secret code길이 입력시 숫자가 아닌 입력 -> 예외발생

* 조합 가능 숫자 36초과 시 >예외발생

* secret code > 조합가능 숫자 > 예외발생

  ->난수는 겹치는 숫자가 없으므로, 난수 조합가능 숫자와 코드길이는 같거나 코드길이가 더 작아야한다.

 

2. 원하는 입력에 따라 난수를 생성한다. 

  > 난수는 겹치는 수가 없다.

 

3. 난수를 맞춰본다. 자리와 숫자가 모두 맞으면 bull이고 숫자만 맞으면, cow이다. 

 

4. 모든 숫자를 맞추면 실행을 종료한다.  

 

 

연습한것 

-예외처리 + 유효성검사 (커피머신 만들기에서 부족했던 점...) 연습 

-난수 만들기 

 

부족한 점

-코드를 더 깔끔하게 정리할 수 있을 것같다.

 

추후 개선사항

-> 나중에 클래스로 만드는 작업을 해보자. ->코드 깔끔하게 정리하기

-> 재입력 입력취소 등등도 고려해 볼만하다.