日期:2014-05-20  浏览次数:20643 次

贪吃蛇小游戏里面的蛇怎么能自动跑起来
刚学java,写贪吃蛇小游戏,只有输入方向键,才能走动,怎么能初始化的时候,蛇就能跑起来?求思路?
游戏 Java 贪吃蛇

------解决方案--------------------
贪吃蛇的一个秘诀:砍掉尾巴放头上,像下面那样,把尾巴上的那个0拿出来放到头前面去,是不是就向前走了一步?
00000
 00000
  00000
------解决方案--------------------
刚开始的时候设个默认的方向让蛇走:在头结点添加,在尾节点删除,另外要设置键盘触发事件,具体的去网上搜搜吧
------解决方案--------------------
游戏不是fps的嘛,
1、首先确定蛇头。
2、每X fps,让蛇朝着蛇头的方向移动 (即不停的改变 x或 y坐标的值,重新画蛇)
3、X值,随难度提高而越来越快,这样蛇也就跑的越来越快了。
4、反正键盘控制的是蛇头。


------解决方案--------------------
用一个while循环,里面要有判断向左向右还是向下向上的条件语句,除非你触发换方向,否则蛇就会一直向某个方向移动。
当然这个移动你应该知道怎么编吧(就是你按一下动一下的那个)。
你还可以给个判断是否继续的参数给while循环,以便蛇出界时就结束游戏。(如果设置不给,设置为true,那也可以,游戏永不结束而已)
------解决方案--------------------
以前练习写的一个蛇的例子,没写完,当时是想用线程来画来着。



import javax.swing.*;
import java.awt.*;
import java.util.*;


class GameThread implements Runnable
{
private GamePanle gamePanel;
private final int fps = 40;

public GameThread(final GamePanle gamePanel)
{
this.gamePanel = gamePanel;
}


public void run()
{
while (true)
{
try
{
gamePanel.logic();
gamePanel.draw();
Thread.sleep(1000/fps);
}
catch (Exception e)
{
e.printStackTrace();
}

}
}
}



class Snake
{
//蛇头的开始位置
public int x = 200;
public int y = 100;
private int speed = 5;
//1,2,3,4 表示4个方向
private byte direct = 1;
//简单起见就3节
private ArrayList<Body> bodys = new  ArrayList<Body>(); 

class Body
{
int x,y;
int w = 20;
int h = 20;
//0 往下走 1往上走  2 往右 3 往左
int dir = 3;

public Body(int x,int y)
{
this.x = x;
this.y = y;
}

public void move()
{

//测试距离
int dleft = x;
int dright = GamePanle.WIDTH - x;
int dtop = y;
int dbottom = GamePanle.HEIGHT - y;
System.out.println("{"+dleft+","+dright+","+dtop+","+dbottom+"}");


//靠左边的时候
if (dleft <= w)
{
//到了左上角
if (dtop < h)
{
dir = 1 ;
}
//到了左下角
else if (dbottom < h)
{
dir = 2 ;
}
else
//中间
{
dir = 0;
}
}

//靠右边的时候
if (dright <= w)
{