介绍
这篇文章主要讲解了“GUI怎么制作java贪吃蛇游戏”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“GUI怎么制作java贪吃蛇游戏”吧!
项目结构
新建一个JFrame窗口,作为程序入口
public class GameStart { ,public static  void main (String [], args), { JFrame 才能;JFrame =, new JFrame (); jFrame.setBounds才能(100100900720); jFrame.setDefaultCloseOperation才能(WindowConstants.EXIT_ON_CLOSE); jFrame.setResizable才能(假); jFrame.add才能(new GameJPanel ()); jFrame.setVisible才能(真正的); ,} }
创建一个面板类
//面板 public class  GameJPanel extends JPanel  implements ActionListener { ,int 长度;//蛇的长度 ,int [] snakeX =, new int[600];//蛇的X的最大长度 ,int [] snakeY =, new int[500];//蛇的Y的最大长度 ,String fx =,“R"; ,boolean isStart =, false;//默认不开始 ,//定时器 ,Timer Timer =, new 计时器(100,,这个);//100毫秒=1秒 ,int foodX; foodY, int ; ,Random Random =, new 随机();//随机数 ,boolean isFail =, false;//失败条件 ,int 分数; ,public GameJPanel (), { ,,init (); this.setFocusable才能(真正);//获取焦点事件 addKeyListener才能(new GameKeyListener(这));//开才能启定时器 timer.start才能(); ,} ,//初始化 ,void init (), { 时间=length 才能;3; snakeX才能[0],=,100; 阴险的才能[0],=,100;//第一个身体 snakeX才能[1],=,75; 阴险的才能[1],=,100;//第二个身体 snakeX才能[2],=,50; 阴险的才能[2],=,100;//第三个身体 fx =,才能“R";//才能食物随机分布 foodX 才能=,25,+,25,*,random.nextInt (34); foodY 才能=,75,+,25,*,random.nextInt (24); 时间=score 才能;0; ,} ,//绘制面板,所有东西都是通过图形这个画笔绘制 ,@Override ,protected void  paintComponent (Graphics 图形),{ super.paintComponent才能(图形);//清屏//才能添加静态布的局 GameData.header.paintIcon才能(这,图形,25日,11); graphics.fillRect才能(25,75,,850,,600);//积才能分板 graphics.setColor才能(Color.white); graphics.setFont才能(new 字体(“微软雅黑,,,Font.BOLD,, 18)); graphics.drawString才能(“长度:“+长度,750,35); graphics.drawString才能(“得分:“+得分,750年,55岁);//先才能画食物,防止吃掉有延迟 GameData.food.paintIcon才能(图形,这一点,还以为,foodX,香);//画才能小蛇 switch 才能;(外汇),{ ,,case “R": ,,,GameData.right.paintIcon(图形,这一点,还以为;snakeX[0],,阴险的[0]); ,,,休息; ,,case “L": ,,,GameData.left.paintIcon(图形,这一点,还以为;snakeX[0],,阴险的[0]); ,,,休息; ,,case “U": ,,,GameData.up.paintIcon(图形,这一点,还以为;snakeX[0],,阴险的[0]); ,,,休息; ,,case “D": ,,,GameData.down.paintIcon(图形,这一点,还以为;snakeX[0],,阴险的[0]); ,,,休息; ,,}//身才能体 for 才能;(int 小姐:=,1;,小姐:& lt;,长度;,我+ +),{ ,,GameData.body.paintIcon(图形,这一点,还以为;snakeX[我],阴险的[我]); ,,}//才能游戏状态 if 才能;(! isStart), { ,,graphics.setColor (Color.white); ,,graphics.setFont (new 字体(“微软雅黑,,,Font.BOLD,, 40));//设置字体 ,,graphics.drawString(“按下空格,开始游戏“,,300,,300); ,,}//才能游戏失败 if 才能;(isFail), { ,,graphics.setColor (Color.red); ,,graphics.setFont (new 字体(“微软雅黑,,,Font.BOLD,, 40)); ,,graphics.drawString(“游戏失败,请按空格继续“,,300,,300); ,,} ,} ,//事件监听——固定事件刷新一次,1 s=100毫秒 ,@Override ,public void  actionPerformed (ActionEvent actionEvent), { if 才能;(isStart ,,, ! isFail), { ,,//吃食物 ,,if (snakeX [0],==, foodX ,,,阴险的[0],==,好吃),{ ,,,//长度+ 1 ,,,长度+ +; ,,,+=10分; ,,,//重新随机绘制食物 ,,,foodX =, 25, +, 25, *, random.nextInt (34); null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nulljava GUI怎么制作贪吃蛇游戏