我应该将游戏循环放在 Swing 应用程序的什么位置?

我正在尝试用 Java 制作一个简单的 2D 游戏。
据我所知,我的游戏应该由两个线程组成:“事件调度线程”(用于 GUI 操作)和“游戏线程”(用于游戏循环)。
我创建了一个大纲,但找不到放置游戏循环的位置。
简而言之,我正在尝试在不冻结 UI 线程的情况下创建游戏循环。
如果您能提供有关我做错的事情的任何信息,我将不胜感激。
这是我的游戏循环(您也可以提供提示以创建更好的游戏循环):

while(true) {
    repaint();
    try {
        Thread.sleep(17);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();

            }

        });
    }
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Forge and Attack");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setUndecorated(true);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setfocusable(true);
        frame.add(new MyPanel()); 
    }   
}
class MyPanel extends JPanel implements KeyListener,MouseListener {
    public MyPanel() {
        setBackground(Color.BLACK);
        setOpaque(true);
        addKeyListener(this);
        addmouseListener(new MouseAdapter(){
            public void mousepressed(MouseEvent e){
                
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        
    }
}
huang118118bing 回答:我应该将游戏循环放在 Swing 应用程序的什么位置?

我认为这是一个可以扩展的有趣话题...我已经涵盖了您提出的问题,并展示了做某些事情的更好或更正确的方法,例如绘画、聆听按下的按键以及一些其他人则喜欢分离关注点并使整个游戏更具可重用性/可扩展性。

1.在哪里放置游戏循环?

所以这不是直截了当的,可能取决于每个人的编码风格,但实际上我们在这里寻求实现的只是创建游戏循环并在适当的时间启动它。我相信代码有 1000 个单词(有时可能只有 1000 个单词 :)),但下面是一些代码,它们以最少的方式(仍然产生一个有效的工作示例)显示了可以创建/放置游戏循环的位置和在代码中使用,为了清晰和理解,代码被大量注释:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class MyGame {

    private Scene scene;
    private Sprite player;
    private Thread gameLoop;
    private boolean isRunning;

    public MyGame() {
        createAndShowUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MyGame::new);
    }

    /**
     * Here we will create our swing UI as well as initialise and setup our
     * sprites,scene,and game loop and other buttons etc
     */
    private void createAndShowUI() {
        JFrame frame = new JFrame("MyGame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        player = new Sprite(/*ImageIO.read(getClass().getResourceAsStream("...."))*/);

        this.scene = new Scene();
        this.scene.add(player);

        this.addKeyBindings();
        this.setupGameLoop();

        frame.add(scene);
        frame.pack();
        frame.setVisible(true);

        // after setting the frame visible we start the game loop,this could be done in a button or wherever you want
        this.isRunning = true;
        this.gameLoop.start();
    }

    /**
     * This method would actually create and setup the game loop The game loop
     * will always be encapsulated in a Thread,Timer or some sort of construct
     * that generates a separate thread in order to not block the UI
     */
    private void setupGameLoop() {
        // initialise the thread 
        gameLoop = new Thread(() -> {
            // while the game "is running" and the isRunning boolean is set to true,loop forever
            while (isRunning) {
                // here we do 2 very important things which might later be expanded to 3:
                // 1. We call Scene#update: this essentially will iterate all of our Sprites in our game and update their movments/position in the game via Sprite#update()
                this.scene.update();

                // TODO later on one might add a method like this.scene.checkCollisions in which you check if 2 sprites are interesecting and do something about it
                // 2. We then call JPanel#repaint() which will cause JPanel#paintComponent to be called and thus we will iterate all of our sprites
                // and invoke the Sprite#render method which will draw them to the screen
                this.scene.repaint();

                // here we throttle our game loop,because we are using a while loop this will execute as fast as it possible can,which might not be needed
                // so here we call Thread#slepp so we can give the CPU some time to breathe :)
                try {
                    Thread.sleep(15);
                } catch (InterruptedException ex) {
                }
            }
        });
    }

    private void addKeyBindings() {
        // here we would use KeyBindings (https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) and add them to our Scene/JPanel
        // these would allow us to manipulate our Sprite objects using the keyboard below is 2 examples for using the A key to make our player/Sprite go left
        // or the D key to make the player/Sprite go to the right
        this.scene.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,false),"A pressed");
        this.scene.getActionMap().put("A pressed",new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                player.LEFT = true;
            }
        });
        this.scene.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,true),"A released");
        this.scene.getActionMap().put("A released",new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                player.LEFT = false;
            }
        });
        this.scene.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D,"D pressed");
        this.scene.getActionMap().put("D pressed",new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                player.RIGHT = true;
            }
        });
        this.scene.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D,"D released");
        this.scene.getActionMap().put("D released",new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                player.RIGHT = false;
            }
        });
    }

    public class Scene extends JPanel {

        private final ArrayList<Sprite> sprites;

        public Scene() {
            // we are using a game loop to repaint,so probably dont want swing randomly doing it for us
            this.setIgnoreRepaint(true);
            this.sprites = new ArrayList<>();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            // this method gets called on Scene#repaint in our game loop and we then render each in our game
            sprites.forEach((sprite) -> {
                sprite.render(g2d);
            });
        }

        @Override
        public Dimension getPreferredSize() {
            // because no components are added to the JPanel,we will have a default sizxe of 0,0 so we instead force the JPanel to a size we want
            return new Dimension(500,500);
        }

        public void add(Sprite go) {
            this.sprites.add(go);
        }

        private void update() {
            // this method gets called on Scene#update in our game loop and we then update the sprites movement and position our game
            sprites.forEach((go) -> {
                go.update();
            });
        }
    }

    public class Sprite {

        private int x = 50,y = 50,speed = 5;
        //private final BufferedImage image;

        public boolean LEFT,RIGHT,UP,DOWN;

        public Sprite(/*BufferedImage image*/) {
            //this.image = image;
        }

        public void render(Graphics2D g2d) {
            //g2d.drawImage(this.image,this.x,this.y,null);
            g2d.fillRect(this.x,100,100);
        }

        public void update() {
            if (LEFT) {
                this.x -= this.speed;
            }
            if (RIGHT) {
                this.x += this.speed;
            }
            if (UP) {
                this.y -= this.speed;
            }
            if (DOWN) {
                this.y += this.speed;
            }
        }
    }
}

2.创建更好的游戏循环的提示

这很像我的回答中的第一点,非常主观,取决于您要实现的目标以及您的问题会以何种粒度得到满足。因此,而不是规定 1 种类型的游戏循环。让我们看看我们可以拥有的各种类型:

首先什么是游戏循环?*

游戏循环是整个游戏程序的整体流程控制。这是一个循环,因为游戏会一遍又一遍地执行一系列操作,直到用户退出。游戏循环的每次迭代都称为一个帧。大多数实时游戏每秒更新几次:30 和 60 是两个最常见的间隔。如果游戏以 60 FPS(每秒帧数)运行,这意味着游戏循环每秒完成 60 次迭代。

一个。 While 循环

我们在上面的例子中已经看到了这一点,它只是一个封装在 Thread 中的 while 循环,可能还有一个 Thread#sleep 调用来帮助限制 CPU 使用率。这和 Swing Timer 可能是您可以使用的最基本的。

gameLoop = new Thread(() -> {
    while (isRunning) {
        this.scene.update();
        this.scene.repaint();
        try {
            Thread.sleep(15);
        } catch (InterruptedException ex) {
        }
    }
});

优点:

  • 易于实施
  • 所有更新和渲染,重绘都是在与 EDT 不同的线程中完成的

缺点:

  • 无法保证在不同的 PC 上具有相同的帧速率,因此根据硬件的不同,游戏的移动在不同的计算机上可能看起来更好/更糟或更慢/更快

B. 摇摆计时器

类似于 while 循环,可以使用 Swing Timer 来定期触发动作事件,因为它是周期性触发的,我们可以简单地使用 if 语句来检查游戏是否正在运行,然后调用我们需要的方法

gameLoop = new Timer(15,(ActionEvent e) -> {
    if (isRunning) {
        MyGame.this.scene.update();
        MyGame.this.scene.repaint();
    }
});

优点:

  • 易于实施

缺点:

  • 在不需要或不需要的 EDT 上运行,因为我们没有更新任何 Swing 组件,而只是简单地对其进行绘制
  • 无法保证在不同的 PC 上具有相同的帧速率,因此根据硬件的不同,游戏的移动在不同的计算机上可能看起来更好/更糟或更慢/更快

c. 固定时间步*

这是一个更复杂的游戏循环(但比可变时间步游戏循环更简单)。这是在我们想要实现特定 FPS(即每秒 30 或 60 帧)的前提下工作的,因此我们只需确保我们调用的更新和渲染方法准确每秒次数。 更新方法不接受“已用时间”,因为它们假定每次更新都有固定的时间段。计算可以按 position += distancePerUpdate 进行。该示例包括渲染期间的插值。

gameLoop = new Thread(() -> {
    //This value would probably be stored elsewhere.
    final double GAME_HERTZ = 60.0;
    //Calculate how many ns each frame should take for our target game hertz.
    final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
    //If we are able to get as high as this FPS,don't render again.
    final double TARGET_FPS = 60;
    final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;
    //At the very most we will update the game this many times before a new render.
    //If you're worried about visual hitches more than perfect timing,set this to 1.
    final int MAX_UPDATES_BEFORE_RENDER = 5;
    //We will need the last update time.
    double lastUpdateTime = System.nanoTime();
    //Store the last time we rendered.
    double lastRenderTime = System.nanoTime();

    while (isRunning) {
        double now = System.nanoTime();
        int updateCount = 0;

        //Do as many game updates as we need to,potentially playing catchup.
        while (now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER) {
            MyGame.this.scene.update();
            lastUpdateTime += TIME_BETWEEN_UPDATES;
            updateCount++;
        }

        //If for some reason an update takes forever,we don't want to do an insane number of catchups.
        //If you were doing some sort of game that needed to keep EXACT time,you would get rid of this.
        if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) {
            lastUpdateTime = now - TIME_BETWEEN_UPDATES;
        }

        //Render. To do so,we need to calculate interpolation for a smooth render.
        float interpolation = Math.min(1.0f,(float) ((now - lastUpdateTime) / TIME_BETWEEN_UPDATES));
        MyGame.this.scene.render(interpolation);
        lastRenderTime = now;

        //Yield until it has been at least the target time between renders. This saves the CPU from hogging.
        while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
            //allow the threading system to play threads that are waiting to run.
            Thread.yield();

            //This stops the app from consuming all your CPU. It makes this slightly less accurate,but is worth it.
            //You can remove this line and it will still work (better),your CPU just climbs on certain OSes.
            //FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
            //On my OS it does not unpuase the game if i take this away
            try {
                Thread.sleep(1);
            } catch (Exception e) {
            }

            now = System.nanoTime();
        }
    }
});

这个循环需要进行其他更改以允许插值:

场景:

public class Scene extends JPanel {

    private float interpolation;

    @Override
    protected void paintComponent(Graphics g) {
        ...
        sprites.forEach((sprite) -> {
            sprite.render(g2d,this.interpolation);
        });
    }

    public void render(float interpolation) {
        this.interpolation = interpolation;
        this.repaint();
    }
}

精灵:

public class Sprite {

    public void render(Graphics2D g2d,float interpolation) {
        g2d.fillRect((int) (this.x + interpolation),(int) (this.y + interpolation),100);
    }

}

优点:

  • 各种计算机/硬件上的可预测、确定性 FPS
  • 更清晰的计算代码

缺点:

  • 未同步到监视器 v-sync(除非您进行插值,否则会导致图形抖动)- 此示例进行插值
  • 有限的最大帧速率(除非您进行插值) - 此示例进行插值

d。 可变时间步*

通常在实现物理系统时使用,或者在需要记录经过时间时使用,即动画。物理/动画更新通过“自上次更新后经过的时间”参数传递,因此依赖于帧率。这可能意味着按照 position += distancePerSecond * timeElapsed 进行计算。

gameLoop = new Thread(() -> {
    // how many frames should be drawn in a second
    final int FRAMES_PER_SECOND = 60;
    // calculate how many nano seconds each frame should take for our target frames per second.
    final long TIME_BETWEEN_UPDATES = 1000000000 / FRAMES_PER_SECOND;
    // track number of frames
    int frameCount;
    // if you're worried about visual hitches more than perfect timing,set this to 1. else 5 should be okay
    final int MAX_UPDATES_BETWEEN_RENDER = 1;

    // we will need the last update time.
    long lastUpdateTime = System.nanoTime();
    // store the time we started this will be used for updating map and charcter animations
    long currTime = System.currentTimeMillis();

    while (isRunning) {
        long now = System.nanoTime();
        long elapsedTime = System.currentTimeMillis() - currTime;
        currTime += elapsedTime;

        int updateCount = 0;
        // do as many game updates as we need to,potentially playing catchup.
        while (now - lastUpdateTime >= TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BETWEEN_RENDER) {
            MyGame.this.scene.update(elapsedTime);//Update the entity movements and collision checks etc (all has to do with updating the games status i.e  call move() on Enitites)
            lastUpdateTime += TIME_BETWEEN_UPDATES;
            updateCount++;
        }

        // if for some reason an update takes forever,we don't want to do an insane number of catchups.
        // if you were doing some sort of game that needed to keep EXACT time,you would get rid of this.
        if (now - lastUpdateTime >= TIME_BETWEEN_UPDATES) {
            lastUpdateTime = now - TIME_BETWEEN_UPDATES;
        }

        MyGame.this.scene.repaint(); // draw call for rendering sprites etc

        long lastRenderTime = now;

        //Yield until it has been at least the target time between renders. This saves the CPU from hogging.
        while (now - lastRenderTime < TIME_BETWEEN_UPDATES && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
            Thread.yield();
            now = System.nanoTime();
        }
    }
});

场景:

public class Scene extends JPanel {

    private void update(long elapsedTime) {
        // this method gets called on Scene#update in our game loop and we then update the sprites movement and position our game
        sprites.forEach((go) -> {
            go.update(elapsedTime);
        });
    }
}

精灵:

public class Sprite {

    private float speed = 0.5f;
    
    public void update(long elapsedTime) {
        if (LEFT) {
            this.x -= this.speed * elapsedTime;
        }
        if (RIGHT) {
            this.x += this.speed * elapsedTime;
        }
        if (UP) {
            this.y -= this.speed * elapsedTime;
        }
        if (DOWN) {
            this.y += this.speed * elapsedTime;
        }
    }
}

优点:

  • 光滑
  • 更容易编码

缺点:

  • 非确定性,在非常小的或大的步骤中不可预测
本文链接:https://www.f2er.com/1035770.html

大家都在问