⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gameui.java

📁 一个简单的猜数字游戏
💻 JAVA
字号:
package game.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import game.GameIsWorkingException;
import game.GameNotWorkingException;
import game.GuessGame;
import game.NumberUsedException;

public class GameUI {
	
	private GuessGame game;

	
	public GameUI() {
		
	}
	
	public void setGame(GuessGame game) {
		this.game = game;
	}

	public void mainMenu() {
		PrintWriter out = new PrintWriter(System.out, true);
		BufferedReader in = 
			new BufferedReader(new InputStreamReader(System.in));
		
		while(true){
			out.println("欢迎您使用猜数游戏: 1 开始, 2 历史分数, 0 退出:");
			try {
				String cmd = in.readLine();
				if(cmd.equals("0")){
					out.println("感谢你的使用, bye!");
					break;
				}else if(cmd.equals("1")){
					startGame(in, out);
				}else if(cmd.equals("2")){
					showHistory(in, out);
				}else{
					out.println("不可识别命令!");
				}
			} catch (IOException e) {
				//处理控制台读取错误
				e.printStackTrace();
				break;
			}
		}
	}

	private void showHistory(BufferedReader in, PrintWriter out) {
		try {
			game.showHistory();
		} catch (IOException e) {
			//e.printStackTrace();
			out.println(e.getMessage());
		}
	}

	private void startGame(BufferedReader in, PrintWriter out) {
		
		try {
			game.start();
		} catch (GameIsWorkingException e) {
			//e.printStackTrace();
			out.println(e.getMessage());
			return;
		}
		
		while(true){
			out.println("当前分数:" +game.getScore());
			out.println("猜过数字:" +game.getUsedNumberList());
			out.println("请猜测1~100数字:");
			try {
				String str = in.readLine();
				
				int num = Integer.parseInt(str);
				
				if(num<1 || num>100){ // 表单的检验
					out.println("数字必须是1~100之间的数");
					continue;
				}
				
				int val = game.guess(num);
				
				if(val>0){
					out.println("猜大了! 继续呀...");
					continue;
				}
				if(val<0){
					out.println("猜小了! 继续呀...");
					continue;
				}
				if(val==0){
					gameOver(in, out);
					break;
				}
			} catch (NumberFormatException e) {
				out.println("输入的不是数字!");
				continue;
			} catch (IOException e) {
				out.println(e.getMessage());
				break;
			} catch (NumberUsedException e) {
				out.println(e.getMessage());
				continue;
			} catch (GameNotWorkingException e) {
				out.println(e.getMessage());
				break;
			}
			
		}
		
		
	}

	private void gameOver(BufferedReader in, PrintWriter out) {
		out.println("恭喜, 恭喜, 你经过" + game.getScore() + " 的努力, 结束了战斗! 留下你芳名:");
		
		try {
			String name = in.readLine();
			game.saveScore(name);
		} catch (IOException e) {
			out.println(e.getMessage());
		}
		
		
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -