0

先生/女士对不起这个愚蠢的问题,因为我是一个新手,请帮助我检测在线程的帮助下移动的椭圆障碍物与在箭头键的帮助下移动矩形的玩家之间的碰撞(使用 Keylistener)。这是代码

public void init()
{
    r = new Rectangle(0, 0, 50, 20);
    addKeyListener(this);
    Collision();

}
public void Collision()
    {
        if((r.x==x_pos) || (r.y==y_pos))
        System.exit(0);
    }

    public void paint (Graphics g)
{   
    g.drawString("first click the left button of mouse keeping it over the rectangle then move the rectangle by arrow keys",20,10);

    g.fillRect(r.x, r.y, r.width, r.height);
    g.setColor  (Color.red);
    g.fillOval (x_pos , 10 , 2*radius, 2*radius);
    g.setColor  (Color.black);
    g.fillOval (10 ,  y_pos , 4*radius, 1*radius);
    g.setColor  (Color.pink);
    g.fillOval (x_pos , 40 , 2*radius, 2*radius);
    g.setColor  (Color.yellow);
    g.fillOval (x_pos ,  120 , 4*radius, 2*radius);
    g.setColor  (Color.gray);
    g.fillOval (120 , y_pos , 2*radius, 1*radius);
    g.setColor  (Color.orange);
    g.fillOval (x_pos , 150, 2*radius, 2*radius);
    g.setColor  (Color.magenta);
    g.fillOval (x_pos, 260 , 3*radius, 2*radius);
    g.setColor  (Color.cyan);
    g.fillOval (240 , y_pos , 2*radius, 2*radius);
    g.setColor  (Color.green);
    g.fillOval (280 , y_pos , 2*radius, 2*radius);
    g.setColor  (Color.blue);
    g.fillOval (x_pos , 290 , 2*radius, 2*radius);
    g.setColor  (Color.orange);
    g.fillOval (x_pos , y_pos , 2*radius, 2*radius);
    g.setColor  (Color.magenta);
    g.fillOval (x_pos ,  360 , 2*radius, 2*radius);
    g.setColor  (Color.darkGray);
    g.fillOval (x_pos , 390 , 2*radius, 2*radius);

}


public void start ()
{

    Thread th1 = new Thread (this);
    th1.start ();

}

              public void stop()
{

}

public void destroy()
{

}

public void run ()
{

    while(true)
    {

        x_pos++;
        try
        {
            Thread.sleep(10);
        }
        catch(InterruptedException e){}
        if(x_pos++> getSize().width)
        x_pos=0;
        repaint();

        y_pos++;
        try
        {
            Thread.sleep(10);
        }
        catch(InterruptedException e){}
        if(y_pos++> getSize().height)
        y_pos=0;
        repaint();

    }
    }


    public void keyPressed(KeyEvent e)
    {
         int keyCode = e.getKeyCode();

         if(keyCode == KeyEvent.VK_LEFT)
        {
             r.x -= 10;
            if(r.x < 0) 
            r.x = 0;
             repaint();
         }
         else if(keyCode == KeyEvent.VK_RIGHT)
        {
            r.x += 10;
             if(r.x > getSize().width-r.width)
             {
                 r.x = getSize().width-r.width;
             }
            repaint();
        }
        else if(keyCode == KeyEvent.VK_UP)
         {
             r.y -= 10;
             if(r.y < 0) r.y = 0;
            repaint();
        }
        else if(keyCode == KeyEvent.VK_DOWN)
        {
             r.y += 10;
            if(r.y > getSize().height-r.height)
            {
                 r.y = getSize().height-r.height;
             }
            repaint();
        }

    }   
        public void keyReleased(KeyEvent e){}
         public void keyTyped(KeyEvent e){}

}

4

1 回答 1

1

这是一个基本的乒乓球游戏的代码,它可能有助于解决您的问题....

