Java實現猜字母游戲


 

 

 

package day06;

import java.util.Scanner;

public class HomeWork {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String string = "GuessingGame";
		System.out.println(string+"歡迎嘗試猜字謎游戲!滿分500分,最低分為0分!");
		System.out.println(string+"請輸入游戲級別(5,7,9)");
		int n = scanner.nextInt();
		int count = 0;
		System.out.println(string+"游戲開始,請輸入你所猜的"+n+"個字母的序列:(exit - 退出)");
		
		char[] chs = generate(n);
		System.out.println(chs);
		while(true){
			String s = scanner.next().trim().toUpperCase();
			char[] input = s.toCharArray();
			int[] result = check(chs, input);
			int score = 500-count*10;
			if(s.equals("EXIT")){
				System.out.println("歡迎再次挑戰!");
				break;
			}
			if(score<=0){
				score=0;
			}
			if(result[1] == chs.length){
				System.out.println("恭喜你!猜對了!你的得分是:"+score);
				break;
			}else{
				count++;
				System.out.println(string+"你猜對"+result[0]+"個字符,其中"+result[1]+"個字符的位置正確!(總次數="+count+",exit - 退出!");
			}
		}
	}

	// 聲明一個方法,用於生成隨機不同字符數組,n控制生成字符的個數
	public static char[] generate(int n){
		char[] chs = new char[n];
		char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                'W', 'X', 'Y', 'Z' };
		//設置開關
		boolean[] flags = new boolean[letters.length];
		for(int i=0;i<chs.length;i++){
			int index;//letters下標
			do{
				//生成隨機下標
				index = (int) (Math.random()*letters.length);
			}while(flags[index]);//為true,則以存在,再次循環,取得不同的字符
				chs[i] = letters[index];//給生成的新的數組賦值
				flags[index] = true;//設置為false,說明這個位置已經有數據了
		}
		return chs;
	}
	
	//聲明一個方法,比較隨機生成的數組和用戶輸入的數組,返回int數組,里面保存了對比后字符對的個數和位置對的個數
	public static int[] check(char[] chs,char[] input){
		int[] result = new int[2];
		for(int i=0;i<chs.length;i++){
			for(int k=0;k<input.length;k++){
				if(chs[i] == input[k]){
					result[0]++;//記錄字符對的個數
					if(i==k){
						result[1]++;//記錄位置對的個數
					}
					break;
				}
			}
		}
		return result;
	}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM