如何在J帧中以随机间隔引入障碍物(2D游戏中的矩形)?

时间:2017-11-04 09:45:07

标签: java jframe awt graphics2d

我要感谢stackoverflow社区花时间研究我的问题并帮助我完成这个项目(一些片段来自社区问题)。我是初学者,如果有任何信息含糊不清,我很抱歉不足。
我正在尝试创建一个2D游戏,其中一个球在随机间隔接近它的障碍物上跳跃(按下空格键)。但我无法弄清楚为什么障碍在执行时不会出现的原因。对问题的任何洞察都是有价值的 为简单起见,我认为屏幕上一次只能有一个障碍物。我添加了注释以增强代码的可读性。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BallTrial {

public static void main(String[] args) {
    BallTrial b = new BallTrial();
}

public BallTrial() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException ex) {
            }

            //Creates the Game Frame
            JFrame frame = new JFrame("Ball Game");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.add(new BallObstacle());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

public static class BallObstacle extends JPanel {

    //Features of the Ball
    protected static final int ballh = 20; //Height of ball
    protected static final int ballw = 20; //Width of Ball
    private float jumpvelocity;            
    private int yPos;
    //Action of gravity while jumping to reduce jumpvelocity
    private float gravity;                 
    private boolean bounce = false;

    private Timer GameBegins;

    //Features of the obstacle
    protected static final int obstacleh = 35; //Obstacle Height
    protected static final int obstaclew = 10; //Obstacle Width
    private float approachvelocity;            
    private int xPos;
    private int obstacleProb;                 //Probability of obstacle apperance 
    private boolean charge = false;

    public BallObstacle() {

        yPos = getPreferredSize().height - ballh;
        jumpvelocity = 0;
        gravity = 0.5f;

        xPos = getPreferredSize().width + obstaclew;
        approachvelocity = 0;

        //generates probablity only if there is no obstacle on the screen
        if(obstacleProb !=1)    
            obstacleProb = (int)(2 * Math.random());

        //obstacle emerges depending on probability
        if((obstacleProb == 1)&&(xPos - obstaclew == getWidth())){  
            approachvelocity = 30;
            charge = true;
        }

        //to make ball jump on pressing space
        InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
        ActionMap am = getActionMap();
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "Jump");
        am.put("Jump", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Can only bound when we're on the ground
                if (yPos + ballh == getHeight()) {
                    jumpvelocity = -7;
                    bounce = true;
                }
            }
        });

        GameBegins = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int width = getWidth();

                if (xPos + 10 > 0) {
                    if (charge) {
                        //Subtract approach velocity from xPos to
                        //make the obstacle approach the ball
                        xPos -= approachvelocity;
                    }
                }
                else{
                    //Once obstacle crosses the ball reset the
                    //obstacle to its initial position until next occurance
                    xPos = width + obstaclew;
                    charge = false;
                }

                int height = getHeight();
                if (height > 0) {
                    if (bounce) {
                        // Add the jumpvelocity to the yPos
                        // jumpvelocity may be postive or negative, allowing
                        // for both up and down movement
                        yPos += jumpvelocity;
                        // Add the gravity to the jumpvelocity, this will slow down
                        // the upward movement and speed up the downward movement
                        jumpvelocity += gravity;
                        if (yPos + ballh >= height) {
                            // Seat the sprite on the ground
                            yPos = height - ballh;
                            //Stop bouncing
                            bounce = false;
                            } 
                    }
                }
                repaint();
            }
        });
        GameBegins.start();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D ball = (Graphics2D) g.create();
        Graphics2D floor = (Graphics2D) g.create();
        Graphics2D wall = (Graphics2D) g.create();
        Graphics2D obstacle = (Graphics2D) g.create();

        obstacle.setColor(Color.GREEN);
        obstacle.fillRect(xPos,75,10,35);

        wall.setColor(Color.WHITE);
        wall.fillRect(0,0,500,200);

        floor.setColor(Color.BLACK);
        floor.fillRect(0,110,500,200);

        ball.setColor(Color.RED);
        ball.fillOval(30,yPos-90,20,20);

        obstacle.dispose();
        ball.dispose();
        wall.dispose();
        floor.dispose();
    }
}
}

执行此操作后,我打算使用intersect方法在球与障碍物碰撞时终止程序并显示分数(分数=沿x轴/ 20行进的距离)。

0 个答案:

没有答案