国庆在家用JAVA写了个贪吃蛇

        这两天国庆放假实在无聊,开始几天天天躺床上刷抖音,结果回来的小侄子天天来找我完,(不是来找我玩,是来找我手机玩),想着能不能自己写一个小游戏给他玩,思来想去,想我这种菜鸡也只能写一个最简单的贪吃蛇。

游戏说明

1、上下左右四个方向键控制移动(没了,多了咱写不出)。

2、长按加速移动(假的,如上面1所说)。

游戏效果展示

        做这个游戏找素材真的太难了,找了半天没找到,(是我不知道上哪里去找),最后只好自己找了一堆卡通图片慢慢抠图,才有了上面的那些食物,结果在游戏里面发现展示出来好小,蛇身我是真没找到满意的,最后只有用纯色小方块代替了。右边四个功能显示区也懒得继续写了,以后有时间再来写吧,(因为现在代码真的是屎山)。

        至于我为什么不想写下去了,前面说了,这个游戏本来写个小侄子玩的,连夜写的,第二天让他来玩,结果只玩了几分钟,他就不想玩了。跑去玩微信小程序里面的游戏了,后来准备写的双人模式也放弃了。

        代码是看了黑马的视频后写的,所以思路几乎差不多,只是做了一些美化。

游戏代码详解(bushi)

1、Class Node

定义每一个节点的坐标 x,y ,  color用来判断食物的不同类别了,最开始是有其他用途,后面也懒得改了。

package game;

import java.util.Comparator;
import java.util.Random;

public class Node implements Comparator<Node> {
    private int x;
    private int y;
    private int color;

    Node(){

    }

    Node(int x,int y){
        this.x = x;
        this.y = y;
    }

    Node(int x,int y,int color){
        this.x = x;
        this.y = y;
        this.color = color;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    @Override
    public int compare(Node o1, Node o2) {
        return o1.x - o2.x;
    }
}

2、Class Snake

//设置蛇身
private LinkedList<Node> body;
private HashSet<Node> hashBody;
//当前分数
private double score = 15;
//分数池
private double[] scoreArray = {3,2,2,1,1,1};
//设置默认方向为 向右
private Direction direction = Direction.RIGHT;
private boolean isLiving = true;

        主要就是蛇身,最开始用了个LinkedList想着蛇移动时就是在沿着蛇移动的方向添加一个节点,然后把最后一个节点删除,用LinedList底层链表实现的比较方便,不用大规模对数据进行移动

        Sanke有两个主要方法,move 和 eat

        move里面最开始判断是否撞墙,撞墙了就游戏结束,没有就继续判断是否吃到自己身体,吃到了就把后面的部分删除,蛇身就会变短

        eat方法是吃到食物后对score对应的分数池的分数进行加分,当距离上一次蛇身+1后累加的分数>=3时,在蛇尾部添加一个节点,这里不能添加到头部,我看黑马视频里面直接添加在头部,这样当食物出显在墙边时,对着墙过去吃食物就会直接撞墙,然后就GAMEOVER了

package game;

import java.util.HashSet;
import java.util.LinkedList;

public class Snake {
    //设置蛇身
    private LinkedList<Node> body;
    private HashSet<Node> hashBody;
    //当前分数
    private double score = 15;
    private double[] scoreArray = {3,2,2,1,1,1};
    //设置默认方向为 向右
    private Direction direction = Direction.RIGHT;
    private boolean isLiving = true;

    Snake(){
        initSnake();
    }

    private void initSnake(){
        body = new LinkedList<>();
        body.addLast(new Node(20,13));
        body.addLast(new Node(19,13));
        body.addLast(new Node(18,13));
        body.addLast(new Node(17,13));
        body.addLast(new Node(16,13));
        hashBody = new HashSet<>();
        hashBody.add(new Node(20,13));
        hashBody.add(new Node(19,13));
        hashBody.add(new Node(18,13));
        hashBody.add(new Node(17,13));
        hashBody.add(new Node(16,13));

    }

