用java实现贪吃蛇小游戏

在本类中目的是做一个背景和画板,实现贪吃蛇游戏的一个动态效果

package Snake; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Background { //容器对象 private JFrame sanke_jf = new JFrame("贪吃蛇小游戏"); private JPanel jPanel = new JPanel(); private SnakeClass snake;// private GetFood.Food food;//食物 public Background( SnakeClass snake, GetFood.Food food) { //构造器 this.food = food; this.snake = snake; } //背景的大小 public static final int BACK_WIDTH = 1210; public static final int BACK_HEIGHT = 858; //游戏相关信息的画布和画笔 private class DrawArea extends Canvas { @Override public void paint(Graphics g) { if (Is.isOver) { g.setColor(Color.black); g.setFont(new Font("Times", Font.BOLD, 45)); g.drawString("游戏结束!", 600, 350); g.drawString("你的分数:"+food.count, 600, 400); g.drawString("历史最高分:"+SaveMaxCount.read(), 600, 450); } else { if (food.color==5||food.color==10||food.color==7){ g.setColor(Color.orange); g.fillOval(food.foodx, food.foody, Node.NODE_DIA, Node.NODE_DIA); }else if(food.color==4||food.color==8){ g.setColor(Color.black); g.fillOval(food.foodx, food.foody, Node.NODE_DIA, Node.NODE_DIA); }else { g.setColor(Color.GREEN); g.fillOval(food.foodx, food.foody, Node.NODE_DIA, Node.NODE_DIA); } //蛇头(黄色) g.setColor(Color.orange); g.fillOval(snake.head.nodex, snake.head.nodey, Node.NODE_DIA, Node.NODE_DIA); //蛇的身体(蓝色) g.setColor(Color.BLUE); Node temp = snake.head; while (true) { if (temp.next == null) { g.fillOval(temp.nodex, temp.nodey, Node.NODE_DIA, Node.NODE_DIA); break; } temp = temp.next; g.fillOval(temp.nodex, temp.nodey, Node.NODE_DIA, Node.NODE_DIA); } } } } private Timer timer;//多久自动执行一次相关代码的对象 //创建绘画区域对象 DrawArea drawArea = new DrawArea(); //组装显示界面的方法 public void draw_back() { drawArea.setPreferredSize(new Dimension(BACK_WIDTH, BACK_HEIGHT));//为绘画区域设置大小 //键盘监听器,用键盘控制蛇的移动 KeyListener listener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); snake.move(keyCode); } }; //为相关区域添加监听器 jPanel.addKeyListener(listener); sanke_jf.addKeyListener(listener); drawArea.addKeyListener(listener); //设置JFrame容器的大小 sanke_jf.setSize(BACK_WIDTH, BACK_HEIGHT); //每过指定时间自动执行的任务代码 ActionListener tack = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { drawArea.repaint();//重画,实现视觉效果 snake.autmove(); if (Is.isOver) timer.stop(); } }; timer = new Timer(230, tack); timer.start(); //将绘画区域添加到容器中 jPanel.add(drawArea); sanke_jf.add(jPanel); sanke_jf.setResizable(false);//设置JFrame的大小不可变 sanke_jf.setVisible(true);//设置窗口可见 //点击右上角“x”号结束程序 sanke_jf.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { System.exit(0); } }); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzzfxz.html