package com.piyush;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable{

boolean player1Flag1,player1Flag2, player2Flag1, player2Flag2;
boolean flag,gameOver;
private int ballX = 10, ballY = 100, player1X=10, player1Y=100, player2X=230, player2Y=100;
int scorePlayer1=0, scorePlayer2=0;
int right=5; // to the right
int left= -5; //to the left
int up=5; // upward
int down= -5; // down
int width, height; // Width and height of the ball

Thread t;

public GamePanel() {
    super();
    flag=true;
    this.setBackground(Color.GRAY);
    t=new Thread(this);
    t.start();
    // TODO Auto-generated constructor stub
}
public void keyPressed(KeyEvent evt)
{
    switch(evt.getKeyCode())
    {

        case KeyEvent.VK_W :
            player1Flag1 = true;
            break;
        case KeyEvent.VK_S : 
            player1Flag2 = true;
            break;


        case KeyEvent.VK_UP:
            player2Flag1=true;
            break;
       case KeyEvent.VK_DOWN:
           player2Flag2=true;
            break;
    }

}
public void keyReleased(KeyEvent evt)
{
    switch(evt.getKeyCode())
    {

        case KeyEvent.VK_W :
            player1Flag1 = false;
            break;
        case KeyEvent.VK_S : 
            player1Flag2 = false;
            break;


        case KeyEvent.VK_UP:
            player2Flag1=false;
            break;
       case KeyEvent.VK_DOWN:
           player2Flag2=false;
            break;
    }

}

public void paintComponent(Graphics gc){

    super.paintComponent(gc);


    gc.setColor(Color.black);
    gc.fillOval(ballX, ballY, 8,8);


    gc.fillRect(player1X, player1Y, 10, 25);
    gc.fillRect(player2X, player2Y, 10, 25);


    gc.drawString("Player1: "+scorePlayer1, 25, 10);
    gc.drawString("Player2: "+scorePlayer2, 150, 10);

    if(gameOver)
        gc.drawString("Game Over", 100, 125);
}


public void positionBall(int nx, int ny)
{
    ballX= nx; 
    ballY= ny; 
    this.width=this.getWidth();
    this.height=this.getHeight();
    repaint();
}
 public void moverPlayer1()
    {
        if (player1Flag1 == true && player1Y >= 0)
            player1Y += down;
        if (player1Flag2 == true && player1Y <= (this.getHeight()-25))
            player1Y += up;
        positionPlayer1(player1X, player1Y);
    }


    public void moverPlayer2()
    {
        if (player2Flag1 == true && player2Y >= 0)
            player2Y += down;
        if (player2Flag2 == true && player2Y <= (this.getHeight()-25))
            player2Y += up;
        positionPlayer2(player2X, player2Y);
    }


    public void positionPlayer1(int x, int y){
        this.player1X=x;
        this.player1Y=y;
        repaint();
    }

    public void positionPlayer2(int x, int y){
        this.player2X=x;
        this.player2Y=y;
        repaint();
    }

@Override
public void run() {
    boolean rToL=false;
    boolean dToU=false;

    while(true){

        if(flag){

        if (rToL) 
        {

            ballX += right;
            if (ballX >= (width - 8))
                rToL= false;
        }
        else
        {

            ballX += left;
            if ( ballX <= 0)
                rToL =  true;
        }



        if (dToU) 
        {

            ballY += up;
            if (ballY >= (height - 8))
                dToU= false;

        }
        else
        {

            ballY += down;
            if ( ballY <= 0)
                dToU =  true;
        }
       positionBall(ballX, ballY);


        try 
        {
            Thread.sleep(50);
        }
        catch(InterruptedException ex)
        {

        }


        moverPlayer1();


        moverPlayer2();


        if (ballX >= (width - 8))
            scorePlayer1++;


        if ( ballX == 0)
            scorePlayer2++;


        if(scorePlayer1==5 || scorePlayer2==5){
            flag=false;
            gameOver=true;
        }


        if(ballX==player1X+10 && ballY>=player1Y && ballY<=(player1Y+25))
            rToL=true;


        if(ballX==(player2X-5) && ballY>=player2Y && ballY<=(player2Y+25))
            rToL=false;
        }
    }

}

}

测试类如下:

package com.piyush;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

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

    public class Test extends JFrame{


private JPanel jContentPane = null;

private GamePanel panel = null; 

private GamePanel getPanel() {
    if (panel == null) {
        panel = new GamePanel(); 
    }
    return panel;
}

/**
 * This is the default constructor
 */
public Test() {
    super();
    initialize();
          this.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent evt) {
            formKeyPressed(evt);
        }

        public void keyReleased(KeyEvent evt) {
            formKeyReleased(evt);
        }
    });

}


private void formKeyPressed(KeyEvent evt)
{
    panel.keyPressed(evt);
}

private void formKeyReleased(KeyEvent evt)
{
    panel.keyReleased(evt);
}


private void initialize() {
    this.setResizable(false);
    this.setBounds(new Rectangle(312, 184, 250, 250)); 
    this.setMinimumSize(new Dimension(250, 250));
    this.setMaximumSize(new Dimension(250, 250));
    this.setBackground(Color.gray);     
    this.setContentPane(getJContentPane());
    this.setTitle("Pong");
}

/**
 * This method initializes jContentPane
 * 
 * @return javax.swing.JPanel
 */
private JPanel getJContentPane() {
    if (jContentPane == null) {
        jContentPane = new JPanel();
        jContentPane.setLayout(new BorderLayout());
        jContentPane.add(getPanel(), BorderLayout.CENTER);
        jContentPane.setBackground(Color.gray);
    }
    return jContentPane;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Test m = new Test();
            m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            m.setVisible(true);
        }
    });
}

}

如果您不能理解任何部分,请告诉我。

于 2012-07-24T11:31:22.477 回答