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<answer.length;i++) {
            System.out.print(answer[i]);
        }
        System.out.println();
        */
        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;i<ch.length;i++) {

            char check = (char)('A'+Math.random()*('Z'-'A'+1));
            boolean b = true;
            for(int j=0;j<ch.length;j++) {
                if(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;i<answer.length;i++) {
            for(int j=0;j<input.length;j++) {
                if(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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值