所以我试图制作一个游戏,其中一个街区从天而降,你必须躲闪它。我使用keylistener移动播放器,使用计时器移动掉落的块。我可以移动播放器,在那里重新制作作品;这是问题所在的红色区块。
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class boxface extends JComponent implements KeyListener {
private int x=0, y=0;
final static java.util.Timer tmr = new java.util.Timer();
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_RIGHT)
moveRight();
else if(e.getKeyCode()== KeyEvent.VK_LEFT)
moveLeft(); }
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
Rectangle player = new Rectangle(x, 400, 50, 50);
Rectangle bg = new Rectangle(0, 0, 700, 750);
int x2 = ((int)((Math.random()*3)))*50;
Rectangle enemy = new Rectangle(x2, y, 50, 50);
int temp = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fill(bg);
g2.setColor(Color.WHITE);
g2.fill(player);
g2.setColor(Color.RED);
g2.fill(enemy); }
public void moveLeft() {
if(x > 0) {
x -= 50;
player.setLocation(x, 400);
repaint();}}
public void moveRight() {
if(x < 100) {
x += 50;
player.setLocation(x, 400);
repaint();} }
public void enemyDown() {
if(enemy.getBounds().y == 400) {
x2=((int)((Math.random()*3)))*50;
y=0;
enemy.setLocation(x2, y);
repaint(); }
else {
y = y + 50;
enemy.setLocation(x2, y);
repaint();} }
public void intersector() {
if(enemy.intersects(player))
tmr.cancel(); }
public boxface(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false); }
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(400, 200, 156, 479);
f.setMinimumSize(new Dimension(156, 0));
f.setResizable(false);
f.getContentPane().add(new boxface());
f.setVisible(true);
}
});
tmr.scheduleAtFixedRate(new TimerTask() {
public void run()
{
boxface exec = new boxface();
exec.enemyDown();
exec.intersector();
}
},0,10000);
}
}
经过一些实验,只有enemyDown()的底部被激活(&#34; else&#34;语句,而不是&#34; if&#34;),但它重置了y co每次都是红色的。无论如何,该程序永远不会重新粉碎敌人,所以它并不重要。在过去的72小时里,我已经睡了2个小时,所以这可能是一个非常愚蠢,简单的错误,但是现在我无法找到解决这个问题的方法。