我正在制作蛇游戏;蛇在光标后面移动。蛇的运动很完美,但它的身体看起来像一条圆圈。
哪里的圈子应该出现在自己的盒子里。我调试了程序并试图弄清楚问题,但是在得到每个圈子的x位置和y位置的值后我感到困惑,因为它显示了一个差距btw每个圆圈有20个像素(圆圈大小),因此它应该在自己的方框中显示它们但不是。我无法弄清问题在哪里,这是我的类代码,它吸引蛇并移动它:
`import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel implements MouseMotionListener {
int x_Cur;
int y_Cur;
int dots;
int delta_x, delta_y;
double angle;
double x_inc, y_inc;
double speed = 5.0;
int max_points = (600 * 600);
final int x_positions[] = new int[max_points];
final int y_positions[] = new int[max_points];
public Game() {
addMouseMotionListener(this);
setFocusable(true);
setPreferredSize(new Dimension(600, 600));
setVisible(true);
first_Snake();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.green);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.setColor(Color.yellow);
g.fillOval(x_positions[z], y_positions[z], 20, 20);
} else {
g.setColor(Color.green);
g.fillOval(x_positions[z], y_positions[z], 20, 20);
}
System.out.println("xs"+z+"="+x_positions[z]+"\n"+"ys"+z+"="+y_positions[z]);
}
try {
Thread.sleep(10);
} catch (Exception e) {
}
delta_x = x_Cur - x_positions[0];
delta_y = y_Cur - y_positions[0];
angle = Math.atan2(delta_y, delta_x);
double speed = Math.sqrt(delta_x * delta_x + delta_y * delta_y);
speed = Math.min(speed, 2.5);
x_inc = (speed * Math.cos(angle));
y_inc = (speed * Math.sin(angle));
move();
}
public void move(){
if(!(delta_x==0&&delta_y==0)){
for (int z = dots; z > 0; z--) {
x_positions[z] = x_positions[z-1];
y_positions[z] = y_positions[z-1];
}
}
x_positions[0]+= x_inc;
y_positions[0]+= y_inc;
action();
}
public void action(){
repaint();
}
public void first_Snake() {
dots = 20;
for (int z = 0; z < dots; z++) {
x_positions[z] = 50 - z * 20;
y_positions[z] = 50;
}
}
@Override
public void mouseDragged(MouseEvent me) {
}
@Override
public void mouseMoved(MouseEvent me) {
x_Cur = me.getX() - 20;
y_Cur = me.getY() - 20;
}
}`
这是包含主要方法的类:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Snake extends JFrame {
public Snake() {
add(new Game());
setTitle("Snake");
pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame ex = new Snake();
ex.setVisible(true);
}
});
}
}
请帮忙。