1

这是我制作的乒乓球游戏,但唯一不起作用的是球拍移动。我不确定如何使键盘与程序一起使用。这是主游戏的代码:

//Project: A program where you play the game pong

//This module defines the properties of the user interface

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


public class pongframe extends JFrame
{
    private JLabel playerlefttitle;
    private JLabel playerrighttitle;
    private JLabel speedtitle;
    private JTextField speedfield;
    private JTextField playerleftscorefield;
    private JTextField playerrightscorefield;
    private JButton newgame;
    private JButton gobutton;
    private JButton pausebutton;
    private JButton quitgame;
    private Timer systemclock;
    private Timer paddleclock;
    private String speedstring;
    private int speed;
    private int leng = 10;
    private int delayinterval;
    private float millisecondpersecond = 1000.0f;
    private boolean win = false;
    private int playerleftscore=0;
    private int playerrightscore=0;
    private boolean rightup = false;
    private boolean rightdown = false;
    private boolean leftup = false;
    private boolean leftdown = false;
    private boolean barhit = true;
    private double direction=0;
    private pongoperations graphicalpanel;
    private Clockhandlerclass clockhandler;
    private PaddleClockHandlerClass paddleclockhandler;
    private PaddleHandlerClass paddlehandler;

    public pongframe()
    {
        super("Pong");
        JPanel panel1 = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        graphicalpanel = new pongoperations();
        graphicalpanel.setBackground(Color.GREEN);
        add(graphicalpanel, BorderLayout.CENTER);

        add(panel1, BorderLayout.SOUTH);
        c.insets = new Insets(0,0,10,10);
        newgame = new JButton("New");
        c.gridx = 0;
        c.gridy = 1;
        panel1.add(newgame, c);
        speedtitle = new JLabel("Speed");
        c.gridx = 1;
        c.gridy = 0;
        panel1.add(speedtitle, c);
        speedfield = new JTextField(3);
        c.gridx = 1;
        c.gridy = 1;
        panel1.add(speedfield, c);
        quitgame = new JButton("Quit");
        c.gridx = 2;
        c.gridy = 1;
        panel1.add(quitgame, c);
        playerlefttitle = new JLabel("Player Left");
        c.gridx = 0;
        c.gridy = 3;
        panel1.add(playerlefttitle, c);
        playerrighttitle = new JLabel("Player Right");
        c.gridx = 3;
        c.gridy = 3;
        panel1.add(playerrighttitle, c);
        playerleftscorefield = new JTextField(2);
        playerleftscorefield.setEditable(false);
        c.gridx = 0;
        c.gridy = 4;
        panel1.add(playerleftscorefield, c);
        gobutton = new JButton("Go");
        c.gridx = 1;
        c.gridy = 4;
        panel1.add(gobutton, c);
        pausebutton = new JButton("Pause");
        c.gridx = 2;
        c.gridy = 4;
        panel1.add(pausebutton, c);
        playerrightscorefield = new JTextField(2);
        playerrightscorefield.setEditable(false);
        c.gridx = 3;
        c.gridy = 4;
        panel1.add(playerrightscorefield, c);
        buttonhandler myhandler = new buttonhandler();
        newgame.addActionListener(myhandler);
        gobutton.addActionListener(myhandler);
        pausebutton.addActionListener(myhandler);
        quitgame.addActionListener(myhandler);
        clockhandler = new Clockhandlerclass();
        paddleclockhandler = new PaddleClockHandlerClass();
        paddlehandler = new PaddleHandlerClass();
    }
    private class buttonhandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            graphicalpanel.reset();
            if(event.getSource() == newgame)
            {
                speedfield.setText("");
                playerleftscore = 0;
                playerrightscore = 0;
                playerleftscorefield.setText("0");
                playerrightscorefield.setText("0");
                graphicalpanel.reset();
                graphicalpanel.repaint();
                gobutton.setEnabled(true);
                speedfield.setEditable(true);
                newgame.setEnabled(false);
            }
            else if(event.getSource() == gobutton)
            {
                speedstring = speedfield.getText();
                leng = speedstring.length();
                if(leng == 0)
                    speed = 0;
                else 
                {
                    speed = Integer.parseInt(speedstring);
                    gobutton.setEnabled(false);
                    speedfield.setEditable(false);
                }
                newgame.setEnabled(false);
                delayinterval = (int)Math.floor(millisecondpersecond/speed + 0.5f);
                systemclock = new Timer(delayinterval, clockhandler);
                systemclock.start();
                paddleclock = new Timer(delayinterval, paddleclockhandler);
                paddleclock.start();
            }
            else if(event.getSource() == pausebutton)
            {
                gobutton.setEnabled(true);
                newgame.setEnabled(true);
                systemclock.stop();
            }
            else if(event.getSource() == quitgame)
            {
                System.exit(0);
            }
            else
                System.out.println("Unkown error");
        }
    }
    private class Clockhandlerclass implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            if(event.getSource() == systemclock)
            {
                graphicalpanel.grabFocus();
                graphicalpanel.moveball(speed,delayinterval, direction, barhit);
                direction = graphicalpanel.changedirection(direction);

                if(win == false)
                {
                    barhit = graphicalpanel.barhits(barhit);
                    graphicalpanel.repaint();
                    win = graphicalpanel.winner();
                    playerleftscore = graphicalpanel.playerleftwin(playerleftscore);
                    playerrightscore = graphicalpanel.playerrightwin(playerrightscore);
                    playerleftscorefield.setText(Integer.toString(playerleftscore));
                    playerrightscorefield.setText(Integer.toString(playerrightscore));
                }
                else if(win == true)
                {
                    graphicalpanel.reset();
                    win = false;
                    systemclock.restart();
                    if(playerleftscore == 10)
                    {
                        newgame.setEnabled(true);
                        systemclock.stop();
                    }
                    else if(playerrightscore == 10)
                    {
                        newgame.setEnabled(true);
                        systemclock.stop();
                    }
                    graphicalpanel.repaint();
                }   
            }
            else
                System.out.printf("%s\n", "There is a bug in the clock.");
        }
    }
    private class PaddleClockHandlerClass implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            if(event.getSource() == paddleclock)
            {
                graphicalpanel.moveplayer1(rightup, rightdown);
                graphicalpanel.moveplayer2(leftup, leftdown);
                graphicalpanel.repaint();
            }
        }
    }
    private class PaddleHandlerClass implements KeyListener
    {
        public void keyTyped(KeyEvent event)
        {
        }
        public void keyPressed(KeyEvent event)
        {
            if(event.getKeyCode() == KeyEvent.VK_UP)
            {
                rightup = true;
                System.out.println("Up");
            }
            else if(event.getKeyCode() == KeyEvent.VK_DOWN)
                rightdown = true;
            if(event.getKeyCode() == KeyEvent.VK_W)
                leftup = true;
            else if(event.getKeyCode() == KeyEvent.VK_S)
                leftdown = true;
        }
        public void keyReleased(KeyEvent event)
        {
            if(event.getKeyCode() == KeyEvent.VK_UP)
                rightup = false;
            else if(event.getKeyCode() == KeyEvent.VK_DOWN)
                rightdown = false;
            if(event.getKeyCode() == KeyEvent.VK_W)
                leftup = false;
            else if(event.getKeyCode() == KeyEvent.VK_S)
                leftdown = false;
        }
    }
}   