    public double f(){
        return 0.15*score + 10;
    }

    public void move(){
        if(isLiving){
            Node head = body.getFirst();
            switch (direction){
                case UP:
                    body.addFirst(new Node(head.getX(),head.getY()-1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(),head.getY()+1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX()-1,head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX()+1,head.getY()));
                    break;
            }
            body.removeLast();
            //判断是否到达边界
            head = body.getFirst();
            if(head.getX()<=0 || head.getY()<=0 || head.getX()>=59
                    || head.getY()>=39) {
                isLiving = false;
            }
            for(Node node : Data.wall){
                if(node.getY() == head.getY() && node.getX() == head.getX()){
                    isLiving = false;
                    break;
                }
            }

            //判断是否吃到自己身体
            for(int i=1;i<body.size();i++){
                Node node = body.get(i);
                if(head.getX() == node.getX() && head.getY() == node.getY()){
                    score = Math.max(0,score - (body.size()-i) );
                    int len = body.size() - i+1;
                    while(len != 0){
                        len --;
                        body.removeLast();
                    }
                }
            }
        }
    }

    public void eat(Node food){
        score += scoreArray[food.getColor()];
        Node head = body.getFirst();
        Node tail = body.getLast();
        if(head.getX() <= food.getX() && head.getX()+15 >= food.getX()
                && head.getY() <= food.getY() && head.getY()+15 >= food.getY() && score/3 > body.size()){
            Node tail1 = new Node(tail.getX()-1,tail.getY() );
            Node tail2 = new Node(tail.getX()+1,tail.getY() );
            Node tail3 = new Node(tail.getX(),tail.getY()-1 );
            Node tail4 = new Node(tail.getX(),tail.getY()+1 );

            if(!hashBody.contains(tail1) ){
                body.addLast(tail1);
                hashBody.add(tail1);
                return;
            }else if(!hashBody.contains(tail2)){
                body.addLast(tail2);
                hashBody.add(tail2);
                return;
            }else if(!hashBody.contains(tail3)){
                body.addLast(tail3);
                hashBody.add(tail3);
                return;
            }else if(!hashBody.contains(tail4)){
                body.addLast(tail4);
                hashBody.add(tail4);
                return;
            }
        }
    }

    public HashSet<Node> getHashBody() {
        return hashBody;
    }

    public void setHashBody(HashSet<Node> hashBody) {
        this.hashBody = hashBody;
    }

    public boolean isLiving() {
        return isLiving;
    }

