我为非常简单的pong编写了这段代码,一切运行良好,除了我无法弄清楚如何使KeyListener工作。我不知道在哪里放置Listener或如何使用它。欢迎任何其他提示,我是菜鸟,所以请解释到那个级别。
package pong;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Pong extends JPanel implements KeyListener
{
int border = 15;
int enemyScore = 0;
int playerScore = 0;
int ballx = 248;
int bally = 170;
int playerx = 482;
double playery = 162;
int playeryy = 162;
int enemyx = 0;
double enemyy = 162;
int enemyyy = 162;
boolean gameReset = true;
boolean down;
boolean right;
//ball movement
private void moveBall()
{
Random rand = new Random();
while (gameReset == true)
{
ballx = 240;
bally = 170;
down = rand.nextBoolean();
right = rand.nextBoolean();
gameReset = false;
}
if (right == true)
{
ballx++;
}
else
{
ballx--;
}
if (down == true)
{
bally++;
}
else
{
bally--;
}
if(bally == getHeight()-border)
{
down = false;
}
else if (bally == 0)
{
down = true;
}
if (playeryy < bally+14 && playeryy+59 > bally && ballx == 468)
{
right = false;
}
else if (ballx == getWidth()-border)
{
gameReset = true;
enemyScore ++;
}
else if (enemyyy < bally+14 && enemyyy+59 > bally && ballx == 13)
{
right = true;
}
else if (ballx == 0)
{
gameReset = true;
playerScore ++;
}
}
//enemy movement
private void moveEnemy()
{
if (right == false && bally > enemyy+8 && enemyy < 294)
{
enemyy += 0.8;
enemyyy = (int) enemyy;
}
else if (right == false && bally < enemyy+8 && enemyy > 0)
{
enemyy -= 0.8;
enemyyy = (int) enemyy;
}
}
//Drawing
@Override
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(enemyx, enemyyy, 15, 60);
g.fillRect(playerx, playeryy, 15, 60);
g.fill3DRect(ballx, bally, 15, 15, true);
System.out.println("Enemy Score: " + enemyScore + " Player Score: "+ playerScore);
}
public static void main(String[] args) throws InterruptedException
{
JFrame frame = new JFrame("p0ng"); //makes new frame
frame.setSize(512,384); //sets the size
frame.setVisible(true); //makes it visble
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //allows it to sleep
Pong game = new Pong();
frame.add(game);
while(true)
{
game.moveBall();
game.moveEnemy();
game.repaint();
Thread.sleep(10);
}
}
@Override
public void keyTyped(KeyEvent ke) {
//not being used
}
//Player movement
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_UP && playery < 294)
{
playery += .8;
playeryy = (int) playery;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN && playery > 0)
{
playery -= .8;
playeryy = (int) playery;
}
repaint();
}
@Override
public void keyReleased(KeyEvent ke) {
//not being used
}
}
答案 0 :(得分:2)
欢迎任何其他提示
KeyListener
,这太不可靠,尤其是当有更好的选择时。首先看看How to Use Key Bindings paintComponent
而不是paint
。请查看Performing Custom Painting和Painting in AWT and Swing if
语句来阻止你需要/不需要根据当前状态执行的部分答案 1 :(得分:0)
public Pong(){
addKeyListner(this);
}
您需要将panel
注册到keyListner
。
您可以使用addKeyListner
方法执行此操作,因为您已将Keylistner
实施到同一class
。您可以使用this
关键字。您可以在constructor
。