当前位置:文档之家› java版贪吃蛇小游戏

java版贪吃蛇小游戏

辅助类 Coordinate.java复制代码package com.nn.util;/***坐标点*/public class Coordinate {public int x;public int y;public Coordinate(int newX, int newY) { x = newX;y = newY;}public boolean equals(Coordinate other) { if (x == other.x && y == other.y) {return true;}return false;}@Overridepublic String toString() {return "Coordinate: [" + x + "," + y + "]";}}复制代码接口Direction复制代码package com.nn.entity;public interface Direction {public class Dir{public static final int UP = 1;public static final int DOWN = 2;public static final int LEFT = 3;public static final int RIGHT = 4;}}复制代码实体类Snake.java复制代码package com.nn.entity;import java.util.ArrayList;import com.nn.entity.Direction.Dir; import com.nn.util.Coordinate;public class Snake{//小方块x坐标private int x;//小方块y坐标private int y;//宽度public static final int TILE_W = 10;//高度public static final int TILE_H = 10;//下一个方向private int mNextDirection = Dir.RIGHT;//游戏是否结束private boolean isEnd;//存放贪吃蛇private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();//存放豆子private ArrayList<Coordinate> mAppleList = new ArrayList<Coordinate>();public Snake(){initNewGame();}//初始化新游戏public void initNewGame(){//初始化蛇身mSnakeTrail.add(new Coordinate(5, 7));mSnakeTrail.add(new Coordinate(6, 7));mSnakeTrail.add(new Coordinate(7, 7));mSnakeTrail.add(new Coordinate(8, 7));mSnakeTrail.add(new Coordinate(9, 7));mSnakeTrail.add(new Coordinate(10, 7));//初始化豆子mAppleList.add(new Coordinate(20,3));//设置初始状态为falseisEnd = false;}public ArrayList<Coordinate> getmSnakeTrail() { return mSnakeTrail;}public ArrayList<Coordinate> getmAppleList() { return mAppleList;}public boolean isEnd() {return isEnd;}public int getmNextDirection() {return mNextDirection;}public void setEnd(boolean isEnd) {this.isEnd = isEnd;}}复制代码frame类继承JFrame SnakeFrame.java复制代码package com.nn.ui;import java.awt.Dimension;import java.awt.Toolkit;import javax.swing.JFrame;/***游戏界面*/public class SnakeFrame extends JFrame{private static final long serialVersionUID = 1L;//宽度private static final int width = 530;//高度private static final int height = 450;//高度偏移量private static final int offset = 15;public SnakeFrame(){init();}/*** 初始化游戏界面*/private void init(){this.setTitle("Java版贪吃蛇_1.0");//frame的高度宽度this.setSize(width, height);//窗口居中显示Toolkit toolkit = Toolkit.getDefaultToolkit();Dimension screen = toolkit.getScreenSize();int w = screen.width;int h = screen.height;//计算左上角坐标点的x y值this.setLocation((w-this.getWidth())/2, (h-this.getHeight())/2-offset);//设置默认关闭的操作this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置窗口大小不可改变this.setResizable(false);//设置可见性this.setVisible(true);this.setLayout(null);}}复制代码panel j继承JPanel SnakePanel.java复制代码package com.nn.ui;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import javax.swing.JButton;import javax.swing.JPanel;import com.nn.control.PlayControl;import com.nn.entity.Snake;import com.nn.util.Coordinate;public class SnakePanel extends JPanel{private static final long serialVersionUID = 1L;//panel的宽度private static final int width = 400;//panel的高度private static final int height = 400;//坐标点xprivate static final int x = 10;//坐标点yprivate static final int y = 10;//方块尺寸private static final int SIZE = 10;//是否开启网格private boolean isOpen = false; private Snake snake;//开启作弊private JButton girdButton; private JButton aboutButton;//暂停继续按钮private JButton PauseButton;//重新开始游戏private JButton StartButton;public Snake getSnake() {return snake;}private ArrayList<Coordinate> mSnakeTrail = null; private ArrayList<Coordinate> mAppleList = null;public SnakePanel() {snake = new Snake();this.setLayout(null);StartButton = new JButton("重新开始");StartButton.setLocation(420,100);StartButton.setSize(90,26);this.add(StartButton);PauseButton = new JButton("暂停游戏");PauseButton.setLocation(420, 150);PauseButton.setSize(90,26);this.add(PauseButton);girdButton = new JButton("开启网格");girdButton.setLocation(420, 200);girdButton.setSize(90,26);this.add(girdButton);aboutButton = new JButton("关于游戏");aboutButton.setLocation(420, 250);aboutButton.setSize(90,26);this.add(aboutButton);girdButton.addActionListener(new GirdActionListener());aboutButton.addActionListener(new AboutActionListerner());}class GirdActionListener implements ActionListener{ int i = 1;public void actionPerformed(ActionEvent e) {if(i%2==1){girdButton.setText("关闭网格");isOpen = false;i++;}else if(i%2==0){girdButton.setText("开启网格");isOpen = true;i++;}}}class AboutActionListerner implements ActionListener{public void actionPerformed(ActionEvent e) {}}@Overridepublic void paintComponent(Graphics g) {super.paintComponent(g);creatGameWindow(g);if(snake.isEnd()){paintWords(g);}//将焦点定在Jpanel上this.requestFocus();}/*** 安装玩家控制器* @param control*/public void setGameControl(PlayControl control){ this.addKeyListener(control);}private void creatGameWindow(Graphics g) {g.setColor(Color.BLACK);g.drawRect(x, y, width, height);g.setColor(Color.WHITE);g.fillRect(x+1, y+1, width-1, height-1);g.setColor(Color.GRAY);/***************test******************/paintLine(g);/***************test******************/mSnakeTrail = snake.getmSnakeTrail();mAppleList = snake.getmAppleList();if(mSnakeTrail==null){return;}g.setColor(Color.BLACK);for(int i=0;i<mSnakeTrail.size();i++){g.fillRect(this.x+mSnakeTrail.get(i).x*SIZE, this.y+mSnakeTrail.get(i).y*SIZE,Snake.TILE_W, Snake.TILE_H);}//画豆子g.fillRect(this.x+mAppleList.get(0).x*SIZE, this.y+mAppleList.get(0).y*SIZE, Snake.TILE_W,Snake.TILE_H);}//画网格private void paintLine(Graphics g){for(int i = 1;i < 40;i++){g.drawLine(this.x, i*10+this.y, 400+this.x, i*10+this.y);}for(int i = 1;i < 40;i++){g.drawLine(i*10+this.x,this.y,i*10+this.x,400+this.y);}}//结束提示private void paintWords(Graphics g){Font font = new Font("宋体", Font.BOLD, 64);g.setFont(font);g.setColor(Color.RED);g.drawString("游戏结束",60,220);}}复制代码最关键的类控制类PlayControl.java复制代码package com.nn.control;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.ArrayList;import java.util.Random;import com.nn.entity.Direction.Dir;import com.nn.ui.SnakePanel;import com.nn.util.Coordinate;public class PlayControl implements KeyListener{private SnakePanel panel;//蛇头在list中索引private int headIndex;/*** 贪吃蛇列表*/ArrayList<Coordinate> mSnakeTrail;/** 豆子列表*/private ArrayList<Coordinate> mAppleList;//新产生的豆子Coordinate newCoordinate;private int mNextDirection;//是否绘制出结束提示private boolean isDraw = false;private Random random = new Random();public PlayControl(SnakePanel panel){this.panel = panel;mSnakeTrail = panel.getSnake().getmSnakeTrail();mAppleList = panel.getSnake().getmAppleList();mNextDirection = panel.getSnake().getmNextDirection();headIndex = mSnakeTrail.size()-1;Thread thread = new Thread(runnable);thread.start();}//响应键盘按下事件public void keyPressed(KeyEvent e) {if(isDraw){return;}switch (e.getKeyCode()) {case KeyEvent.VK_UP:if(mNextDirection!=Dir.DOWN){mNextDirection = Dir.UP;//moveUp();}break;case KeyEvent.VK_DOWN:if(mNextDirection!=Dir.UP){mNextDirection = Dir.DOWN;//moveDown();}break;case KeyEvent.VK_LEFT:if(mNextDirection!=Dir.RIGHT){mNextDirection = Dir.LEFT;//moveLeft();}break;case KeyEvent.VK_RIGHT:if(mNextDirection!=Dir.LEFT){mNextDirection = Dir.RIGHT;//moveRight();}break;}}@Overridepublic void keyReleased(KeyEvent e) {}@Overridepublic void keyTyped(KeyEvent e) {}//向上移动private void moveUp(){if(!isEndGame()){//每移动一次先在头部加一块list增加一个元素mSnakeTrail.add(newCoordinate(mSnakeTrail.get(headIndex).x, mSnakeTrail.get(headIndex).y-1));//如果判断吃到豆子if(isEat()){//吃到豆子的处理afterEatApple();}//否则移除第一个元素else {mSnakeTrail.remove(0);}//重新绘制panel.repaint();}}//向下移动private void moveDown(){if(!isEndGame()){mSnakeTrail.add(new Coordinate(mSnakeTrail.get(headIndex).x, mSnakeTrail.get(headIndex).y+1));if(isEat()){afterEatApple();}else {mSnakeTrail.remove(0);}panel.repaint();}}//向左移动private void moveLeft(){if(!isEndGame()){mSnakeTrail.add(new Coordinate(mSnakeTrail.get(headIndex).x-1, mSnakeTrail.get(headIndex).y));if(isEat()){afterEatApple();}else {mSnakeTrail.remove(0);}panel.repaint();}}//向右移动private void moveRight(){if(!isEndGame()){mSnakeTrail.add(new Coordinate(mSnakeTrail.get(headIndex).x+1, mSnakeTrail.get(headIndex).y));if(isEat()){afterEatApple();}else {mSnakeTrail.remove(0);}panel.repaint();}}//增加一个坐标点到存放蛇的list 添加到list的末尾private void afterEatApple(){//每增加一个索引值加1 重新开始游戏时要回复初始值headIndex++;mAppleList.add(newCoordinate(random.nextInt(40), random.nextInt(40)));mAppleList.remove(0);newCoordinate = mAppleList.get(0);//System.out.println("蛇身长度:"+mSnakeTrail.size());}//判断蛇是否吃到豆子private boolean isEat(){returnmSnakeTrail.get(mSnakeTrail.size()-1).equals(mAppleLis t.get(0));}//判断是否到边界或者碰到自己的身体private boolean isEndGame(){int x = mSnakeTrail.get(headIndex).x;int y = mSnakeTrail.get(headIndex).y;if(touchBody()||x<0||x>39||y<0||y>39){afterEndGame();return true;}return false;}//碰到自己身体private boolean touchBody(){for(int i =0;i<mSnakeTrail.size()-1;i++){if(mSnakeTrail.get(headIndex).equals(mSnakeTrail.get(i)) ){return true;}}return false;}//游戏结束处理private void afterEndGame(){mSnakeTrail.remove(headIndex);panel.getSnake().setEnd(true);panel.repaint();this.isDraw = true;}Runnable runnable = new Runnable() {public void run() {moveRight();while(!isEndGame()){if(mNextDirection==Dir.UP) moveUp();else if(mNextDirection==Dir.DOWN) moveDown();else if(mNextDirection==Dir.LEFT) moveLeft();else if(mNextDirection==Dir.RIGHT) moveRight();try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}};}复制代码最后是测试类SnakeTest.java复制代码package com.nn.main;import com.nn.control.PlayControl;import com.nn.ui.SnakeFrame;import com.nn.ui.SnakePanel;/**java版贪吃蛇小游戏*启动游戏**/public class SnakeTest {public static void main(String[] args) {SnakeFrame frame = new SnakeFrame();SnakePanel panel = new SnakePanel();PlayControl playControl = new PlayControl(panel);panel.setGameControl(playControl);//setContentPane()把panel设置为JFrame的内容面板frame.setContentPane(panel);}}31 / 31。

相关主题