java 贪吃蛇

贪吃蛇

在这里插入图片描述

启动类

package com.snake;

import javax.swing.*;

public class GameStart {
    public static void main(String[] args) {
        JFrame gameFrame = new JFrame("snake");

        GamePanel gamePanel = new GamePanel();

        gameFrame.add(gamePanel);


        gameFrame.setBounds(500,100,900,720);
        gameFrame.setVisible(true);
        gameFrame.setResizable(false);
        gameFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

*面板类 (主要功能)

package com.snake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

/**
 * 基本步骤
 * 1.定义数据
 * 2.将数据画上去
 * 3.监听事件
 *    键盘
 *    游戏事件
 */

public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的数据
    int length;
    int[] snakeX = new int[800];
    int[] snakeY = new int[800];

    //定义food的数据
    int foodX;
    int foodY;
    public void foodInit(){
        foodX = 25+25*random.nextInt(34);
        foodY = 75+25*random.nextInt(24);
    }
    Random random = new Random();//随机数
    Timer time = new Timer(120,this);//定时器 监听this 100毫秒执行一次
    String direct;//定义方向
    int score;
    boolean isFail = false;//游戏是否失败
    boolean isStart = false;//游戏是否开始

    public GamePanel(){
        init();
        //获得键盘焦点事件
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        time.start();//游戏一开始 定时器就启动
    }

    //初始化方法
    public void init(){
        length = 3;
        snakeX[0] = 100;snakeY[0] = 100;//头坐标
        snakeX[1] = 75;snakeY[1] = 100;//第一节坐标
        snakeX[2] = 50;snakeY[2] = 100;//第二节坐标
        direct = "R";
        //初始化food
        foodInit();
        score = 0;
    }

    //绘制画笔 游戏所有界面都由这画笔画
    @Override
    protected void paintComponent(Graphics g) {
        //清屏 闪烁
        super.paintComponent(g);

        this.setBackground(Color.BLACK);
        //先绘制静态图像
        //Date.head.paintIcon(this,g,25,11);

        g.fillRect(25,75,850,600);
        g.setColor(new Color(0x242467));
        g.fillRect(25,11,850,50);

        //画出food
        Date.food.paintIcon(this,g,foodX,foodY);

        //把蛇画上来
        //画出头
        if (direct.equals("R")){
            Date.right.paintIcon(this,g,snakeX[0],snakeY[0]);//头初始化向右
        }else if (direct.equals("L")){
            Date.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (direct.equals("U")){
            Date.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (direct.equals("D")){
            Date.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //画出身体
        for (int i = 1; i < length; i++) {
            Date.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

        //画出分数
        g.setColor(new Color(0x4DD29B));
        g.setFont(new Font("宋体",Font.BOLD,45));
        g.drawString("分数:"+score,150,50);

        //画出长度
        g.setColor(new Color(0x4DD29B));
        g.setFont(new Font("宋体",Font.BOLD,45));
        g.drawString("长度:"+length,550,50);

        //画出失败提示
        if (isFail == true){
            g.setColor(Color.red);
            g.setFont(new Font("宋体",Font.BOLD,30));//设置字体 Font.BOLD加粗
            g.drawString("失败!按下空格重新开始游戏",250,350);

        }

        //画出启停提示
         if (isStart == false){
             g.setColor(Color.ORANGE);
             g.setFont(new Font("宋体",Font.BOLD,20));//设置字体 Font.BOLD加粗
             g.drawString("按下空格",405,330);
             g.setFont(new Font("宋体",Font.BOLD,30));//设置字体 Font.BOLD加粗
             g.drawString("开始|继续",370,370);
         }
    }


    //键盘监听
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获取按压的是哪个键
        if(keyCode == KeyEvent.VK_SPACE){//按压空格
            if (isFail){
                //重新开始
                isFail = false;
                init();
            }else {
                isStart = !isStart;
            }
            repaint();
        }
        if(keyCode == KeyEvent.VK_UP){
            if (direct != "D"){ //防止回头
                direct = "U";
            }
        } else if (keyCode == KeyEvent.VK_DOWN) {
            if (direct != "U"){
                direct = "D";
            }
        }else if (keyCode == KeyEvent.VK_LEFT) {
            if (direct != "R"){
                direct = "L";
            }
        }else if (keyCode == KeyEvent.VK_RIGHT) {
            if (direct != "L"){
                direct = "R";
            }
        }
    }

    //事件监听
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart == true && isFail == false){
            //吃食物
            if (snakeX[0] == foodX && snakeY[0] == foodY){
                length++;
                foodInit();//food刷新
                score += 10;
            }
            //移动
            for (int i = length-1 ; i > 0; i--) { //后面一节往前移一节
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }
            if (direct.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if (snakeX[0] > 850){
                    snakeX[0] = 25;
                }//边界判断
            } else if (direct.equals("L")) {
                snakeX[0] -= 25;
                if (snakeX[0] < 25){
                    snakeX[0] = 850;
                }//边界判断
            } else if (direct.equals("U")) {
                snakeY[0] -= 25;
                if (snakeY[0] < 75){
                    snakeY[0] = 650;
                }//边界判断
            } else if (direct.equals("D")) {
                snakeY[0] += 25;
                if (snakeY[0] > 650){
                    snakeY[0] = 75;
                }//边界判断
            }

            //速度设置
            if (length >= 15){
                time.setDelay(140);
            } else if (length > 15 && length <= 20) {
                time.setDelay(170);
            } else if (length > 20 && length <= 25) {
                time.setDelay(215);
            } else if (length > 25 && length <= 30) {
                time.setDelay(250);
            } else if (length > 30 && length <= 35) {
                time.setDelay(300);
            } else if (length > 35 && length <= 40) {
                time.setDelay(330);
            } else if (length > 40 && length <= 45) {
                time.setDelay(360);
            } else if (length > 45 && length <= 50) {
                time.setDelay(380);
            } else if (length > 50 && length <= 55) {
                time.setDelay(400);
            } else if (length > 55 && length <= 60) {
                time.setDelay(420);
            }

            //失败判断 撞到自己就结束
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                    isFail = true;
                }
            }
            repaint();//重画
        }
        time.start();//定时器开始
    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
    @Override
    public void keyTyped(KeyEvent e) {

    }
}

素材类

package com.snake;

import javax.swing.*;
import java.net.URL;

public class Date {
    //添加界面及身体元素 图标
    public static URL headURL = Date.class.getResource("picture/head.png");
    public static ImageIcon head =  new ImageIcon(headURL);
    public static URL foodURL = Date.class.getResource("picture/food.png");
    public static ImageIcon food =  new ImageIcon(foodURL);
    public static URL bodyURL = Date.class.getResource("picture/body.png");
    public static ImageIcon body =  new ImageIcon(bodyURL);
    public static URL upURL = Date.class.getResource("picture/up.png");
    public static ImageIcon up =  new ImageIcon(upURL);
    public static URL downURL = Date.class.getResource("picture/down.png");
    public static ImageIcon down =  new ImageIcon(downURL);
    public static URL leftURL = Date.class.getResource("picture/left.png");
    public static ImageIcon left =  new ImageIcon(leftURL);
    public static URL rightURL = Date.class.getResource("picture/right.png");
    public static ImageIcon right =  new ImageIcon(rightURL);

}

@kuangstudy

可以运行! (以下代码只是其中的一个类) package chy.snake.entities; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import chy.snake.listener.SnakeListener; import chy.snake.util.Global; public class Snake { public static final int up = 1; public static final int down = -1; public static final int left = -2; public static final int right = 2; private int oldDirection,newDirection; //newDirection:一次时间 间隔内输入的最后方向 private Point oldTail; private boolean life; //life 为 true或者false,初始为true, 用于118行 private LinkedList<Point> body = new LinkedList<Point> (); //需要经常访问蛇的第一个和最后一个节点,使用链表LinkedList存放蛇的身体节点,因为它有getFirst(),getLast(),removeLast(),方法 private Set<SnakeListener> listeners = new HashSet<SnakeListener>(); public Snake(){ init(); } public void init(){ //初始化 int x = Global.WIDTH/2; int y = Global.HEIGHT/2; for(int i=0;i<3;i++){ //初始长度3 body.addLast(new Point(x-i,y)); //是addLast } oldDirection = newDirection = right; //初始方向 右 life = true; } public void die(){ life = false; } public void move(){ System.out.println("Snake's move"); if (!(oldDirection + newDirection == 0)){ oldDirection = newDirection; } //1.去尾 oldTail = body.removeLast(); int x = body.getFirst().x; int y = body.getFirst().y; //蛇头的x,y坐标 switch(oldDirection){ case up: y--; break; case down: y++; break; case left: x--; break; case right: x++; break; } Point newHead = new Point(x,y); //2.加头 body.addFirst(newHead); } public void changeDirection(int direction){ /*无效方向:在蛇的这一次移动之后和下一次移动之前的 这个时间间隔内输入了多个方向,只有最后一个方向 是 有效方向,其余的都为无效方向*/ System.out.println("Snake's changeDirection"); newDirection = direction; //将一个时间间隔内按得最后方向,赋给 newDirection } public void eatFood(){ System.out.println("Snake's eatFood"); body.addLast(oldTail); //后面的节点不去掉 } public boolean isEatFood(){ System.out.println("Snake's isEatFood"); return false; } public boolean isEatBody(Snake snake){ //比较蛇是否吃到身体 System.out.println("snake's isEatBody"); for(int i= 1;i<body.size();i++){ //i 从蛇头结点的下一个节点开始,排除蛇头结点 if(body.get(i).equals(this.getHead())){ //如果i 的节点 和 头结点 相同 return true; } } return false; } public void drawMe(Graphics g){ System.out.println("Snake's drawMe"); g.setColor(Color.GREEN); //设置蛇的颜色 for(Point p : body){ g.fill3DRect(p.x * Global.CELL_SIZE, p.y * Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true); } } public Point getHead(){ //得到蛇头节点,判断吃食物 return body.getFirst(); } private class SnakeDriver implements Runnable{ //线程,不停的调用move方法 @Override public void run() { // TODO 自动生成的方法存根 while(life){ // 42和46行,life为true 或者false move(); for(SnakeListener l : listeners){ l.snakeMoved(Snake.this); //循环,依次调用SnakeMoved方法 } try { Thread.sleep(300); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } } public void start(){ new Thread(new SnakeDriver()).start(); //启动线程的方法 } public void addSnakeListener(SnakeListener l){ if(l != null){ this.listeners.add(l); } } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值