java贪吃蛇小游戏

创建GameWin.java

package com.sxt;

import com.sxt.obj.BodyObj;
import com.sxt.obj.FoodObj;
import com.sxt.obj.HeadObj;
import com.sxt.utils.GameUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

public class GameWin extends JFrame {


    //游戏状态 0.未开始  1.游戏中  2.暂停  3.失败  4.通关 5.失败后重新开始 6.下一关
    public static int state = 0;
    //分数
    public int score = 0;
    //定义双缓存图片
    Image offScreenImage = null;
    //窗口宽高
    int winWidth = 800;
    int winHeight = 600;
    //蛇头对象
    public HeadObj headObj = new HeadObj(GameUtils.rightImg,60,570,this);

    //蛇的身体集合
    public List<BodyObj> bodyObjList = new ArrayList<>();

    //食物
    public FoodObj foodObj = new FoodObj().getFood();

    public void launch(){
        //设置窗口是否可见
        this.setVisible(true);
        //设置窗口的大小
        this.setSize(winWidth,winHeight);
        //设置窗口的位置在屏幕上居中
        this.setLocationRelativeTo(null);
        //设置窗口的标题
        this.setTitle("尚学堂贪吃蛇");

        //蛇身体的初始化
        bodyObjList.add(new BodyObj(GameUtils.bodyImg,30,570,this));
        bodyObjList.add(new BodyObj(GameUtils.bodyImg,0,570,this));

        //键盘事件
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SPACE){
                    switch (state){
                        case 0:
                            //未开始
                            state = 1;
                            break;
                        case 1:
                            //游戏中
                            state = 2;
                            repaint();
                            break;
                        case 2:
                            //游戏暂停
                            state = 1;
                            break;
                        case 3:
                            //失败后重新开始
                            state = 5;
                            break;
                        case 4:
                            //下一关
                            state = 6;
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        while (true){
            if (state == 1){
                //游戏中才调用
                repaint();
            }
            //失败重启
            if (state == 5){
                state = 0;
                resetGame();
            }
            //通关下一关
            if (state == 6 && GameUtils.level != 3){
                state = 1;
                GameUtils.level++;
                resetGame();
            }
            try {
                //1秒1000毫秒
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void paint(Graphics g) {
        //初始化双缓存图片
        if (offScreenImage == null){
            offScreenImage = this.createImage(winWidth,winHeight);
        }
        //获取图片对应的graphics对象
        Graphics gImage = offScreenImage.getGraphics();
        //灰色背景
        gImage.setColor(Color.gray);
        gImage.fillRect(0,0,winWidth,winHeight);
        //网格线
        gImage.setColor(Color.black);
        //横线
        for (int i = 0; i <= 20 ; i++) {
            //横线
            gImage.drawLine(0,i * 30,600,i * 30);
            //竖线
            gImage.drawLine(i * 30,0,i * 30,600);
        }
        //绘制蛇身体
        for (int i = bodyObjList.size() - 1; i >= 0; i--) {
            bodyObjList.get(i).paintSelf(gImage);
        }
        //绘制蛇头
        headObj.paintSelf(gImage);
        //食物绘制
        foodObj.paintSelf(gImage);
        //关卡
        GameUtils.drawWord(gImage,"第"+GameUtils.level+"关",Color.orange,40,650,260);
        //分数绘制
        GameUtils.drawWord(gImage,score + " 分",Color.BLUE,50,650,330);
        //绘制提示语
        gImage.setColor(Color.gray);
        prompt(gImage);
        //将双缓存图片绘制到窗口中
        g.drawImage(offScreenImage,0,0,null);
    }

    //绘制提示语
    void prompt(Graphics g){
        //未开始
        if (state == 0){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"按下空格键开始游戏",Color.yellow,35,150,290);
        }
        //暂停
        if (state == 2){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"按下空格键继续游戏",Color.yellow,35,150,290);
        }
        //失败
        if (state == 3){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"失败,按空格重新开始",Color.red,35,150,290);
        }
        //通关
        if (state == 4){
            g.fillRect(120,240,400,70);
            if (GameUtils.level == 3){
                GameUtils.drawWord(g,"达成条件,游戏通关",Color.green,35,150,290);
            } else {
                GameUtils.drawWord(g,"达成条件,空格下一关",Color.green,35,150,290);
            }

        }

    }


    //游戏重置
    void resetGame(){
        //关闭当前窗口
        this.dispose();
        //开启新窗口
        String[] args = {};
        main(args);
    }

    public static void main(String[] args) {
        GameWin gameWin = new GameWin();
        gameWin.launch();
    }
}

身体:BodyObj

package com.sxt.obj;

import com.sxt.GameWin;

import java.awt.*;

public class BodyObj extends GameObj {
    public BodyObj(Image img, int x, int y, GameWin frame) {
        super(img, x, y, frame);
    }

    @Override
    public void paintSelf(Graphics g) {
        super.paintSelf(g);
    }

