Home  >  Q&A  >  body text

java - 贪吃蛇相关问题?

先附上地址:https://github.com/KingJeason/MySnake.git。
第一个问题 :
我判断蛇死亡的函数是:

private void checkDead() {

    for(`Node` n = head.next; n != null; n = n.next) {
        if(getRectangle(head).intersects(getRectangle(n))) {
            y.stop(y.gogogo);
        }
    }
    
}

意思就是遍历一遍蛇。如果蛇头的区域和蛇神的任何一个区域有交集。则死亡。
Ok。让我们回到游戏中。比如一条蛇从左到右行驶。

这时,如果迅速按下 下-左键。蛇就会死亡。原因是蛇还没有往下走一格就向左移动。则碰到了蛇的第二个节点。这就比较蛋疼了 。该如何改进。

第二个问题。
我设计的思路是由诺基亚老款机有一款贪吃蛇游戏而得。(黑白屏的那种) 就是每吃五个球。会出现一个分数比较高的大球。 先说说我写的小球的实现吧。
public void eat(Egg e){

    if(this.getRectangle(head).intersects(e.getRectangle())){
        e.reAppear();//如果蛇头和小球有交集,则改变小球的位置。
        this.addTohead();//增加蛇的一节。
        this.score += 5;//分数+5。
        
    }
}

然后我在线程里调用了这个函数。
但是大球该如何实现呢。我的思路是 在 Egg(小球)类里写一个成员变量
public static int num = 0;
然后在线程成判断

 if(e.num % 5 == 0 && e.num != 0){
                
                b.draw(g);//调用BigEgg(大球)里的draw方法。
            }

说了这么多,我的问题来了 ,大球总要吃吧。在吃完大球后,我不希望他再次出现,而是要等小球再次吃五次才出现大球。这时,eat方法该怎么写。。。
if(this.getRectangle(head).intersects(e.getRectangle())){
????
}

黄舟黄舟2714 days ago653

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 17:57:08

    I took a look at your code and give you some suggestions:

    It is not recommended to add the class files in the bin folder to git

    For question 1: Just trigger the function that checks whether the snake is dead when the snake reaches one square. I have written a greedy snake in C language before. My method is to maintain a two-dimensional array and use this two-dimensional array to represent the body of the snake. 1 means it is the body of a snake, and 0 means it is not the body of a snake.

    See: https://github.com/sadhen/snacurse

    reply
    0
  • Cancelreply