我们再来回顾一下题目:
一、城堡游戏介绍:
1.这个程序的任务是通过玩家的输入的方向(纯文字)在虚构的城堡内移动(以纯文字作为移动后的返回结果)。
2.这个程序接受help、bye、go south、go north、go west、go east六种命令,要求命令单独一行输入并在结束时敲回车,另外如果接受go xxx的不合规信息会输出不存在这样的房间。
3.help提供帮助信息,bye结束游戏,go后面空一格加south、north、west、east表示在虚构的城堡中移动。
4.有五个地点,分别是:小酒吧,大厅,书房,卧室,次卧。
5.地图:
二:优化上一次的代码
package com.company;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/*
城堡游戏介绍:
1.这个程序的任务是通过玩家的输入的方向(纯文字)在虚构的城堡内移动(以纯文字作为移动后的返回结果)。
2.这个程序接受help、bye、go south、go north、go west、go east六种命令,要求命令单独一行输入并在结束时敲回车,
另外如果接受go xxx的不合规信息会输出不存在这样的房间。
3.help提供帮助信息,bye结束游戏,go后面空一格加south、north、west、east表示在虚构的城堡中移动。
4.有五个地点,分别是:小酒吧,大厅,书房,卧室,次卧。
5.地图:...
*/
//定义一个Room类,表示每个房间的情况
class Room{
public String room_name;
public Room(String room_name){
this.room_name=room_name;
}
HashMap<String, Room> Exists = new HashMap<String, Room>(); //记录在某个方向上连通的房间
public void getExists(String direction,Room room) {
Exists.put(direction,room);
}
public String toString(){
return room_name;
}
}
public class Game {
private static Room current_room;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Room pub=new Room("小酒馆");
Room hall=new Room("大厅");
Room study=new Room("书房");
Room bedroom=new Room("卧室");
Room bedroom1=new Room("次卧");
current_room=pub;
//设置各个房间之间连通的门
pub.getExists("east",hall);
hall.getExists("east",bedroom1);
hall.getExists("south",study);
hall.getExists("west",pub);
bedroom1.getExists("west",hall);
study.getExists("east",bedroom);
study.getExists("north",hall);
bedroom.getExists("west",study);
System.out.println("欢迎来到城堡游戏!");
System.out.println("请输入您选择的前进方向(east,south,west,north):");
System.out.println("输入格式例如:go east");
System.out.println("如果需要帮助,请输入:help ,如果需要结束游戏,请输入:bye");
Game game=new Game();
game.choice(current_room);
while(true) {
String str = in.nextLine();
String[] arr = str.split(" ");
if(arr[0].equals("help")) {
game.help();
} else if(arr[0].equals("bye")) {
break;
}
else if(arr[0].equals("go")){
game.go_ahead(arr[1]);
}
else{
System.out.println("不存在这样的房间!");
}
}
}
public void help(){
System.out.println("迷路了吗?你可以做的命令有:go | bye | help");
System.out.println("如:go east");
}
public void go_ahead(String direction) {
if(current_room.Exists.containsKey(direction)){
Room nextroom=current_room.Exists.get(direction);
current_room=nextroom;
Game g=new Game();
g.choice(current_room);
}
else{
System.out.println("该输入的方向上没有房间");
}
}
public void choice(Room room){
Set<String> dirs=room.Exists.keySet();
System.out.print("你目前在"+current_room+",可选择的方向有:");
for (String s:dirs){
System.out.print(" "+s);
}
System.out.println();
}
}
运行结果: