JAVA小游戏——猜字母

游戏规则

玩家需要任意输入五个不同的大写英文字母,每次输入后都会返回两个提示,一个是当前猜对的字母数,还有一个是字母和位置都匹配的数目,通过提示猜出正确的结果。
玩家起始分值设为500分,每猜错一次减10分,游戏结束显示最终得分。
(无图形界面)

游戏源码

import java.util.Scanner;

public class GuessTheLetters {

    public static void main(String[] args) {
        System.out.println("这是一个猜字母游戏!"+"\n"+"【请输入五个不同的英文大写字母,看你能不能猜到】");
        char[] answer = charGenerate();
        //这里可以显示答案
        /*
        for(int i=0;i
        Scanner s = new Scanner(System.in);
        System.out.println("开始猜吧!");
        int score=500;
        while(true) {
            String str = s.next().toUpperCase();
            if(str.equals("EXIT")) {
                System.out.println("退出!");
                break;
            }
           char[] inputChars = str.toCharArray();
           boolean b =compare(answer,inputChars);
           if(b==true) {
               System.out.println("分数为:"+score);
               break;
           }else {
               score=score-10;
           }
        }
    }

    public static char[] charGenerate(){ //生成五个不同的随机字母
        char[] ch = new char[5];
        for(int i=0;ichar check = (char)('A'+Math.random()*('Z'-'A'+1));
            boolean b = true;
            for(int j=0;jif(check==ch[j]) {
                    b=false;
                    break;
                }
            }
            if(b==true) ch[i]=check;
            else i--;  
        }
        return ch;
    }

    public static boolean compare(char[] answer,char[] input) { //匹配
        int flag=0,position=0;
        boolean b=false;
        for(int i=0;ifor(int j=0;jif(answer[i]==input[j]) {
                    flag++;
                    if(i==j) position++;
                }
            }
        }
        if(flag==5 && position==5) {
            b=true;
            System.out.println("你真聪明都猜对了!");
        }else {
            System.out.println("猜测正确的字母数:"+flag+" "+"猜测正确的位置数:"+position);
        }
        return b;
    }

}

你可能感兴趣的:(JAVA)