gpt4 book ai didi

java - HTTP 请求后在单独的线程上更改渲染屏幕

转载 作者:行者123 更新时间:2023-11-30 07:36:28 24 4
gpt4 key购买 nike

我的目标是当游戏无法再到达后端时更改用户的屏幕。我的代码按预期执行,只是屏幕永远不会改变。这是最初的调用:

timer.testTimeToServer(api, game);

这是计时器对象的类。我用(我的 url)代替我后端的实际 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);
}

我很困惑,因为代码打印出“应该切换屏幕”,所以它的行为就像预期的那样,除了游戏被卡住并且屏幕切换从未真正发生之外。

最佳答案

懒惰方式:

在你的主游戏类上:

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 类中创建一个回调,渲染方法上的每一帧都会检查结果并更改屏幕。

关于java - HTTP 请求后在单独的线程上更改渲染屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com