下一段代码是我在游戏中使用的函数:

//Project: A program where you play the game pong

//This module contains the graphics and algorithms used by this project.

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;

public class pongoperations extends JPanel
{
    int widthofgraphicalarea;
    int heightofgraphicalarea;
    final int ballradius = 8;
    int ballxcoordinate;
    double ballycoordinate;
    int paddle1xcoordinate;
    int paddle1ycoordinate;
    int paddle2xcoordinate;
    int paddle2ycoordinate;

    public void paintComponent(Graphics graphicarea)
    {//function to paint the area
        super.paintComponent(graphicarea);
        this.setBackground(Color.GREEN);
        widthofgraphicalarea = getWidth();
        heightofgraphicalarea = getHeight();
        //create paddle 1
        graphicarea.setColor(Color.BLUE);
        graphicarea.fillRect(paddle1xcoordinate, paddle1ycoordinate, 10, 50);
        //create paddle 2
        graphicarea.setColor(Color.RED);
        graphicarea.fillRect(paddle2xcoordinate, paddle2ycoordinate, 10, 50);
        //Give the ball a white color
        graphicarea.setColor(Color.WHITE);
        //The 3rd and 4th parameters below represent the diameter of the ball.
        graphicarea.fillOval(ballxcoordinate,(int)ballycoordinate,2*ballradius,2*ballradius);
    }//End of method paintComponent
    public void moveplayer1(boolean rightup, boolean rightdown)
    {
        if(rightup == true)
        paddle1ycoordinate -= 5;
        else if(rightdown == true)
        paddle1ycoordinate += 5;
        positionPlayer1(paddle1xcoordinate, paddle1ycoordinate);
    }
    public void moveplayer2(boolean leftup, boolean leftdown)
    {
        if(leftup == true)
        paddle2ycoordinate -= 5;
        else if(leftdown == true)
        paddle2ycoordinate += 5;
        positionPlayer2(paddle2xcoordinate, paddle2ycoordinate);
    }
    public void positionPlayer1(int x, int y)
    {
        this.paddle1xcoordinate = x;
        this.paddle1ycoordinate = y;
        repaint();
    }
    public void positionPlayer2(int x, int y)
    {
        this.paddle2xcoordinate = x;
        this.paddle2ycoordinate = y;
        repaint();
    }
    public void moveball(int speed, int delayinterval, double direction, boolean barhit)
    {
        if(barhit == true)
            ballxcoordinate+=1;
        else if(barhit == false)
            ballxcoordinate-=1;
        if(direction > 0)
            ballycoordinate = ballycoordinate + (double)Math.sin(Math.toRadians(direction));
        else if(direction < 0)
            ballycoordinate = ballycoordinate + (double)Math.sin(Math.toRadians(direction));
    }
    public boolean barhits(boolean barhit)
    {
        if(ballxcoordinate == paddle1xcoordinate+10 && (ballycoordinate >= paddle1ycoordinate && ballycoordinate <= paddle1ycoordinate+50))
            barhit = true;
        else if(ballxcoordinate+2*ballradius == paddle2xcoordinate && (ballycoordinate+2*ballradius >= paddle2ycoordinate && ballycoordinate+2*ballradius <= paddle2ycoordinate+50))
            barhit = false;
        return barhit;
    }
    public boolean winner()
    {
        if(ballxcoordinate+2*ballradius >= widthofgraphicalarea)
            return true;
        else if(ballxcoordinate+2*ballradius <= 16)
            return true;

        return false;
    }
    public int playerleftwin(int playerleftscore)
    {
        if(ballxcoordinate+2*ballradius >= widthofgraphicalarea)
            playerleftscore+=1;

        return playerleftscore;
    }
    public int playerrightwin(int playerrightscore)
    {
        if(ballxcoordinate+2*ballradius <= 16)
            playerrightscore+=1;

        return playerrightscore;
    }
    public double changedirection(double direction)
    {//function to change the direction of the ball to bounce of walls
        if((int)ballycoordinate+2*ballradius >= heightofgraphicalarea || (int)ballycoordinate+2*ballradius < 16)
            direction = -direction;
        return direction;
    }
    public void reset()
    {//reset the ball at middle of left side
        ballxcoordinate = widthofgraphicalarea/2 - ballradius;
        ballycoordinate = heightofgraphicalarea/2 - ballradius;
        paddle1xcoordinate = 10;
        paddle1ycoordinate = heightofgraphicalarea/2-25;
        paddle2xcoordinate = widthofgraphicalarea-20;
        paddle2ycoordinate = heightofgraphicalarea/2-25;
    }
}

