【发布时间】:2016-11-25 17:32:12
【问题描述】:
我正在制作游戏2048的AI版本。在后台创建游戏树后,我想用asynctask更新UI。它现在不起作用。
这是我在MainActivity.java; 中使用AsyncTask 的地方
private class AsyncTaskRunner extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... v) {
try {
Tree tree = new Tree(gameEngine);
List<Node> path;
Node root = new Node(gameEngine.grid.cells);
tree.createInitialTree(root);
path = ai.findPath(root);
Node maxNode = path.get(path.size() - 1);
for (Node node : path) {
SystemClock.sleep(500);
publishProgress(node.getDir());
}
while (!maxNode.myLose && (gameEngine.grid.areCellsAvailable(maxNode.getBoard()) || gameEngine.availableTileMatchLeft(maxNode)
|| gameEngine.availableTileMatchRight(maxNode) || gameEngine.availableTileMatchUp(maxNode) ||
gameEngine.availableTileMatchDown(maxNode))) {
tree = new Tree(gameEngine);
tree.createTree(maxNode);
path = ai.findPath(maxNode);
for (Node node : path) {
SystemClock.sleep(500);
publishProgress(node.getDir());
}
maxNode = path.get(path.size() - 1);
}
System .out.println("You lose!!!");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
protected void onProgressUpdate(String... direction) {
switch (direction[0]) {
case "left": onLeftSwipe();
break;
case "right": onRightSwipe();
break;
case "down": onDownSwipe();
break;
case "up": onUpSwipe();
break;
}
super.onProgressUpdate(direction);
}
@Override
protected void onPostExecute(Void v) {
}
}
从onCreate()调用它;
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
使用publishProggress(path),我将发送列表path,其中包含人工智能将执行的动作。但是当涉及到onProggressUpdate() 并执行onSwipeLeft() 时,它不会更新游戏画面。我是否正确使用AsyncTask?感谢您的帮助。
更新:它现在正在更新UI,但不会等待publishProggress() 完成。我该怎么做?
【问题讨论】:
-
onSwipeLeft 在做什么?我想问题就在那里!
-
它将图块向左移动。当AI未激活时,它正常工作。 @WasiAhmad
-
那么,您认为问题可能出在 AI 逻辑上??然后您可以调试以查看您的 AI 逻辑在特定情况下正在做什么!我在您提供的代码中没有发现任何问题。
-
我相信问题出在
AsyncTask。以前没用过,可能有问题。我认为 AI 逻辑是正确的,经过调试但找不到问题。doInBackground()中有两个publishProgress()方法,使用方法对吗? @WasiAhmad -
是的,没问题。根据我的说法,您只做错了一件事,我不确定这是否是原因!我在回答中提到了这一点。
标签: android-asynctask artificial-intelligence