0
即時通訊相當新的Java和我很困惑如何做到這一點。我有一個聽取WASD的關鍵聽衆,它指示我的Snake的移動。關鍵聽衆改變了我的蛇段的x和y位置。我有一個計時器鏈接到名爲「Listener」的監聽器,該監聽器將移動重新繪製到緩衝區和屏幕上。我的問題是,爲什麼我的關鍵聽衆指示的移動不會將其放到緩衝區中?另外,我知道我的移動功能工作原因是snek.move(4);在計時器中工作。最後說明,這是一個我幾乎沒有開始的Snake遊戲。聆聽者和定時器之間的通信
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class SnekePanel extends JPanel
{
private static final int FRAME1 = 1000;
private static final int FRAME2 = 1000;
private static final Color BACKGROUND = new Color(0, 0, 0);
private BufferedImage myImage;
private Graphics myBuffer;
private Sneke snek;
private Food food;
private Timer t;
private int points = 0;
public SnekePanel()
{
myImage = new BufferedImage(FRAME1, FRAME2, BufferedImage.TYPE_INT_RGB);
myBuffer = myImage.getGraphics();
myBuffer.setColor(BACKGROUND);
myBuffer.fillRect(0, 0, FRAME1,FRAME2);
int xPos = (int)(Math.random()*(FRAME1-100) + 50);
int yPos = (int)(Math.random()*(FRAME2-100)+ 50);
food = new Food(xPos, yPos, 10, Color.RED);
snek = new Sneke(200,200,1,Color.WHITE);
t = new Timer(5, new Listener());
t.start();
addKeyListener(new Key());
setFocusable(true);
}
public void paintComponent(Graphics g)
{
g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
}
private class Key extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_W)
{
snek.move(1);
}
if(e.getKeyCode() == KeyEvent.VK_A)
{
snek.move(2);
}
if(e.getKeyCode() == KeyEvent.VK_S)
{
snek.move(3);
}
if(e.getKeyCode() == KeyEvent.VK_D)
{
snek.move(4);
}
}
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(snek.checkBlock() != 0)
{
myBuffer.setColor(BACKGROUND);
myBuffer.fillRect(0,0,FRAME1,FRAME2);
snek.move(4);
collide(snek, food);
food.draw(myBuffer);
snek.draw(myBuffer);
myBuffer.setColor(Color.BLACK);
repaint();
}
}
}
private void collide(Sneke b, Food pd)
{
int sx = b.getX(snek.getLength()-1);
int sy = b.getY(snek.getLength()-1);
int fx = pd.getX();
int fy = pd.getY();
if(sx == sy && fx == fy)
{
snek.setLength(snek.getLength()+1);
}
}
}
很好,因爲關鍵監聽改變蛇的領域,然後蛇在計時器重新繪製,我希望計時器反映關鍵聽衆的I/O。 –
@SompTingWong:好吧,因爲你的計時器改變了字段,所以你需要調整你的期望。也許你不應該在定時器中設置蛇的狀態。 –
@SompTingWong:查看使用密鑰綁定的示例請 –