    public void setLiving(boolean living) {
        isLiving = living;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

3、Class Food

        food类,用的hashset存食物的坐标,想着在判断食物被吃的时候不用遍历直接用contain方法,后面发现不行,也没有去看contain方法源码了,(屎山就让他继续屎下去吧),有一个random方法,随机位置生成食物。

package game;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

public class Food extends Node{
    Random r = new Random();
//    ArrayList<Node> food = new ArrayList<>();
    HashSet<Node> food = new HashSet<>();

    Food(){
        initFood1();
    }

    private void initFood1(){
        int cnt=0;
        while(true){
            int x = r.nextInt(58) + 1;
            int y = r.nextInt(38) + 1;
            if(!Data.wall.contains(new Node(x,y)) && !Data.wall.contains(new Node(x,y))){
                cnt++;
                food.add(new Node(x,y,r.nextInt(6)));
            }
            if(cnt >= 25){
                break;
            }
        }
    }


    public void random(){
        Node node = new Node();
        Snake snake = new Snake();
        HashSet<Node> hBody = snake.getHashBody();
        boolean flag = true;
        do {
            node.setX(r.nextInt(58) + 1);
            node.setY(r.nextInt(38) + 1);
            node.setColor(r.nextInt(6));

            for(Node node1 : Data.wall){
                if(node1.getX() == node.getX() && node1.getY() == node.getY()){
                    continue;
                }
            }

            food.add(node);
            flag = false;
        }while(flag);
//        System.out.printf("新生成食物坐标:%d %d",x,y,color);
    }
}

        

4、Class Direction

        枚举类,四个方向

package game;

public enum Direction {
    UP,DOWN,LEFT,RIGHT
}

5、Class MianFrame

        MainFrame继承了JFrame 类

        常量部分

    public static final int WIN_WIDTH = 1092;
    public static final int WIN_HEIGHT = 635;
    public static final int CELL_LENGTH = 15;
    public static final int MAP_HEIGHT = 600;
    public static final int MAP_WIDTH = 900;

        定义了几个变量

                

    private Direction direction = Direction.RIGHT;
    private JPanel jpanel;
    private Snake snake;
    private Food snakeFood;
    private Timer timer;
    private Data data;

         构造方法

  MainFrame() {
        //初始化窗体
        initJfame();
        //初始化蛇身
        initSnake();
        //初始化食物
        initFood();
        //初始化数据
        initData();
        //初始化棋盘
        initGamePanel();
        //初始化计时器
        initTimer();
        //键盘监听
        setKeyListener();
    }

       构造方法里面的函数实现

         initJframe函数
 private void initJfame() {
        setSize(WIN_WIDTH, WIN_HEIGHT);
        setLocation(80, 80);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
    }

        1、设置窗体长、宽

        2、设置起始位置

        3、窗体关闭时程序运行也结束

        4、设置窗体大小不可变

         initSnake/initData/initFood

         这里就是把对象new出来(为什么要在写一个函数呢,这样看起来有逼格一点)

 private void initSnake() {
        snake = new Snake();
    }

    private void initFood() {
        snakeFood = new Food();
    }

    private void initData() {
        data = new Data();
    }

      initGamePanel

        1、绘制背景

        2、绘制地图,地图放在Data类里面的map中(上面讲到过)

        3、绘制蛇身,蛇头和蛇身颜色做了一下区分

        4、绘制分数

        5、绘制食物

        最后调用 add 方法添加到窗体里面

private void initGamePanel() {
        jpanel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                g.clearRect(0, 0, WIN_WIDTH, WIN_HEIGHT);

                g.drawImage(Data.bgImg, 0, 0, this);

                //绘制地图
                for (Node node : Data.wall) {
                    g.drawImage(Data.brick, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH,
                            CELL_LENGTH, CELL_LENGTH, this);
                }

                //绘制蛇身
                LinkedList<Node> body = snake.getBody();
                boolean flag = true;
                for (Node node : body) {
                    if (flag) {
                        g.setColor(Data.snakeHeadColor);
                        g.fillRect(node.getX() * 15, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH);
                        g.setColor(Data.snakeBodyColor);
                        flag = false;
                        continue;
                    }
                    g.fillRect(node.getX() * 15, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH);

                }


                String str1 = String.valueOf(snake.getScore() - 15);
                String str2 = String.valueOf(snake.getBody().size());

                g.setColor(Data.fontColor);
                g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 22));
                g.drawString("SCORES:" , 920, 42);

                g.drawString(str1, 930, 66);

                g.drawString("LENGTH:",920, 100);
                g.drawString(str2 ,930, 124);