    @Override
    public String toString() {
        return "BodyObj{" +
                "img=" + img +
                ", x=" + x +
                ", y=" + y +
                '}';
    }
}


食物:FoodObj

package com.sxt.obj;

import com.sxt.GameWin;
import com.sxt.utils.GameUtils;

import java.awt.*;
import java.util.Random;

public class FoodObj extends GameObj {

    //随机
    Random r = new Random();

    public FoodObj() {
        super();
    }

    public FoodObj(Image img, int x, int y, GameWin frame) {
        super(img, x, y, frame);
    }

    //获取食物
    public FoodObj getFood(){
        return new FoodObj(GameUtils.foodImg,r.nextInt(20) * 30,(r.nextInt(19) + 1) * 30,this.frame);
    }

    @Override
    public void paintSelf(Graphics g) {
        super.paintSelf(g);
    }
}


面板:GameObj

package com.sxt.obj;

import com.sxt.GameWin;

import java.awt.*;

public class GameObj {

    //图片
    Image img;
    //坐标
    int x;
    int y;
    //宽高
    int width = 30;
    int height = 30;
    //窗口类的引用
    GameWin frame;

    public Image getImg() {
        return img;
    }

    public void setImg(Image img) {
        this.img = img;
    }

    public int getX() {
        return x;
    }

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

    public int getY() {
        return y;
    }

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

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public GameWin getFrame() {
        return frame;
    }

    public void setFrame(GameWin frame) {
        this.frame = frame;
    }

    public GameObj() {
    }

    public GameObj(Image img, int x, int y, GameWin frame) {
        this.img = img;
        this.x = x;
        this.y = y;
        this.frame = frame;
    }

    public GameObj(Image img, int x, int y, int width, int height, GameWin frame) {
        this.img = img;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.frame = frame;
    }

    //绘制自身
    public void paintSelf(Graphics g){
        g.drawImage(img,x,y,null);
    }
}

头部:HeadObj

package com.sxt.obj;

import com.sxt.GameWin;
import com.sxt.utils.GameUtils;


import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class HeadObj extends GameObj {
    //方向 up down left right
    private String direction = "right";

    public String getDirection() {
        return direction;
    }

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

    public HeadObj(Image img, int x, int y, GameWin frame) {
        super(img, x, y, frame);
        //键盘监听事件
        this.frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                changeDirection(e);
            }
        });
    }

    //控制移动方向  w -up  a - left   d -right  s-down
    public void changeDirection(KeyEvent e){
        switch (e.getKeyCode()){
            case KeyEvent.VK_A:
                if (!"right".equals(direction)){
                    direction = "left";
                    img = GameUtils.leftImg;
                }
                break;
            case KeyEvent.VK_D:
                if (!"left".equals(direction)){
                    direction = "right";
                    img = GameUtils.rightImg;
                }
                break;
            case KeyEvent.VK_W:
                if (!"down".equals(direction)){
                    direction = "up";
                    img = GameUtils.upImg;
                }
                break;
            case KeyEvent.VK_S:
                if (!"up".equals(direction)){
                    direction = "down";
                    img = GameUtils.downImg;
                }
                break;
            default:
                break;
        }
    }

    //蛇的移动
    public void move(){
        //蛇身体的移动
        java.util.List<BodyObj> bodyObjList = this.frame.bodyObjList;
        for (int i = bodyObjList.size() - 1; i >= 1; i--) {
            bodyObjList.get(i).x = bodyObjList.get(i - 1).x;
            bodyObjList.get(i).y = bodyObjList.get(i - 1).y;
            //蛇头与身体的碰撞判断
            if (this.x == bodyObjList.get(i).x && this.y == bodyObjList.get(i).y){
                //失败
                GameWin.state = 3;
            }
        }
        bodyObjList.get(0).x = this.x;
        bodyObjList.get(0).y = this.y;
        //蛇头的移动
        switch (direction){
            case "up":
                y -= height;
                break;
            case "down":
                y += height;
                break;
            case "left":
                x -= width;
                break;
            case "right":
                x += width;
            default:
                break;
        }
    }

    @Override
    public void paintSelf(Graphics g) {
        super.paintSelf(g);
        //蛇吃食物
        FoodObj food = this.frame.foodObj;
        //身体最后一节的坐标
        Integer newX = null;
        Integer newY = null;
        if (this.x == food.x && this.y == food.y){
            this.frame.foodObj = food.getFood();
            //获取蛇身的最后一个元素
            BodyObj lastBody = this.frame.bodyObjList.get(this.frame.bodyObjList.size() - 1);
            newX = lastBody.x;
            newY = lastBody.y;
            //分数+1
            this.frame.score++;
        }
        //通关判断
        if (this.frame.score >= 10){
            //通关
            GameWin.state = 4;
        }
        move();
        //move结束后,新的bodyObj对象添加到bodyObjList
        if (newX != null && newY != null){
            this.frame.bodyObjList.add(new BodyObj(GameUtils.bodyImg,newX,newY,this.frame));
        }



        //越界处理
        if (x < 0){
            x = 570;
        } else if (x > 570){
            x = 0;
        } else if (y < 30){
            y = 570;
        }else if (y > 570){
            y = 30;
        }
    }

    @Override
    public String toString() {
        return "HeadObj{" +
                "img=" + img +
                ", x=" + x +
                ", y=" + y +
                '}';
    }
}

