在一个项目中,我正在使用自定义配置文件以允许将自定义卡加载到游戏中。(类似于 .properties 文件,不同之处在于它包含多个项目的信息,以及不同类型的项目)。
文件是这样设置的:
# Pound Signs denote comments
# Empty lines are also ignored by the parser.
# Here are three example items
CARD_TYPE_ONE
{
name = item one name
species = robot
isMoveable = false
}
CARD_TYPE_TWO
{
name = foo
attackType = bar
}
CARD_TYPE_TWO
{
name = foo2
special = true
attackType = bar2
}
所有卡片都将具有任何未分配属性的默认值(即 CARD_TYPE_TWO 下的“特殊”默认为“假”),但如您所见,相同类型的不同卡片可以有不同的长度
我用于读取属性的代码如下所示:
private int createCardType2(String cardFile, int expectedLineNumber) {
// Builds Card type 2.
//cardFile is the location (with extension) of the .cards file
//expectedLineNumber is where the main program currently sits in reading the program
int i = 0;
Scanner in = null;
try {
in = new Scanner(new File(cardFile));
} catch (java.io.IOException e) { System.out.println(e); }
int x = 1;
while (in.hasNext()){
//loops through the previous lines in the file
while( i < expectedLineNumber) {
in.nextLine();
i++;
}
if (i != expectedLineNumber) {
//Something went wrong, and that can't be right
System.out.println("We have encountered an error, aborting now.");
break;
}
String <some dynamic name> = in.nextLine();
if (dynamicallyNamedString.equals("}") {
//find key pairs and set attributes.
}
if (!dynamicallyNamedString..trim().equals("}") && !in.hasNext()) {
//malformed file, throw an error
break;
}
}
in.close();
return i; //so that the main program knows where to go to to continue.
}
我将使用 String.split() 和“=”作为分隔符来获取我的密钥对。
我也知道 Java 没有动态变量命名,但我不认为哈希表是正确的,我不能使用数组,因为我不知道初始大小。
我觉得我错过了一些非常简单的东西。