2 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
沒有 MCVE 就不可能知道您的問題出在哪里,但設(shè)計(jì)似乎過于復(fù)雜。不要使用段,而是使用點(diǎn)。
假設(shè)你的觀點(diǎn)看起來像
class Point {
int x, y;
// getters/setters if you want
}
然后蛇由一個(gè)點(diǎn)列表和一個(gè)方向表示:
class Snake {
List<Point> body = new LinkedList<>();
Point head; // easier to separate the head, but you can do with including it in the list
Direction dir;
}
您可以添加next()方法來計(jì)算蛇的表示:
void next() {
int temp1x = head.x;
int temp1y = head.y;
switch(dir) {
case LEFT:
head.x -= stepSize;
break;
//...
}
int temp2x, temp2y;
for (Point point : points) {
temp2x = point.x;
temp2y = point.y;
point.x = temp1x;
point.y = temp1y;
temp1x = temp2x;
temp1y = temp2y;
}
}
我會(huì)把它留給你來簡(jiǎn)化實(shí)現(xiàn)(如果你擴(kuò)展類以允許它,你可以使用Point而不是單獨(dú)的 x 和 y ints Point)。
筆記:
LinkedList 確實(shí)是列表實(shí)現(xiàn)的不錯(cuò)選擇。
方法名稱以小寫字母開頭(next而不是Next)。

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
創(chuàng)建新段時(shí),您傳遞第一個(gè)段的位置對(duì)象,而不是該位置的 COPY。所以你所有的段對(duì)象共享非常相同的位置對(duì)象。如果您在新段內(nèi)修改它,它也會(huì)在所有其他段中修改,因?yàn)樗峭粋€(gè)對(duì)象。(當(dāng)你傳遞一個(gè)對(duì)象時(shí),你傳遞的是對(duì)象的引用,而不是對(duì)象的值。)所以而不是這一行:
Point head = nodes.getFirst().location;
用這個(gè):
Point head = new Point(nodes.getFirst().location);
添加回答
舉報(bào)