                //绘制食物
                g.setColor(Color.PINK);
                for (Node node : snakeFood.food) {
                    switch (node.getColor()) {
                        case 0:
                            g.drawImage(Data.food1, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 1:
                            g.drawImage(Data.food2, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 2:
                            g.drawImage(Data.food3, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 3:
                            g.drawImage(Data.food4, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 4:
                            g.drawImage(Data.food5, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 5:
                            g.drawImage(Data.food6, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                    }
                }
            }

        };
        add(jpanel);
//        jpanel.setBackground(Color.BLUE);

    }

        initTimer

               new 一个对象,然后重写run方法,run方法里面主要是调用蛇的移动方法,和判断蛇是否吃到食物,最后调用repaint进行重新绘制,最后对蛇的当前状态判断一下,isliving为true的话每隔0.1s调用一下timetask 让run 方法 run 起来

private void initTimer() {
        timer = new Timer();
        TimerTask timertask = new TimerTask() {
            @Override
            public void run() {
                snake.move();

                Node head = snake.getBody().getFirst();

                for (Node node : snakeFood.food) {
                    if (head.getX() == node.getX() && head.getY() == node.getY()) {
                        snake.eat(node);
                        snakeFood.food.remove(node);
                        snakeFood.random();
                        break;
                    }
                }

                jpanel.repaint();
            }
        };
        if (snake.isLiving())
            timer.scheduleAtFixedRate(timertask, 0, 100);
        else {
            System.out.println("撞墙了,GameOver!");
            return;
        }
    }

        setKeyListener 设置键盘监听

        监听上下左右四个方向键

private void setKeyListener() {
        addKeyListener(new KeyAdapter() {
            //            当键盘按下时会自动掉用此方法
            @Override
            public void keyPressed(KeyEvent e) {
//                键盘中每个键都有编号
                switch (e.getKeyCode()) {
                    case KeyEvent.VK_UP://上键
                        if (snake.getDirection() != Direction.DOWN)
                            snake.setDirection(Direction.UP);
                        break;
                    case KeyEvent.VK_DOWN://下键
                        if (snake.getDirection() != Direction.UP)
                            snake.setDirection(Direction.DOWN);
                        break;
                    case KeyEvent.VK_LEFT://左键
                        if (snake.getDirection() != Direction.RIGHT)
                            snake.setDirection(Direction.LEFT);
                        break;
                    case KeyEvent.VK_RIGHT://右键
                        if (snake.getDirection() != Direction.LEFT)
                            snake.setDirection(Direction.RIGHT);
                        break;
                }
            }
        });
    }

完整源码

MainFrame

package game;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;


public class MainFrame extends JFrame {
    public static final int WIN_WIDTH = 1092;
    public static final int WIN_HEIGHT = 635;
    public static final int CELL_LENGTH = 15;
    public static final int MAP_HEIGHT = 600;
    public static final int MAP_WIDTH = 900;

    private Direction direction = Direction.RIGHT;
    private JPanel jpanel;
    private Snake snake;
    private Food snakeFood;
    private Timer timer;
    private Data data;

    MainFrame() {
        //初始化窗体
        initJfame();
        //初始化蛇身
        initSnake();
        //初始化食物
        initFood();
        //初始化数据
        initData();
        //初始化棋盘
        initGamePanel();
        //初始化计时器
        initTimer();
        //键盘监听
        setKeyListener();
    }


    //        设置键盘监听
    private void setKeyListener() {
        addKeyListener(new KeyAdapter() {
            //            当键盘按下时会自动掉用此方法
            @Override
            public void keyPressed(KeyEvent e) {
//                键盘中每个键都有编号
                switch (e.getKeyCode()) {
                    case KeyEvent.VK_UP://上键
                        if (snake.getDirection() != Direction.DOWN)
                            snake.setDirection(Direction.UP);
                        break;
                    case KeyEvent.VK_DOWN://下键
                        if (snake.getDirection() != Direction.UP)
                            snake.setDirection(Direction.DOWN);
                        break;
                    case KeyEvent.VK_LEFT://左键
                        if (snake.getDirection() != Direction.RIGHT)
                            snake.setDirection(Direction.LEFT);
                        break;
                    case KeyEvent.VK_RIGHT://右键
                        if (snake.getDirection() != Direction.LEFT)
                            snake.setDirection(Direction.RIGHT);
                        break;
                }
            }
        });
    }


    private void initTimer() {
        timer = new Timer();
        TimerTask timertask = new TimerTask() {
            @Override
            public void run() {
                snake.move();

                Node head = snake.getBody().getFirst();

                for (Node node : snakeFood.food) {
                    if (head.getX() == node.getX() && head.getY() == node.getY()) {
                        snake.eat(node);
                        snakeFood.food.remove(node);
                        snakeFood.random();
                        break;
                    }
                }

                jpanel.repaint();
            }
        };
        if (snake.isLiving())
            timer.scheduleAtFixedRate(timertask, 0, 100);
        else {
            System.out.println("撞墙了,GameOver!");
            return;
        }
    }

    private void initSnake() {
        snake = new Snake();
    }

    private void initFood() {
        snakeFood = new Food();
    }

    private void initData() {
        data = new Data();
    }

    private void initGamePanel() {
        jpanel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                g.clearRect(0, 0, WIN_WIDTH, WIN_HEIGHT);

                g.drawImage(Data.bgImg, 0, 0, this);

                //绘制地图
                for (Node node : Data.wall) {
                    g.drawImage(Data.brick, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH,
                            CELL_LENGTH, CELL_LENGTH, this);
                }

                //绘制蛇身
                LinkedList<Node> body = snake.getBody();
                boolean flag = true;
                for (Node node : body) {
                    if (flag) {
                        g.setColor(Data.snakeHeadColor);
                        g.fillRect(node.getX() * 15, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH);
                        g.setColor(Data.snakeBodyColor);
                        flag = false;
                        continue;
                    }
                    g.fillRect(node.getX() * 15, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH);

                }


                String str1 = String.valueOf(snake.getScore() - 15);
                String str2 = String.valueOf(snake.getBody().size());

                g.setColor(Data.fontColor);
                g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 22));
                g.drawString("SCORES:" , 920, 42);

                g.drawString(str1, 930, 66);

                g.drawString("LENGTH:",920, 100);
                g.drawString(str2 ,930, 124);


                //绘制食物
                g.setColor(Color.PINK);
                for (Node node : snakeFood.food) {
                    switch (node.getColor()) {
                        case 0:
                            g.drawImage(Data.food1, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 1:
                            g.drawImage(Data.food2, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 2:
                            g.drawImage(Data.food3, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 3:
                            g.drawImage(Data.food4, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 4:
                            g.drawImage(Data.food5, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                        case 5:
                            g.drawImage(Data.food6, node.getX() * CELL_LENGTH, node.getY() * CELL_LENGTH, CELL_LENGTH, CELL_LENGTH, this);
                            break;
                    }
                }
            }

        };
        add(jpanel);
//        jpanel.setBackground(Color.BLUE);

    }

    private void initJfame() {
        setSize(WIN_WIDTH, WIN_HEIGHT);
        setLocation(80, 80);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
    }

    public static void main(String[] args) {
        new MainFrame().setVisible(true);
    }
}

Node

package game;

import java.util.Comparator;
import java.util.Random;

public class Node implements Comparator<Node> {
    private int x;
    private int y;
    private int color;

    Node(){

    }

    Node(int x,int y){
        this.x = x;
        this.y = y;
    }

    Node(int x,int y,int color){
        this.x = x;
        this.y = y;
        this.color = color;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    @Override
    public int compare(Node o1, Node o2) {
        return o1.x - o2.x;
    }
}

food

package game;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

public class Food extends Node{
    Random r = new Random();
//    ArrayList<Node> food = new ArrayList<>();
    HashSet<Node> food = new HashSet<>();

    Food(){
        initFood1();
    }

    private void initFood1(){
        int cnt=0;
        while(true){
            int x = r.nextInt(58) + 1;
            int y = r.nextInt(38) + 1;
            if(!Data.wall.contains(new Node(x,y)) && !Data.wall.contains(new Node(x,y))){
                cnt++;
                food.add(new Node(x,y,r.nextInt(6)));
            }
            if(cnt >= 25){
                break;
            }
        }
    }


    public void random(){
        Node node = new Node();
        Snake snake = new Snake();
        HashSet<Node> hBody = snake.getHashBody();
        boolean flag = true;
        do {
            node.setX(r.nextInt(58) + 1);
            node.setY(r.nextInt(38) + 1);
            node.setColor(r.nextInt(6));

            for(Node node1 : Data.wall){
                if(node1.getX() == node.getX() && node1.getY() == node.getY()){
                    continue;
                }
            }

            food.add(node);
            flag = false;
        }while(flag);
//        System.out.printf("新生成食物坐标:%d %d",x,y,color);
    }
}

Snake

package game;

import java.util.HashSet;
import java.util.LinkedList;

public class Snake {
    //设置蛇身
    private LinkedList<Node> body;
    private HashSet<Node> hashBody;
    //当前分数
    private double score = 15;
    private double[] scoreArray = {3,2,2,1,1,1};
    //设置默认方向为 向右
    private Direction direction = Direction.RIGHT;
    private boolean isLiving = true;

    Snake(){
        initSnake();
    }

    private void initSnake(){
        body = new LinkedList<>();
        body.addLast(new Node(20,13));
        body.addLast(new Node(19,13));
        body.addLast(new Node(18,13));
        body.addLast(new Node(17,13));
        body.addLast(new Node(16,13));
        hashBody = new HashSet<>();
        hashBody.add(new Node(20,13));
        hashBody.add(new Node(19,13));
        hashBody.add(new Node(18,13));
        hashBody.add(new Node(17,13));
        hashBody.add(new Node(16,13));

    }

    public double f(){
        return 0.15*score + 10;
    }

    public void move(){
        if(isLiving){
            Node head = body.getFirst();
            switch (direction){
                case UP:
                    body.addFirst(new Node(head.getX(),head.getY()-1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(),head.getY()+1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX()-1,head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX()+1,head.getY()));
                    break;
            }
            body.removeLast();
            //判断是否到达边界
            head = body.getFirst();
            if(head.getX()<=0 || head.getY()<=0 || head.getX()>=59
                    || head.getY()>=39) {
                isLiving = false;
            }
            for(Node node : Data.wall){
                if(node.getY() == head.getY() && node.getX() == head.getX()){
                    isLiving = false;
                    break;
                }
            }




            //判断是否吃到自己身体
            for(int i=1;i<body.size();i++){
                Node node = body.get(i);
                if(head.getX() == node.getX() && head.getY() == node.getY()){
                    score = Math.max(0,score - (body.size()-i) );
                    int len = body.size() - i+1;
                    while(len != 0){
                        len --;
                        body.removeLast();
                    }
                }
            }
        }
    }

    public void eat(Node food){
        score += scoreArray[food.getColor()];
        Node head = body.getFirst();
        Node tail = body.getLast();
        if(head.getX() <= food.getX() && head.getX()+15 >= food.getX()
                && head.getY() <= food.getY() && head.getY()+15 >= food.getY() && score/3 > body.size()){
            Node tail1 = new Node(tail.getX()-1,tail.getY() );
            Node tail2 = new Node(tail.getX()+1,tail.getY() );
            Node tail3 = new Node(tail.getX(),tail.getY()-1 );
            Node tail4 = new Node(tail.getX(),tail.getY()+1 );

            if(!hashBody.contains(tail1) ){
                body.addLast(tail1);
                hashBody.add(tail1);
                return;
            }else if(!hashBody.contains(tail2)){
                body.addLast(tail2);
                hashBody.add(tail2);
                return;
            }else if(!hashBody.contains(tail3)){
                body.addLast(tail3);
                hashBody.add(tail3);
                return;
            }else if(!hashBody.contains(tail4)){
                body.addLast(tail4);
                hashBody.add(tail4);
                return;
            }
        }
    }

    public HashSet<Node> getHashBody() {
        return hashBody;
    }

    public void setHashBody(HashSet<Node> hashBody) {
        this.hashBody = hashBody;
    }

    public boolean isLiving() {
        return isLiving;
    }

    public void setLiving(boolean living) {
        isLiving = living;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

Direction

package game;

public enum Direction {
    UP,DOWN,LEFT,RIGHT
}

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值