GameUtils

package com.sxt.utils;

import java.awt.*;

public class GameUtils {

    //蛇头
    public static Image upImg = Toolkit.getDefaultToolkit().getImage("img/up.png");
    public static Image downImg = Toolkit.getDefaultToolkit().getImage("img/down.png");
    public static Image leftImg = Toolkit.getDefaultToolkit().getImage("img/left.png");
    public static Image rightImg = Toolkit.getDefaultToolkit().getImage("img/right.png");
    //蛇身
    public static Image bodyImg = Toolkit.getDefaultToolkit().getImage("img/body.png");
    //食物
    public static Image foodImg = Toolkit.getDefaultToolkit().getImage("img/food.png");
    //关卡
    public static int level = 1;
    //绘制文字
    public static void drawWord(Graphics g,String str,Color color,int size,int x,int y){
        g.setColor(color);
        g.setFont(new Font("仿宋",Font.BOLD,size));
        g.drawString(str,x,y);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class snate extends JFrame implements KeyListener,Runnable { JLabel j; Canvas j1; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; //SnakeModel se=null; //222222 // boolean[][] matrix; LinkedList nodeArray = new LinkedList();//表 Node food;//节点 int maxX; int maxY; int direction = 2; boolean running = false; int timeInterval = 200; double speedChangeRate = 0.75; boolean paused = false; int score = 0; int countMove = 0; // UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; snate() { super(); //setSize(500,400); Container c=getContentPane(); j=new JLabel("Score:"); c.add(j,BorderLayout.NORTH); j1=new Canvas(); j1.setSize(canvasWidth+1,canvasHeight+1); j1.addKeyListener(this); c.add(j1,BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JLabel j2; j2 = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); p1.add(j2, BorderLayout.NORTH); j2 = new JLabel("ENTER or R or S for start;", JLabel.CENTER); p1.add(j2, BorderLayout.CENTER); j2 = new JLabel("SPACE or P for pause",JLabel.CENTER); p1.add(j2, BorderLayout.SOUTH); c.add(p1,BorderLayout.SOUTH); addKeyListener(this); pack(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // begin(); // //2222222 // this.gs = gs; this.maxX = maxX; this.maxY = maxY; // initial matirx matrix = new boolean[maxX][]; for(int i=0; i<maxX; ++i){ matrix[i] = new boolean[maxY]; Arrays.fill(matrix[i],false); } // initial the snake int initArrayLength = maxX > 20 ? 10 : maxX/2; for(int i = 0; i < initArrayLength; ++i){ int x = maxX/2+i; int y = maxY/2; nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } food = createFood(); matrix[food.x][food.y] = true; } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { //se.changeDirection(SnakeModel.UP); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { //se.changeDirection(SnakeModel.DOWN); } if(e.getKeyCode()==KeyEvent.VK_LEFT) { //se.changeDirection(SnakeModel.LEFT); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { //se.changeDirection(SnakeModel.RIGHT); } if(e.getKeyCode()==KeyEvent.VK_R||e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_ENTER) { } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void repaint() { Graphics g = j1.getGraphics(); //背景 g.setColor(Color.red); g.fillRect(0,0,canvasWidth,canvasHeight); //蛇 //g.setColor(Color.BLUE); } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10,10,10,10); } // //222222 // public void changeDirection(int newDirection){ if (direction % 2 != newDirection % 2){ direction = newDirection; } } public boolean moveOn(){ Node n = (Node)nodeArray.getFirst(); int x = n.x; int y = n.y; switch(direction){ case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){ if (matrix[x][y]){ if(x == food.x && y == food.y){ nodeArray.addFirst(food); int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10; countMove = 0; food = createFood(); matrix[food.x][food.y] = true; return true; } else return false; } else{ nodeArray.addFirst(new Node(x,y)); matrix[x][y] = true; n = (Node)nodeArray.removeLast(); matrix[n.x][n.y] = false; countMove++; return true; } } return false; } public void run(){ running = true; while (running){ try{ Thread.sleep(timeInterval); } catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood(){ int x = 0; int y = 0; do{ Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); }while(matrix[x][y]); return new Node(x,y); } public void speedUp(){ timeInterval *= speedChangeRate; } public void speedDown(){ timeInterval /= speedChangeRate; } public void changePauseState(){ paused = !paused; } public String toString(){ String result = ""; for(int i=0; i<nodeArray.size(); ++i){ Node n = (Node)nodeArray.get(i); result += "[" + n.x + "," + n.y + "]"; } return result; } } class Node{ int x; int y; Node(int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) { //Graphics g=j1.getGraphics(); snate s=new snate(); //s.draw_something(g); //s.setVisible(true); } }
可以运行! (以下代码只是其中的一个类) 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、付费专栏及课程。

余额充值