jjzjj

java - 在屏幕之间切换 Libgdx

coder 2024-03-16 原文

我仍在处理这个 libgdx 项目,我正在尝试找出将屏幕更改为我的游戏屏幕的最佳方法现在,当单击一个按钮时,我需要它转换到游戏屏幕。我已经看到一些扩展游戏类的实现,但我不确定从这里开始的最佳方法是什么。

这是主要的应用类:

public class ConnectFourApplication implements ApplicationListener {

    private Screen screen;

    public static void main(String[] args) {            
        new LwjglApplication(new ConnectFourApplication(), "PennyPop", 1280, 720,
                true);
    }

    @Override
    public void create() {
        screen = new MainScreen();
        screen.show();
        
    }

    @Override
    public void dispose() {
        screen.hide();
        screen.dispose();
        
    }
    
    /** Clears the screen with a white color */
    private void clearWhite() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }

    @Override
    public void pause() {
        screen.pause();
    }

    @Override
    public void render() {
        clearWhite();
        screen.render(Gdx.graphics.getDeltaTime());
    }

    @Override
    public void resize(int width, int height) {
        screen.resize(width, height);
        
    }

    @Override
    public void resume() {
        screen.resume();
    }

}


public class MainScreen implements Screen {
    
    private final Stage stage;
    private final SpriteBatch spriteBatch;
    
    //Parameter for drawing the buttons
    private final BitmapFont font;
    private final TextureAtlas buttons; 
    private final Button SFXButton;
    private final Button APIButton;
    private final Button GameButton;
    private final Skin images;
    
    //Parameter for Sound
    private final com.badlogic.gdx.audio.Sound SFXClick;
    
    //Parameter for the api call
    private final String WeatherUrl;
    private final HttpRequest request;
    private final City SanFrancisco;
    
    //The screen to load after the game button is hit
    private Screen gamescreen;
    
    
    public MainScreen() {
        
        //Set up our assets
        spriteBatch = new SpriteBatch();
        stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false, spriteBatch);
        font = new BitmapFont(Gdx.files.internal("assets/font.fnt"),
                 Gdx.files.internal("assets/font.png"), false);
        buttons = new TextureAtlas("assets/GameButtons.pack");
        images = new Skin(buttons);
        images.addRegions(buttons);
        SFXButton = new Button(images.getDrawable("sfxButton"));
        SFXButton.setPosition(295, 310);
        APIButton = new Button(images.getDrawable("apiButton"));
        APIButton.setPosition(405, 310);
        GameButton = new Button(images.getDrawable("gameButton"));
        GameButton.setPosition(515, 310);
        SFXClick = Gdx.audio.newSound(Gdx.files.internal("assets/button_click.wav"));
        
        //Add our actors to the stage
        stage.addActor(SFXButton);
        stage.addActor(APIButton);
        stage.addActor(GameButton);
        