请有人帮忙。提前致谢。

如果您可以提供帮助,另一个问题是一旦完成,我如何将其切换为小程序形式?

4

1 回答 1

1
  • 不要使用KeyListenerSwing 组件使用KeyBindings

  • JFrame不要不必要地扩展课程

  • Swing 组件应该创建在Event Dispatch Thread

  • 要设置应用程序的大小(不setSize(..)调用JFrame),请在添加组件按钮等(您这样做)时使用适当的 LayoutManager,并在paintComponent覆盖JPanel getPreferredSize()并返回适合所有绘图的适当大小时,而不是pack()JFrame设置为可见之前调用

  • 不要忘记调用setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JFrame所以当按下X时,事件调度线程初始线程将退出,否则应用程序将继续在后台运行。

但是要在添加后解决您的问题paddlehandler = new PaddleHandlerClass();

  graphicalpanel.addKeyListener(paddlehandler);

问题是你从来没有添加KeyListener到任何组件来监听事件。

正确的解决方案是KeyBindings这样改变你 PaddleHandlerClass

private class PaddleHandlerClass {

    public PaddleHandlerClass(JComponent jc) {

        jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("UP"), "up");
        jc.getActionMap().put("up", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                rightup = true;
                System.out.println("Up");
            }
        });
        jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released UP"), "rel up");
        jc.getActionMap().put("rel up", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                rightup = false;
            }
        });
    }

}

而不是简单地创建并传递我们想要获取paddleHandler的键的实例:JPanel

paddlehandler = new PaddleHandlerClass(graphicalpanel);
于 2012-12-07T20:27:41.030 回答