程序效果:

代码:

//Snake.java  1 package snake;

 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Random;
 class go implements Runnable {
     Snake s;
     Random random;
     int foodX = 15, foodY = 15;
 int N;
     go(Snake snake) {
         s = snake;
         random = new Random();
         N=s.N;
     }
     Point getFood() {
         Point p = new Point();
         Iterator<Point> it = s.list.iterator();
         Point temp = it.next();
         boolean isFoodinBody = true;
         while (isFoodinBody) {
             foodX = Math.abs(random.nextInt()) % N;
             foodY = Math.abs(random.nextInt()) % N;
             isFoodinBody = false;
             while (it.hasNext()) {
                 temp = (Point) it.next();
                 if (foodX == temp.x && temp.y == foodY) {
                     isFoodinBody = true;
                     break;
                 }
             }
         }
         return p;
     }
     public void run() {
         while (true) {
             Point first = s.list.getFirst();
             int x = first.x, y = first.y;
             int gotfood = 0;
             if (foodX == x && foodY == y) {
                 if (!s.isDead) {
                     s.SCORE += 100;
                     s.scoreField.setText("SCORE:  "+new Integer(s.SCORE).toString());
                     s.list.add(s.list.getLast());
                 }
                 gotfood = 1;
                 foodX = Math.abs(random.nextInt()) % N;
                 foodY = Math.abs(random.nextInt()) % N;
                 s.bs[foodX][foodY].setBackground(Color.PINK);

             }
             Iterator<Point> it = s.list.iterator();
             Point temp = it.next();
             while (it.hasNext()) {
                 temp = (Point) it.next();
                 if (temp.x == x && temp.y == y) {

                     s.gameOver();

                 }
                 if (gotfood == 1 && foodX == temp.x && temp.y == foodY) {
                     Point food = getFood();
                     foodX = food.x;
                     foodY = food.y;
                     s.bs[foodX][foodY].setBackground(Color.PINK);
                     gotfood=0;
                 }
             }
             switch (s.dir) {
                 case 2 :
                     y =( (y - 1)+N )% N;
                     /*if (y == -1)
                         y = 29;*/
                     break;
                 case 0 :
                     y = (y + 1) % N;
                     break;
                 case 3 :
                     x = ((x - 1)+N) % N;
                     /*if (x == -1)
                         x = 29;*/
                     break;
                 case 1 :
                     x = (x + 1) % N;
                     break;
             }
             Point head = new Point(x, y);
             s.bs[x][y].setBackground(Color.LIGHT_GRAY);

             s.list.addFirst(head);
             Point lastP = s.list.removeLast();
             s.bs[lastP.x][lastP.y].setBackground(Color.GRAY);
             try {
                 Thread.sleep(100);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }

             /*
              * for (int i = 0; i <= list.size() - 1; i++) { System.out.print(
              * "(" + list.get(i).x + "," + list.get(i).y + ")  ");
              *
              * }
              */
             // System.out.println();

         }
     }
 }
 public class Snake extends JFrame {
     private static final long serialVersionUID = -6494984874207734357L;
     int N = 30;
     int dir = 0;// 0 右 1下 2左 3上
     int SCORE = 0;
     int a=0,b=0,c=0;
     boolean isDead = false;
     JButton[][] bs = new JButton[N][N];
     JPanel panel,scorePanel;
     JTextField scoreField,bestScoreField;
     LinkedList<Point> list;
     Snake() {
         super("Snake");
         Container container = getContentPane();
         container.setLayout(new BorderLayout());
         scorePanel = new JPanel();
         scorePanel .setLayout(new BorderLayout());
         scoreField = new JTextField(20);
         bestScoreField= new JTextField(50);
         bestScoreField.setText(getBestScores());
         bestScoreField.setEditable(false);
         scoreField.setText("SCORE:  "+new Integer(SCORE).toString());
         scoreField.setEditable(false);
         scorePanel.add(scoreField,BorderLayout.WEST);
         scorePanel.add(bestScoreField,BorderLayout.EAST);
         container.add(scorePanel, BorderLayout.NORTH);
         panel = new JPanel();
         panel.setLayout(new GridLayout(N, N));

         for (int i = 0; i <= N - 1; i++) {
             for (int j = 0; j <= N - 1; j++) {
                 bs[i][j] = new JButton();
                 bs[i][j].setBackground(Color.GRAY);
                 panel.add(bs[i][j]);
             }
         }

         container.add(panel, BorderLayout.CENTER);
         list = new LinkedList<Point>();

         list.add(new Point(15, 15));
         list.add(new Point(15, 14));
         list.add(new Point(15, 13));
         list.add(new Point(15, 12));
         list.add(new Point(15, 11));
         for (int i = 0; i <= list.size() - 1; i++) {
             bs[list.get(i).x][list.get(i).y].setBackground(Color.LIGHT_GRAY);
         }
         /*for (int i = 0; i <= list.size() - 1; i++) {
             System.out.print("(" + list.get(i).x + "," + list.get(i).y + ")  ");

         }*/
         /*System.out.println();*/

         this.addKeyListener(new KeyAdapter() {
             public void keyPressed(KeyEvent e) {
                 int c = e.getKeyCode();
                 //System.out.print(c);
                 int dir1 = dir;
                 switch (c) {
                     case KeyEvent.VK_LEFT :
                         dir1 = 2;
                         break;
                     case KeyEvent.VK_RIGHT :
                         dir1 = 0;
                         break;
                     case KeyEvent.VK_UP :
                         dir1 = 3;
                         break;
                     case KeyEvent.VK_DOWN :
                         dir1 = 1;
                         break;
                     default :
                         System.out.print("hey");
                         break;
                 }
                 if (!(dir1 - dir == -2 | dir1 - dir == 2))
                     dir = dir1;
             }
         });
         this.setFocusable(true);
         setLocation(200, 10);
         setSize(800, 700);
         setVisible(true);
     }
     String getBestScores() {

         BufferedReader reader=null;
         try {
             reader=new BufferedReader(new FileReader("score.txt"));
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         }

         try {
         a=Integer.parseInt(reader.readLine());
         b=Integer.parseInt(reader.readLine());
         c=Integer.parseInt(reader.readLine());
         } catch (NumberFormatException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
         String bestS=new String("Best Score: "+new Integer(a).toString()+"   "+new Integer(b).toString()+"   "+new Integer(c).toString());
         return bestS;
     }
 int gameOver(){
     isDead = true;
     JOptionPane.showMessageDialog(null, "你死了~~~.", "GAME OVER",
             JOptionPane.PLAIN_MESSAGE);
     if(SCORE>a){c=b;b=a;a=SCORE;save();System.exit(0);}
     if(SCORE>b){c=b;b=SCORE;save();System.exit(0);}
     if(SCORE>c){c=SCORE;save();System.exit(0);}
     System.exit(0);
     return 0;
 }
 int save(){

     BufferedWriter writer=null;
         try {
             writer=new BufferedWriter(new FileWriter("score.txt"));
         } catch (IOException e) {
             e.printStackTrace();
         }
     String d=new Integer(a).toString(),e=new Integer(b).toString(),f=new Integer(c).toString();
     try {
         writer.write(d);
         writer.newLine();
         writer.write(e);
         writer.newLine();
         writer.write(f);
         writer.flush();
         writer.close();
         } catch (NumberFormatException ev) {
         ev.printStackTrace();
     } catch (IOException ev) {
         ev.printStackTrace();
     }
     return 0;
 }
     public static void main(String[] args) {
         Snake snake = new Snake();
         snake.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Thread thread = new Thread(new go(snake));
         thread.start();
     }

 }

程序写于大三上学期。

2016.4.12更新博客。

END

贪吃蛇(Java实现)的更多相关文章

  1. 贪吃蛇 Java实现(一)

    贪吃蛇  Java实现 1.面向对象思想 1.创建antition包它是包含sanke  Ground Food类 2.创建Controller包controller类 3.创建Game包有game类 ...

  2. 贪吃蛇java版

    主要的蛇的类 import java.awt.Color; import java.awt.Graphics; import java.awt.HeadlessException; import ja ...

  3. 贪吃蛇的java代码分析(一)

    自我审视 最近自己学习java已经有了一个多月的时间,从一开始对变量常量的概念一无所知,到现在能勉强写几个小程序玩玩,已经有了长足的进步.今天没有去学习,学校里要进行毕业答辩和拍毕业照了,于是请了几天 ...

  4. 贪吃蛇的java代码分析(二)

    代码剖析 贪吃蛇是一款十分经典的小游戏,对初入coding的朋友来说,拿贪吃蛇这样一个案例来练手十分合适,并不高的难度和成功后的成就感都是学习所必须的.下面我将依照我当时的思路,来逐步分析实现的整个过 ...

  5. 贪吃蛇的java代码分析(三)

    代码剖析 在上一篇文章中,我们完成了贪吃蛇部分代码的构造.回头审视我们写的代码与思路,会发现我们遗漏了一个重要的地方,那就是:贪吃蛇的自身移动.想必大家都知道,贪吃蛇自身是会自己移动的,并且会跟随你的 ...

  6. 以小时候玩的贪吃蛇为例,对于Java图像界面的学习感悟

    简介 正文 01.JFrame是啥? 02.JPanel 03. KeyListener 04.Runnable 05.游戏Running 06.游戏初始类编写 07.main 简介: 一直以来用代码 ...

  7. java贪吃蛇

    这个贪吃蛇有很多功能没有实现,比如说穿墙(本来可以实现,但是穿墙后,就会出现坐标混乱,吃不到食物了),还有碰到自己的身体死亡的情况也没有实现,现在我知道如何判断是否碰到身体,但是,我不知道,如何处理碰 ...

  8. Java小游戏贪吃蛇

    package snake; import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java ...

  9. 贪吃蛇C#和JAVA实现

    using System; using System.Windows.Forms; using System.Drawing; class Window : Form { Point[] a = ]; ...

  10. java实现贪吃蛇游戏

    最简单的4个java类就可以实现贪吃蛇: main函数: package tcs; public class GreedSnake { public static void main(String[] ...

随机推荐

  1. HTML5翻页电子书

    体验效果:http://hovertree.com/texiao/jquery/60/ 图片请用正方形的 参考:http://hovertree.com/h/bjaf/d339euw9.htmhttp ...

  2. MSSQL数据库的一些基础知识

    转几个关于MSSQL数据库基础的文章: sql server系统表详细说明 SQL Server中系统数据库介绍 SQL Server中的角色(服务器级别和数据库级别角色)

  3. 增加线程异步发送消息的方法二(Runnable)

    //获取当前时间:毫秒 long a = System.currentTimeMillis(); System.out.println("a :" + a); try { //更改 ...

  4. Hadoop单机伪分布式

    环境配置:Ubuntu11.10,Hadoop1.0.0 安装ssh 1 apt-get install ssh 安装rsy 1 apt-get install rsync 配置ssh免密码登录 1 ...

  5. javascript封装与多态的体现

    封装是实现面向对象程序设计的第一步,封装就是将数据与函数等集合在一个个的单元中(我们称之为类).被封装的对象通常被称为抽象数据类型. 在传统的面向对象语言中有访问修饰符,如Private:只有类本身能 ...

  6. 实用CSS3的transform实现多种动画效果

    查看效果:http://keleyi.com/a/bjad/b6x9q8gs.htm 以下是代码: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. ...

  7. DYN-B201 Dynamics CRM 云生产力解决方案与功能简介

    DYN-B201 Dynamics CRM 云生产力解决方案与功能简介 讲师:王健.林松涛Dynamics CRM 云产品正式落地中国,CRM 与 Azure.O365 深度整合无缝集成,带来无与伦比 ...

  8. EA(企业架构)落地之道

    随着业务和IT的不断融合,企业业务.信息系统和技术结合日益紧密,企业对信息系统及技术的敏捷性要求越来越高.如何在多变的环境下快速创新产品或服务并推向市场是企业面临的日益紧迫的压力.企业架构作为连接和匹 ...

  9. 深入理解JavaScript的闭包特性如何给循环中的对象添加事件

    初学者经常碰到的,即获取HTML元素集合,循环给元素添加事件.在事件响应函数中(event handler)获取对应的索引.但每次获取的都是最后一次循环的索引.原因是初学者并未理解JavaScript ...

  10. IOS开发基础知识--碎片1

    一:NSString与NSInteger的互换 NSInteger转化NSString类型:[NSString stringWithFormat: @"%d", NSInteger ...