        //Set up our Url request to be used when clicking the button
        WeatherUrl = "http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,US";
        request = new HttpRequest(HttpMethods.GET);
        request.setUrl(WeatherUrl);
        SanFrancisco = new City("Unavailable","Unavailable","0","0"); //init san fran to be displayed before they have clicked the button
        
        
        //initialize the game screen that we will switch to when the button is pressed
        gamescreen = new GameScreen();
        
    }

    @Override
    public void dispose() {
        spriteBatch.dispose();
        stage.dispose();
    }

    @Override
    public void render(float delta) {
        stage.act(delta);
        stage.draw();
        
        //Begin sprite batch
        spriteBatch.begin();
        

        //Set our on click listeners for our buttons
        if (SFXButton.isPressed())
            SFXClick.play();
        
        if(APIButton.isPressed())
        {
            CallApi();
        }
            
        if(GameButton.isPressed())
            LoadGame();
        
        
        //Set font color and render the screen
        font.setColor(Color.RED);
        font.draw(spriteBatch, "PennyPop", 455 - font.getBounds("PennpyPop").width/2,
                460 + font.getBounds("PennyPop").height/2);
        
        font.setColor(Color.BLACK);
        font.draw(spriteBatch, "Current Weather", 900 - font.getBounds("PennpyPop").width/2,
                460 + font.getBounds("PennyPop").height/2);
        
        font.setColor(Color.LIGHT_GRAY);
        font.draw(spriteBatch, SanFrancisco.Name, 940 - font.getBounds("PennpyPop").width/2,
                420 + font.getBounds("PennyPop").height/2);
        
        
        font.setColor(Color.RED);
        font.draw(spriteBatch, SanFrancisco.CurrentCondition, 950 - font.getBounds("PennpyPop").width/2,
                300 + font.getBounds("PennyPop").height/2);
        
        
        font.draw(spriteBatch, SanFrancisco.Temperature + " Degrees,", 920 - font.getBounds("PennpyPop").width/2,
                270 + font.getBounds("PennyPop").height/2);
        
        font.draw(spriteBatch, SanFrancisco.WindSpeed, 1200 - font.getBounds("PennpyPop").width/2,
                270 + font.getBounds("PennyPop").height/2);
        
        
        
        //End or sprite batch
        spriteBatch.end();
        
    
    }
    
    //Handles calling our API
    public void CallApi(){
        
        //Sends our stored HTTPRequest object
         Gdx.net.sendHttpRequest(request, new HttpResponseListener() {
            @Override
            public void handleHttpResponse(HttpResponse httpResponse) {
                
                //Uses our private response reader object to give us a the JSON from the api call
                JSONObject json =  HttpResponseReader(httpResponse);
                
                //Gets the name of the city
                SanFrancisco.Name = (String) json.get("name");      

                //Parsed through our returned JSON for the weather key
                JSONArray WeatherArray = (JSONArray) json.get("weather");
                //Gets the actual weather dictionary 
                JSONObject Weather = (JSONObject) WeatherArray.get(0);
                //Finally get the value with the key of description and assign it 
                //To the San Fran current conditions field
                SanFrancisco.CurrentCondition = (String) Weather.get("description");
                

                
                //Gets the actual main dictionary 
                JSONObject main = (JSONObject) json.get("main");            
                //Finally get the values based on the keys
                SanFrancisco.Temperature = (String) Double.toString((double) main.get("temp"));
            
                //Finally get the wind speed
                JSONObject wind = (JSONObject) json.get("wind");    
                SanFrancisco.WindSpeed = (String) Double.toString((double) wind.get("speed"));
                                 
            }
            
            @Override
            public void failed(Throwable t) {
                Gdx.app.log("Failed ", t.getMessage());
                 
            }
         });
    }
    
    //When the button game button is clicked should load the connect four game
    public void LoadGame(){
        hide();
        gamescreen.show();
    }
    
    
    
    //Converts our HttpResponse into a JSON OBject
    private static JSONObject HttpResponseReader(HttpResponse httpResponse){
        
        BufferedReader read = new BufferedReader(new InputStreamReader(httpResponse.getResultAsStream()));  
        StringBuffer result = new StringBuffer();
        String line = "";
        
        try {
          while ((line = read.readLine()) != null) {
                  result.append(line);
              }
          
              JSONObject json;
            try {
                json = (JSONObject)new JSONParser().parse(result.toString());
                return json;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return null;

    }

    @Override
    public void resize(int width, int height) {
        stage.setViewport(width, height, false);
    }

    @Override
    public void hide() {
        Gdx.input.setInputProcessor(null);
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage);
        render(0);
    }

    @Override
    public void pause() {
        // Irrelevant on desktop, ignore this
    }

    @Override
    public void resume() {
        // Irrelevant on desktop, ignore this
    }
}

最佳答案

我总是这样实现屏幕切换:

首先,主类需要扩展 Game(来自 com.badlogic.gdx.Game),您需要有一个类型为 Game 的新字段:

public class ConnectFourApplication extends Game{
     private Game game;

现在在构造函数中初始化game:

public ConnectFourApplication(){
     game = this; // Since this class extends Game

要将屏幕设置为 MainScreen,现在,您需要做的就是使用 setScreen(new MainScreen(game)); 方法(传递 game 所以我们可以从 MainScreen 类设置屏幕) 您现在需要一个用于 MainScreen 类的新构造函数和一个新字段:

private Game game;
public MainScreen(Game game){
     this.game = game;

现在您可以使用 game.setScreen(new Screen(game)); 将屏幕设置为另一个实现 Screen 的类。

但是现在,在主类中,在 render() 方法中,您必须使用 super.render(); 来使用其他屏幕渲染的所有内容!

public void render() {
    clearWhite();
    super.render();
}

PS:确保您作为屏幕创建的类实际上实现了屏幕

关于java - 在屏幕之间切换 Libgdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837013/

有关java - 在屏幕之间切换 Libgdx的更多相关文章

  1. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  2. ruby-on-rails - Ruby on Rails with Haml - 如何从 erb 切换 - 2

    我正在从erb文件切换到HAML。我将hamlgem添加到我的系统中。我创建了app/views/layouts/application.html.haml文件。我应该只删除application.html.erb文件吗?此外,仍然有/public/index.html文件被呈现为默认页面。我想创建自己的默认index.html.haml页面。我应该把它放在哪里以及如何使系统呈现该文件而不是默认索引文件?谢谢! 最佳答案 是的,您可以删除任何已转换为HAML的View的ERB版本。至于你的另一个问题,删除public/index/h

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  5. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. 屏幕录制为什么没声音?检查这2项,轻松解决 - 2

    相信很多人在录制视频的时候都会遇到各种各样的问题,比如录制的视频没有声音。屏幕录制为什么没声音?今天小编就和大家分享一下如何录制音画同步视频的具体操作方法。如果你有录制的视频没有声音,你可以试试这个方法。 一、检查是否打开电脑系统声音相信很多小伙伴在录制视频后会发现录制的视频没有声音,屏幕录制为什么没声音?如果当时没有打开音频录制,则录制好的视频是没有声音的。因此,建议在录制前进行检查。屏幕上没有声音,很可能是因为你的电脑系统的声音被禁止了。您只需打开电脑系统的声音,即可录制音频和图画同步视频。操作方法:步骤1:点击电脑屏幕右下侧的“小喇叭”图案,在上方的选项中,选择“声音”。 步骤2:在“声

  10. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

随机推荐