我(至少对我来说)非常奇怪的情况 我正在尝试重写蛇,并且移动进展非常顺利,只有蛇在吃自己,虽然我正在移除1段,并且添加1(x + 1 - 1 = x?)但蛇消失了,而Arraylist保持不变相同的尺寸(打印)。
计算蛇位置的功能(我认为是造成它的原因):
private void move() {
System.out.println(position.size());
Point toAdd = position.get(position.size() - 1);
position.remove(0);
if(dir == 1)
toAdd.y -= 5;
else if(dir == 2)
toAdd.x -= 5;
else if(dir == 3)
toAdd.x += 5;
else if(dir == 4)
toAdd.y += 5;
if(toAdd.x < 0) toAdd.x = 150;
else if(toAdd.x > 150) toAdd.x = 0;
if(toAdd.y < 0) toAdd.y = 150;
else if(toAdd.y > 150) toAdd.y = 0;
position.add(toAdd);
}
但是,要使它成为一个短的,自包含的,正确的例子:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.*;
import java.util.ArrayList;
class Snake extends JPanel implements Runnable {
int x,y;
boolean horizontal;
ArrayList<Point> position = new ArrayList<Point>();
byte dir = 3;
public Snake(JFrame parent) {
for(int i = 0; i < 5; i++)
position.add(new Point(i*5 + 10, 10));
parent.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
byte change = dir;
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
change = 4;
break;
case KeyEvent.VK_UP:
change = 1;
break;
case KeyEvent.VK_LEFT:
change = 2;
break;
case KeyEvent.VK_RIGHT:
change = 3;
break;
}
changeDirection(change);
}
});
System.out.println("starting thread");
new Thread(this).start();
}
private void changeDirection(byte change) {
if(change != dir && (change - 2 != dir || change + 2 != dir)) {
dir = change;
}
}
public void run() {
for(int i = 0; i != -1; i++){
try {
move();
this.repaint();
Thread.sleep(1000);
}
catch (InterruptedException e) {
System.out.println("INTERRUPTED");
}
}
}
private void move() {
System.out.println(position.size());
Point toAdd = position.get(position.size() - 1);
position.remove(0);
if(dir == 1)
toAdd.y -= 5;
else if(dir == 2)
toAdd.x -= 5;
else if(dir == 3)
toAdd.x += 5;
else if(dir == 4)
toAdd.y += 5;
if(toAdd.x < 0) toAdd.x = 150;
else if(toAdd.x > 150) toAdd.x = 0;
if(toAdd.y < 0) toAdd.y = 150;
else if(toAdd.y > 150) toAdd.y = 0;
position.add(toAdd);
}
public void paintComponent(Graphics g) {
g.clearRect(0,0,150,150);
for(Point p : position)
g.drawRect(p.x, p.y, 5, 5);
}
public static void main(String[] args) {
Snake snake;
JFrame f = new JFrame("Snake");
f.setSize(150, 150);
f.add((snake = new Snake(f)));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setVisible(true);
}
}
运动是我试图实施的第一件事,我还没有碰到检测/食物,这不是问题所在。
我的问题是:
为什么蛇没有收缩,而arraylist不是,我怎么能修复它,即除了前段之外阻止蛇消失?
答案 0 :(得分:6)
确定。这很简单!
您正在更改列表position
中已有的点,最后您将相同的点添加到此列表中。你最终会得到越来越多相同(通过引用)相同位置的元素。
您应该创建Point
的新实例并将其添加到列表中。
Point lastPoint = position.get(position.size() - 1);
Point toAdd = new Point(lastPoint.x, lastPoint.y);