一、开发思路
设定一个一定大小的且大小不可变的游戏窗口
在创建的窗口上绘制游戏的基本面板样式
使用提前保存的素材图标绘制一条静态的小蛇
使小蛇能够移动;实际只需蛇头坐标移动,每节身体覆盖前一节身体坐标,设置定时器Timer timer =new Timer();监听时间让小蛇能移动
监听键盘操作,使用户能通过键盘控制蛇的方向
定义一个食物坐标,用random随机数类实现食物随机生成
小蛇吃到食物时身体长度+1,实际是蛇头坐标与食物坐标重合时
boolean定义游戏失败的判断,当蛇头与任何身体部位坐标重合(或撞到边界)则游戏失败,可再设置积分系统,每吃到一次食物加一定分数
二 新建一个Data类,作为图片资源
package snake;
import java.net.URL;
import javax.swing.ImageIcon;
public class Data {
public static URL headerURL = Data.class.getResource("/statics/header.png");
public static ImageIcon header;
static {
assert headerURL != null;
header = new ImageIcon(headerURL);
}
public static URL upURL = Data.class.getResource("/statics/up.png");
public static URL downURL = Data.class.getResource("/statics/down.png");
public static URL leftURL = Data.class.getResource("/statics/left.png");
public static URL rightURL = Data.class.getResource("/statics/right.png");
public static ImageIcon up = new ImageIcon(upURL);
public static ImageIcon down = new ImageIcon(downURL);
public static ImageIcon left = new ImageIcon(leftURL);
public static ImageIcon right = new ImageIcon(rightURL);
public static URL bodyURL = Data.class.getResource("/statics/body.png");
public static ImageIcon body;
static {
assert bodyURL != null;
body = new ImageIcon(bodyURL);
}
public static URL foodURL = Data.class.getResource("/statics/food.png");
public static ImageIcon food;
static {
assert foodURL != null;
food = new ImageIcon(foodURL);
}
}
三 绘制静态游戏窗口
package snake;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
//创建主窗口
public class MainFrame{
public MainFrame(){
init();
}
public void ini