I am making an AI version of game 2048. After the game tree is created in background, I want to update the UI with asynctask
. It doesn't work for now.
This is where I use the AsyncTask
in MainActivity.java;
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) {
}
}
Calling it from onCreate()
;
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
With publishProggress(path)
, I am sending the list path
which has the moves that the AI will do. But when it comes to the onProggressUpdate()
and execute the onSwipeLeft()
for example, it does not update the game screen. Am I using AsyncTask
correctly? Thank you for your help.
UPDATE: It is now updating the UI
but doesn't wait for the publishProggress()
to finish. How do I do that?