Project 2 - random world generator
昨天晚上做完了phase 1,今天整理一下思路。为了节省时间,phase 2的交互部分就不做了感觉意义并不大。其实project 2难点就是在于随机生成地图,虽然最后生成的地图也很简陋,但是就像josh说的,编生成地图的代码过程才有趣。
目前网上没搜到什么攻略,来做个头一份。估计也就我这种赋闲在家的才有时间做攻略吧,唉。
项目要求 + 成品
这个是josh做的例子,要求如下:
- 2D
- 伪随机生成。就是只要seed是确定的,世界就是确定的;seed改变,世界重新随机生成。
- 包括rooms和hallways,也可以有外部空间(NOTHING)。
- 房间需要是长方形的,也可以有其他形状。
- 房间、走廊大小、长度、数量、位置随机。
- 房间和走廊需要相连
上图是我做出的成品,总觉得看着没有josh的好看,有一些改进的空间。。。可以明显看出用的不是同一种思路,复杂度要高一点。不过确实满足了要求。下面简单说下思路,不会贴太多代码。如果想看代码的在这里:https://github.com/stg1205/CS61B/tree/master/proj2/byog
skeleton文档分析
拿到题目之后,我先观察了一下现有文档的结构。总体来说,是Main.java里面负责调用Game.java里面的两种方法,启动游戏
//Main.java
public class Main {
public static void main(String[] args) {
if (args.length > 1) {
System.out.println("Can only have one argument - the input string");
System.exit(0);
} else if (args.length == 1) {
Game game = new Game();
TETile[][] worldState = game.playWithInputString(args[0]);
System.out.println(TETile.toString(worldState));
} else {
Game game = new Game();
game.playWithKeyboard();
}
}
}
args是在编译的时候输入的字符串,当只有一个字符串时,调用game.playWithInputString(String s)
方法。注意这个args不等于交互,是在编译的时候默认输入的。worldState接收了生成好的TETile世界,然后下一行TETile.toString将世界的二维TETile数组转化为字符串,输出在控制台。这个方法主要用于phase 1的测试,并没有调用stdDraw库中的函数。当没有args时,进入game.playWithKeyboard()
方法,包含欢迎界面,用户交互。所以在phase 1,只需要注意第一种方法。
// Game.java
public TETile[][] playWithInputString(String input) {
// Fill out this method to run the game using the input passed in,
// and return a 2D tile representation of the world that would have been
// drawn if the same inputs had been given to playWithKeyboard().
}
此方法输入为input(args),里面包含seed,返回一个生成的世界TETile[][]。
我是按照从大到小,从外往里的方式思考。现在需要一个worldGenerator方法,其输入是seed(或者是由seed生成的RANDOM),返回生成好的二维数组。另外,根据现有的代码,在Game.java里面也进行了世界的定义,设置长度宽度,并进行初始化,因此再加入一输入变量,二维数组TETile[][] world。整理好代码如下:
// Game.java
public TETile[][] playWithInputString(String input) {
long seed = Long.parseL