我的目标是在游戏无法再到达后端时更改用户的屏幕。我的代码按预期执行,但屏幕永不改变。这是最初的电话:
timer.testTimeToServer(api, game);
这里是计时器对象的类。我把(我的网址)代替我后端的实际IP地址:
public class CustomTimer {
private static final float timeToDrop = 2000;
private float time = 0;
private StopWatch watch = new StopWatch();
public void testTimeToServer(ApiCall api,final proofOfConcept game){
watch.start();
api.httpGetWithCallback("(my url)/api/v1/character", new CallBack(){
@Override
public void callback(String resp){
System.out.println("Server Responded");
time = watch.getTime();
watch.stop();
watch.reset();
if(time > timeToDrop){
game.setScreen(new GameOverScreen(game, false));
System.out.println("Should have switched screen")
}
}
});
}
}
这是api对象中的httpGetWithCallback方法:
public void httpGetWithCallback (final String URL, final CallBack callback){
Thread th = new Thread(new Runnable(){
@Override
public void run() {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
httpRequest.setUrl(URL);
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setTimeOut(timeoutTimeInMilli);
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String successValue = httpResponse.getResultAsString();
if (successValue.contains("\"total_count\": 0"))//wrong credentials
{
callback.callback("EMPTY");
} else//there was a match yo! should probably have a unique conststraint on username. too hard eff it
{
callback.callback(successValue);
}
}
@Override
public void failed(Throwable t) {
callback.callback("FAILED");
}
@Override
public void cancelled() {
callback.callback("CANCELLED");
}
});
}
}
);
}
});
th.start();
threads.add(th);
}
我很难过,因为代码打印出来"应该切换屏幕"所以它表现得像预期的那样,除了游戏被冻结并且屏幕切换实际上从未发生过这样的事实。
答案 0 :(得分:1)
懒惰的方式:
在你的主要游戏课上:
public static ProofOfConcept game;
和你的方法
public void testTimeToServer(ApiCall api){
watch.start();
api.httpGetWithCallback("(my url)/api/v1/character", new CallBack(){
@Override
public void callback(String resp){
System.out.println("Server Responded");
time = watch.getTime();
watch.stop();
watch.reset();
if(time > timeToDrop){
Main.game.setScreen(new GameOverScreen(false));
System.out.println("Should have switched screen")
}
}
});
}
}
正确的方式
您可以在ProofOfConcept类中创建一个回调,即render方法的每一帧都会检查结果并更改屏幕。