2018.6.8 城堡游戏 Java project
Game.java:
import java.util.Scanner;
import java.util.HashMap;
public class Game {
private Room currentRoom;
protected int isAnswer = 0;
private Room outside, lobby, pub, study, bedroom, diningroom, bathroom, loft;
private HashMap<String, Handler> handlers = new HashMap<String, Handler>();
public Game()
{
handlers.put("bye", new HandlerBye(this));
handlers.put("help", new HandlerHelp(this));
handlers.put("go", new HandlerGo(this));
createRooms();
}
private void createRooms()
{
// 制造房间
outside = new Room("城堡外",this);
lobby = new RoomLobby("大堂",this);
pub = new RoomPub("酒吧",this);
study = new RoomStudy("书房",this);
bedroom = new RoomBedroom("卧室",this);
diningroom = new RoomDiningroom("餐厅",this);
bathroom = new RoomBathroom("厕所",this);
loft = new RoomLoft("阁楼",this);
// 初始化房间的出口
outside.setExit("east", lobby);
lobby.setExit("north", diningroom);
lobby.setExit("south", pub);
lobby.setExit("west", outside);
lobby.setExit("up", study);
pub.setExit("north", lobby);
diningroom.setExit("south", lobby);
study.setExit("north", bathroom);
study.setExit("south", bedroom);
study.setExit("down", lobby);
bedroom.setExit("north", study);
bathroom.setExit("south", study);
currentRoom = outside; // 从城堡门外开始
}
private void printWelcome() {
System.out.println();
System.out.println("这个城堡由国王建造,放着他的心爱之物");
System.out.println("里面有七个房间,藏着七个谜题,解开他们就能得到国王的宝贝");
System.out.println("如果需要帮助,请输入 'help' 。");
System.out.println("赶快进去吧!!!");
System.out.println();
showPrompt();
}
// 以下为用户命令
public void goRoom(String direction)
{
Room nextRoom = currentRoom.getExit(direction);
if (nextRoom == null) {
System.out.println("那里没有门!");
}
else {
currentRoom = nextRoom;
showPrompt();
}
}
public void play() {
Scanner in = new Scanner(System.in);
while ( true ) {
String line = in.nextLine();
String[] words = line.split(" ");
Handler handler = handlers.get(words[0]);
String value = "";
if (words.length > 1) {
value = words[1];
}
if (handler != null) {
handler.doCmd(value);
if (handler.isBye()) {
break;
}
}
if (isAnswer == 6) {
break;
}
}
System.out.println(",已回到书房,离开城堡?(Y/N)");
String value = in.nextLine();
if (value.equals("Y")) {
System.out.println("GAME OVER");
}
else {
loft.ending();
}
in.close();
}
public void showPrompt() {
System.out.println("你在" + currentRoom);
if (currentRoom.getAnswer()) {
isAnswer++;
//System.out.println(isAnswer);
}
System.out.print("出口有: ");
System.out.print(currentRoom.getExitDesc());
System.out.println();
}