1. 程式人生 > >java語言的猜數字遊戲程式碼

java語言的猜數字遊戲程式碼

昨天寫的一段亂七八糟的java語言猜數字程式碼。

====================================

系統隨機生成0-9中的不重複四位數字。

然後使用者輸入四個數字

如果數字對了,位置不對 則顯示 nB,n是有幾個是位置對的。

如果數字對了,位置也是對的 則顯示mA,m代表有幾個數字是正確位置上的。

例如:  生成的是0369    使用者輸入的是0396 則顯示2A2B,兩個位置是正確並且數字正確的,另外兩個是數字正確,位置不正確的。

======================================

package com.example.test;

import java.util.Random;
import java.util.Scanner;

public class NumberCode {

	int[] Nums = new int[4];
	int[] inputNumsArray = new int[4];
	int difficultyLevel;
	int difficulty;
	int aA = 0;
	int bB = 0;
	String numberStr = "";
	String str = "";

	/**
	 * 生成隨機數
	 */
	public int[] randNums(int n) {

		for (int i = 0; i < Nums.length; i++) {
			Random ran = new Random();
			int a = ran.nextInt(10);
			if (i - 1 != -1) {
				for (int j = 0; j < i; j++) {
					if (a == Nums[j]) {
						i--;
						break;
					} else {
						Nums[i] = a;
					}
				}
			} else {
				Nums[i] = a;
			}

		}
		return Nums;
	}

	/**
	 * 選擇遊戲難度 
	 */
	public int selectLevel() {
		// 接受一個數字
		// 1:Easy 可以猜12次
		// 2:Common 可以猜9次
		// 3:Hard 可以猜7次
		Scanner scan = new Scanner(System.in);
		System.out
				.println("請選擇難度係數(輸入數字),1:Easy 可以猜12次;2:Common 可以猜9次;3:Hard 可以猜7次");
		difficulty = scan.nextInt();
		switch (difficulty) {
		case 1:
			difficultyLevel = 12;
			break;
		case 2:
			difficultyLevel = 9;
			break;
		case 3:
			difficultyLevel = 7;
			break;
		default:
			break;
		}
		return difficultyLevel;
	}

	/**
	 * 接受使用者輸入的數字
	 */
	public int[] inputNums(int n) {
		Scanner scan = new Scanner(System.in);
		int b = scan.nextInt();
		for (int i = 0; i < inputNumsArray.length; i++) {
			int c = (int) ((int) b / Math.pow(10, 3 - i));
			inputNumsArray[i] = c;
			b = (int) (b - c * Math.pow(10, (3 - i)));
		}
		return inputNumsArray;
	}

	/**
	 * 數字比對的方法
	 */
	public String compare(int[] answer, int[] inputs) {

		for (int i = 0; i < answer.length; i++) {
			if (inputs[i] == answer[i]) {
				aA += 1;
				continue;
			} else {
				for (int j = 0; j < answer.length; j++) {
					if (inputs[i] == answer[j]) {
						bB += 1;
					}
				}
			}
		}
		str = "" + aA + "A " + bB + "B ";
		return str;
	}

	/**
	 * 整個遊戲過程程式碼 
	 */
	public void play() {
		randNums(4);
		for (int i = 0; i < Nums.length; i++) {
			numberStr = numberStr + Nums[i];
		}
		selectLevel();
		System.out.println("你選擇了難度係數:" + difficulty + " 共有:" + difficultyLevel
				+ "次機會。");
		for (int i = 0; i < difficultyLevel; i++) {
			inputNums(4);
			int chanceNums = difficultyLevel - i - 1;
			compare(Nums, inputNumsArray);
			if (aA != 4) {
				if (chanceNums == 0) {
					System.out.println("機會用完了,答案是:" + numberStr);
					break;
				} else {
					System.out.println(str + " 你還有" + chanceNums + "次機會");
				}

				aA = 0;
				bB = 0;
			} else if (aA == 4) {
				System.out.println("恭喜你,答對了");
				break;
			}
		}

	}

	public static void main(String[] args) {
		NumberCode a = new NumberCode();
		a.play();
	}
}