您的位置:首页 > 编程语言 > Java开发

用Java打暴雪星际(3)——探究示例机器人代码

2016-03-24 16:55 435 查看
原创文章,转载请注明。

看过上一节的视频,想必您对机器人打星际有了一个直观的了解。接下来我将简要讲解一下游戏逻辑控制部分。

游戏有主循环,这跟人类的真实世界理解起来可能有一点不同。游戏类似于动画,每一秒由一定数目的帧构成,这些帧快速地播放,我们的眼睛就会产生里面的角色在动的错觉。而游戏和动画的不同在于,在下一帧播放之前,计算机会经过一定的逻辑运算,来确定下一帧中的角色的具体位置和状态。

而我们现在要做的就是在游戏的每一帧之间编写我们的代码,接着计算机会计算出游戏中各个角色的状态和位置并形成图像显示出来。而我们所编写的代码是和游戏中的对象紧密相关联的。

说那么多,现在就开始具体的实战。

第一步,我们先分析示例代码。我们只需要关注其中几段代码即可。

@Override
public void onStart() {
game = mirror.getGame();
self = game.self();

//Use BWTA to analyze map
//This may take a few minutes if the map is processed first time!
System.out.println("Analyzing map...");
BWTA.readMap();
BWTA.analyze();
System.out.println("Map data ready");

int i = 0;
for(BaseLocation baseLocation : BWTA.getBaseLocations()){
System.out.println("Base location #" + (++i) +". Printing location's region polygon:");
for(Position position: baseLocation.getRegion().getPolygon().getPoints()){
System.out.print(position + ", ");
}
System.out.println();
}

}

@Override
public void onFrame() {
//game.setTextSize(10);
game.drawTextScreen(10, 10, "Playing as " + self.getName() + " - " + self.getRace());

StringBuilder units = new StringBuilder("My units:\n");

//iterate through my units
for (Unit myUnit : self.getUnits()) {
units.append(myUnit.getType()).append(" ").append(myUnit.getTilePosition()).append("\n");

//if there's enough minerals, train an SCV
if (myUnit.getType() == UnitType.Terran_Command_Center && self.minerals() >= 50) {
myUnit.train(UnitType.Terran_SCV);
}

//if it's a drone and it's idle, send it to the closest mineral patch
if (myUnit.getType().isWorker() && myUnit.isIdle()) {
Unit closestMineral = null;

//find the closest mineral
for (Unit neutralUnit : game.neutral().getUnits()) {
if (neutralUnit.getType().isMineralField()) {
if (closestMineral == null || myUnit.getDistance(neutralUnit) < myUnit.getDistance(closestMineral)) {
closestMineral = neutralUnit;
}
}
}

//if a mineral patch was found, send the drone to gather it
if (closestMineral != null) {
myUnit.gather(closestMineral, false);
}
}
}

//draw my units on screen
game.drawTextScreen(10, 25, units.toString());
}


这个示例的机器人只做一件事情,就是采矿,没有任何其它功能。

下一节我将讲解游戏的规则与设定,建造军营并生产步兵,并实现探索对方基地与兵力的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: