java - 如何在 java 2d 射击游戏中将计时器设置为 1 分钟?

标签 java multithreading swing timer awt

我需要将其实现到我的程序中的确切代码。我只想玩游戏一分钟,然后在一分钟后打印到游戏结束。如果有人能准确地告诉我它在我的程序中应该放在哪里,我也将不胜感激。请有人帮我解决这个问题。我的时间真的很紧迫。谢谢

这是我的代码:

    import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 320;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE =2;
    public final String TITLE ="2D SPACE GAME";
    public final String NAME ="Sound";


    private boolean running = false;
    private Thread thread;

    private BufferedImage image =
       new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

    private BufferedImage spriteSheet= null;
    private BufferedImage background = null;

    private boolean  is_shooting = false; 

    private Player p;
    private Controller c;
    private  Textures tex;

    public void init(){
        //which will let the ship move better
        requestFocus();
        Sound.sound2.play();
        BufferedImageLoader loader= new BufferedImageLoader();
        try{

            spriteSheet = loader.loadImage("/sprite_sheet.png");
            background  = loader.loadImage("/background.png");
        }catch(IOException e){
            e.printStackTrace();
        }
        addKeyListener(new KeyInput(this));
        tex = new Textures(this);
        //we have to initlise the p under the try and catch or it will not work
        //"this" is refering to game from the player class 200 are the coordinates 
        // tex will contain all the images
        p = new Player(200,200,tex);
        c = new Controller(this,tex);
    }

    //if running equals true we just return out of the method
    private synchronized void start(){
        if (running)
            return;

        running=true; 
        thread = new Thread(this);
        thread.start();
    }   

    private synchronized void stop(){
        if (!running)
            return;

        //this will stop the game loop
        running=false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.exit(1);

    }

    public void run(){
        init();
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60.0; //game updates 60 times
        double ns = 1000000000 / amountOfTicks;
        double delta =0;
        int updates =0;
        int frames =0;
        long timer = System.currentTimeMillis();

        //fps helps us update.

        while(running){
            //loop for the game the heart of the game.
    long now = System.nanoTime();
    delta += (now-lastTime  ) / ns;
    lastTime = now;
    if (delta >=1){
        tick();
        updates++;

        delta--;

        }
    render();
    frames++;

    //calcuating the fps, we want to do every second.

    if(System.currentTimeMillis() - timer > 1000){
        timer+=1000;
        System.out.println(updates+ "Ticks fps "+ frames);
    updates =0;
    frames=0;

    }

    }
    stop();

    }

    private void tick(){
        p.tick();
        c.tick();
    }

    private void render(){
        //this. referes to the canvas class thats were we are getting this
        BufferStrategy bs = this.getBufferStrategy();

        //we want to intilaze once it from loading billions of times
        //we want to introduce tripple buffering 
        if (bs==null)
        {
            createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        ///////////////////////////were we draw the image

        g.drawImage(image,0,0, getWidth(), getHeight(), this);

        g.drawImage(background,0,0, null);


        p.render(g);
        c.render(g);



        /////////////////////////

        //disposing the buffered image
        g.dispose();
        bs.show();
    }

    public void keyPressed(KeyEvent e){
        int key = e.getKeyCode();
        if(key==KeyEvent.VK_RIGHT){
            p.setVelX(5);
        }else if (key==KeyEvent.VK_LEFT){
            p.setVelX(-5);
        }else if (key==KeyEvent.VK_DOWN){
            p.setVelY(5);
        }else if (key==KeyEvent.VK_UP){
            p.setVelY(-5);


        }else if (key==KeyEvent.VK_SPACE && !is_shooting  ){
            is_shooting = true;
            c.addBullet(new Bullet(p.getX(),p.getY(), tex ));
            Sound.sound1.play();
        }


    }

    public void keyReleased(KeyEvent e){
int key = e.getKeyCode();

        if(key==KeyEvent.VK_RIGHT){
            p.setVelX(0);
        }else if (key==KeyEvent.VK_LEFT){
            p.setVelX(0);
        }else if (key==KeyEvent.VK_DOWN){
            p.setVelY(0);
        }else if (key==KeyEvent.VK_UP){
            p.setVelY(0);

        }else if (key ==KeyEvent.VK_SPACE){
            is_shooting = false; // this is going to force the player to realise the key in order to be able to shoot another bullet
        }

    }

    public static void main(String args[]){

        Game game = new Game();

        game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE ));
        game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE ));
        game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE ));

        JFrame frame = new JFrame(game.TITLE);
        frame.add(game);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        game.start();


    }

        public BufferedImage getSpriteSheet(){
            return spriteSheet;

        }



}

最佳答案

  1. 使用 JPanel 代替 awt.Canvas

  2. JPanel 不需要使用 BufferStrategy(用于此作业)

  3. 使用paintComponent代替render()

  4. 使用 Swing Timer 而不是从 util.Timer 调用的 Runnable#Thread

  5. 使用 KeyBinding 而不是 KeyListener

  6. 否则 AWT 或 Swing 容器必须可针对 KeyEvents (setFocusable()) 获得焦点

  7. 这里有一堆带有动画的线程,带有paintComponent,由Swing Timer调用/延迟,由KeyBindings监听

  8. 我不建议混合使用 AWT 组件和 Swing JComponent

  9. 将所需动画的元素添加到 PaintComponent 内的 util.List 中,以在此列表中循环(或移动到/显示所需元素)

关于java - 如何在 java 2d 射击游戏中将计时器设置为 1 分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129787/

相关文章:

java - BorderLayout的参数代表什么意思?

c++ - 弹出对话框将文件保存在单独的线程中

eclipse - 使用 zip 迁移时 WindowBuilder 不显示“设计”选项卡

Java:将图像添加到JTable?

c++ - 将对象传递给多线程对象Qt

java - 如何通过单击鼠标右键获取 JTable 单元格的值

java - 如何限制javac输出?

java - 在普通 Spring 中启用 JPA 异常转换

java - 扫描仪细节

java - notify/notifyall 是否释放被持有的锁