贪吃蛇代码
//主页面
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame("小建建的贪吃蛇");
frame.setBounds(10,10,900,720);
frame.setResizable(false);//窗口大小不可变
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//正常游戏界面应该在上面
frame.add(new GamePanel());
frame.setVisible(true);
}
}
//游戏面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//蛇的数据结构
int length;
int[] snakeX = new int[600];//蛇的X坐标
int[] snakeY = new int[500];//蛇的Y坐标
String fx;
int foodX,foodY;//食物的坐标
Random random = new Random();
int score; //成绩
boolean isStart = false;//游戏状态,默认停止
boolean isFail = false;//游戏是否失败,默认不失败
Timer timer = new Timer(100,this);//定时器,100毫秒执行一次
//构造器
public GamePanel(){
init();
this.setFocusable(true);//获得焦点事件
this.addKeyListener(this);//获得键盘监听事件
timer.start();//游戏开始就进行监听
}
//初始化方法
public void init(){
length = 3;
snakeX[0] = 100;snakeY[0] = 100;//脑袋位置
snakeX[1] = 75;snakeY[1] = 100;//第一个身体位置
snakeX[2] = 50;snakeY[2] = 100;//第二个身体位置
fx = "R";//初始方向向右
score = 0;
//将食物随机放到页面中
foodX = 25 + 25 * random.nextInt(34);
foodY = 75 + 25 * random.nextInt(24);
}
//绘制面板