贪吃蛇(二维数组)

这是我思考了一天的游戏,错过了两节课,心痛啊,总用时2个星期,感动!!!

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SupervisoryControlDesk extends JFrame implements ActionListener,
		ChangeListener, KeyListener {
	private static final long serialVersionUID = 1L;
	protected DataOfMatrix dataOfMatrix;
	Paint_canvas paint_canvas;
	GluttonousSnake gluttonousSnake;
	JButton btn_control, btn_reflesh;
	JSpinner spinner;

	public SupervisoryControlDesk() {
		super("贪吃蛇-(安心)");
		dataOfMatrix = new DataOfMatrix();
		paint_canvas = new Paint_canvas(dataOfMatrix);
		gluttonousSnake = new GluttonousSnake(this, dataOfMatrix, paint_canvas);
		setLayout(new BorderLayout());
		plusNorth();
		plusCenter();
		setBounds(300, 0, 615, 678);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}

	private void plusCenter() {
		getContentPane().add(paint_canvas);
	}

	private void plusNorth() {
		btn_control = new JButton("Start");
		btn_control.addActionListener(this);
		spinner = new JSpinner();
		spinner.setValue(500);
		spinner.addChangeListener(this);
		JPanel panel = new JPanel();
		getContentPane().add(panel, "North");
		panel.add(btn_control);
		panel.add(spinner);
		btn_reflesh = new JButton("Reflesh");
		panel.add(btn_reflesh);
		btn_reflesh.addActionListener(this);
	}

	public static void main(String[] args) {
		new SupervisoryControlDesk();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equalsIgnoreCase("Start")) {
			btn_control.setText("End");
			btn_control.addKeyListener(this);
			gluttonousSnake.timer.restart();
			gluttonousSnake.isStart = true;
			dataOfMatrix.reflesh();
		}
		if (e.getActionCommand().equalsIgnoreCase("End")) {
			btn_control.setText("Start");
			btn_control.removeKeyListener(this);
			gluttonousSnake.timer.stop();
			gluttonousSnake.isStart = false;
		}
		if (e.getSource() == btn_reflesh) {
			if (dataOfMatrix != null) {
				dataOfMatrix.reflesh();
				paint_canvas.repaint();
				btn_control.requestFocus();
			}
		}
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		try {
			int size = Integer.parseInt(""+spinner.getValue());
			if(size<10||size>1000){
				size = 500;
			}
			gluttonousSnake.timer.setDelay(size);
			btn_control.requestFocus();
		} catch (NumberFormatException e1) {
			JOptionPane.showConfirmDialog(this, "输入的值错误,请从新输入!!");
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {// 不用
	}

	@Override
	public void keyPressed(KeyEvent e) {// 目标
		gluttonousSnake.snakeMove_Listiner(e);
	}

	@Override
	public void keyReleased(KeyEvent e) {// 不用
	}

}
public class DataOfMatrix {
	int foodNumber = 10;
	int width , height;//行 列
	int[][] snakeMatrix;

	public DataOfMatrix() {
		set(30,30);
		decorateFood();
	}

	public void set(int width,int height){
		this.width = width;
		this.height = height;
		snakeMatrix = new int[width][height];
		//测试数据
//		for (int i = 0; i < width; i++) {
//			snakeMatrix[i][0] = 4;
//			snakeMatrix[i][height-1] = 4;
//		}
//		for (int j = 0; j < height; j++) {
//			snakeMatrix[0][j] = 4;
//			snakeMatrix[width-1][j] = 4;
//		}
	}

	public void decorateFood() {// decorateFood 布置食物
		int[] temp = decorateFood_number();
		for (int i = 0; i < temp.length; i++) {
			int text_i = temp[i] / height;
			int text_j = temp[i] % height;
			snakeMatrix[text_i][text_j] = 4;// 食物为4
		}
	}

	public int[] decorateFood_number() {// 布置指定范围数量的食物个数
		int[] mat = new int[foodNumber];
		for (int i = 0; i < mat.length; i++) {
			mat[i] = isExist(mat, getRandomNumber());
		}
		return mat;
	}

	public int isExist(int[] mat, int rand) {
		for (int i = 0; i < mat.length; i++) {
			if (rand == mat[i]) {
				rand = getRandomNumber();
				rand = isExist(mat, rand);
			}
		}
		return rand;
	}

	public int getRandomNumber() {
		int temp = (int) (Math.random() * 1000) % (width * height);
		return temp;
	}

	public void reflesh(){
		for (int i = 0; i < snakeMatrix.length; i++) {
			for (int j = 0; j < snakeMatrix[i].length; j++) {
				snakeMatrix[i][j] = 0;
			}
		}
		decorateFood();
		System.out.println("刷新");
	}

}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.Timer;

public class GluttonousSnake implements ActionListener {
	static int countSnake_number = 6;
	SupervisoryControlDesk supervisoryControlDesk;
	DataOfMatrix dataOfMatrix;
	Paint_canvas paint_canvas;
	SnakePartly[] smallSnake;
	Timer timer;
	boolean isStart;

	public GluttonousSnake(SupervisoryControlDesk supervisoryControlDesk,
			DataOfMatrix dataOfMatrix, Paint_canvas paint_canvas) {
		this.supervisoryControlDesk = supervisoryControlDesk;
		this.dataOfMatrix = dataOfMatrix;
		this.paint_canvas = paint_canvas;
		bornFromSnakeBody();
		timer = new Timer(100, this);
		timer.setDelay(500);
	}

	private void bornFromSnakeBody() {
		smallSnake = new SnakePartly[17];// 0号不用
		// 1+10+1 头-身体-尾,第一个不用,用来做方向
		int[] temp = new int[4];
		temp[1] = 1;// 默认向下
		for (int i = 0; i < smallSnake.length; i++) {
			smallSnake[i] = new SnakePartly(15 - i, 8, temp);
		}
		smallSnake[1].setShape(1);
		smallSnake[2].setShape(2);
		smallSnake[3].setShape(2);
		smallSnake[4].setShape(2);
		smallSnake[5].setShape(3);
	}

	public void snakeMove_Listiner(KeyEvent e) {
		smallSnake[0].reflesh();
		if (e.getKeyCode() == KeyEvent.VK_UP) {
			smallSnake[0].directions[0] = -1;
		}
		if (e.getKeyCode() == KeyEvent.VK_DOWN) {
			smallSnake[0].directions[1] = 1;
		}
		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
			smallSnake[0].directions[2] = -1;
		}
		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
			smallSnake[0].directions[3] = 1;
		}
	}

	public void snake_move() {
		// 擦掉最后一个元素
		dataOfMatrix.snakeMatrix[smallSnake[countSnake_number - 1].x][smallSnake[countSnake_number - 1].y] = 0;
		for (int i = countSnake_number - 1; i > 0; i--) {// i = 5初始不小于5
			// 改变方向
			for (int j = 0; j < smallSnake[i].directions.length; j++) {
				smallSnake[i].directions[j] = smallSnake[i - 1].directions[j];
			}
			int text_i = smallSnake[i].x + smallSnake[i].directions[0]
					+ smallSnake[i].directions[1];
			int text_j = smallSnake[i].y + smallSnake[i].directions[2]
					+ smallSnake[i].directions[3];
			// 撞墙就以顺时针的方向为准
			// 0 上 1 下 2 左 3 右
			if (text_j < 0) {// 左
				text_j = dataOfMatrix.width-1;
			}
			if (text_j == dataOfMatrix.width) {// 右
				text_j = 0;
			}
			if (text_i < 0) {// 上
				text_i = dataOfMatrix.height-1;
			}
			if (text_i == dataOfMatrix.height) {// 下
				text_i = 0;
			}
			//从头吃,尾长
			if (i == 1 && dataOfMatrix.snakeMatrix[text_i][text_j] == 4) {// 贪吃,只能可能是头吃
				countSnake_number++;
				for (int j = 0; j < 4; j++) {
					smallSnake[countSnake_number-1].directions[j] =
							smallSnake[countSnake_number-2].directions[j];
				}
				smallSnake[countSnake_number-1].x =
						smallSnake[countSnake_number-2].x+
						-(smallSnake[countSnake_number-1].directions[0]+
								smallSnake[countSnake_number-1].directions[1]
						);
				smallSnake[countSnake_number-1].y =
						smallSnake[countSnake_number-2].y+
						-(smallSnake[countSnake_number-1].directions[2]+
								smallSnake[countSnake_number-1].directions[3]
								);

				smallSnake[countSnake_number-2].body_shape = 2;
				smallSnake[countSnake_number-1].body_shape = 3;
			}
			// 改变蛇的位置
			smallSnake[i].x = text_i;
			smallSnake[i].y = text_j;
			// 将蛇的数据放入数组中
			dataOfMatrix.snakeMatrix[text_i][text_j] = smallSnake[i].body_shape;
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {// timer 定时调用
		if (!isStart) {
			return;
		}
		if (countSnake_number > 15) {//蛇脱皮,也可以吃蛇皮
			System.out.println("吃饱了");
			countSnake_number = 6;
			smallSnake[countSnake_number-1].body_shape = 3;
			isStart = false;
			dataOfMatrix.snakeMatrix[0][0] = 10;
			paint_canvas.repaint();
			supervisoryControlDesk.btn_control.setText("Start");
			return;
		}
		snake_move();
		paint_canvas.repaint();
	}

}

class SnakePartly {
	public int x, y;
	public int[] directions = new int[4];
	public int body_shape;

	public SnakePartly(int x, int y, int[] location) {
		set(x, y, location, 0);// 默认不画
	}

	public void reflesh() {
		if (directions != null) {
			for (int i = 0; i < directions.length; i++) {
				directions[i] = 0;
			}
		}
	}

	public void set(int x, int y, int[] directions, int body_shape) {
		this.x = x;
		this.y = y;
		for (int i = 0; i < directions.length; i++) {
			this.directions[i] = directions[i];
		}
		this.body_shape = body_shape;
	}

	public void setShape(int shape) {
		this.body_shape = shape;
	}

	public void setLocation(int[] location) {
		for (int i = 0; i < location.length; i++) {
			directions[i] = location[i];
		}
	}

	public void setLocation(int n) {
		int temp[] = new int[4];
		if (n == 0 || n == 2) {
			temp[n] = -1;
		}
		if (n == 1 || n == 3) {
			temp[n] = 1;
		}
		setLocation(temp);
	}

}
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class Paint_canvas extends Canvas {
	private static final long serialVersionUID = 1L;
	DataOfMatrix dataOfMatrix;
	boolean isChangColor;

	public Paint_canvas(DataOfMatrix dataOfMatrix) {
		this.dataOfMatrix = dataOfMatrix;
		this.setSize(600, 600);
	}

	@Override
	public void paint(Graphics g) {
		if (dataOfMatrix != null) {
			if(dataOfMatrix.snakeMatrix[0][0]==10){
				Font fontGameOver = new Font("宋体", Font.BOLD, 50);
				g.setFont(fontGameOver);
				g.setColor(Color.red);
				g.drawString("游戏结束", 120, 180);
			}
			for (int i = 0; i < dataOfMatrix.width; i++) {
				g.setColor(Color.blue);
				g.drawLine(i * 20, 0, i * 20, 600);// 列
			}
			for (int j = 0; j < dataOfMatrix.height; j++) {
				g.setColor(Color.blue);
				g.drawLine(0, j * 20, 600, j * 20);// 行
			}
			for (int i = 0; i < dataOfMatrix.width; i++) {
				for (int j = 0; j < dataOfMatrix.height; j++) {
					if (dataOfMatrix.snakeMatrix[i][j] == 4) {
						if(isChangColor){
							g.setColor(Color.blue);
						}else{
							g.setColor(Color.red);
						}
						isChangColor = !isChangColor;
						g.fillOval(j * 20,i * 20, 20, 20);// 行
					}
					if (dataOfMatrix.snakeMatrix[i][j] == 3) {
						g.setColor(Color.black);
						g.drawLine(j * 20, i * 20, j * 20 + 20, i * 20);// 上
						g.drawLine(j * 20 + 10, i * 20, j * 20, i * 20 + 20);// 中间,左下脚
						g.drawLine(j * 20 + 10, i * 20, j * 20 + 20,
								i * 20 + 20);// 中间,右下脚
					}
					if (dataOfMatrix.snakeMatrix[i][j] == 2) {
						g.setColor(Color.gray);
						g.fillRect(j * 20,i * 20, 20, 20);
					}
					if (dataOfMatrix.snakeMatrix[i][j] == 1) {
						g.setColor(Color.black);
						g.fillOval(j * 20,i * 20, 20, 15);
					}
				}
			}
		}
	}

}
时间: 2024-10-16 19:49:39

贪吃蛇(二维数组)的相关文章

C++ 贪吃蛇二维

#include <iostream> #include <conio.h> #include <windows.h> #include <time.h> int g_Dir = 3; #define UP 0 #define DOWN 1 #define LEFT 2 #define RIGHT 3 struct FOOD { int X = 0; int Y = 0; bool State = 0; }Food; //方向控制 void SnekeMov

小游戏●贪吃蛇1(利用二维数组制作)

利用二维数组编写简单贪吃蛇小游戏,由于是初学C#,用的是单线程,所以蛇不会自动前进 代码及简要分析如下: 1 //定义地图,0为空,1为墙,2为蛇,3为食物 2 int[,] map = new int[15, 15]{ 3 {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 4 {1,2,0,0,0,0,0,0,0,0,0,0,0,0,1}, 5 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, 6 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

14-高效求最长公共子序列(二维数组存不下)

/*                                   See LCS again时间限制:1000 ms  |  内存限制:65535 KB难度:3 描述 There are A, B two sequences, the number of elements in the sequence is n.m; Each element in the sequence are different and less than 100000. Calculate the length

java基础:java中的二维数组

二维数组的概念: 一个元素为一维数组的数组. 格式1: 数据类型[][] 数组名 = new 数据类型[m][n]; m:表示这个二维数组有多少个一维数组. n:表示每一个一维数组的元素有多少个. 注意: A:以下格式也可以表示二维数组 a:数据类型 数组名[][] = new 数据类型[m][n]; b:数据类型[] 数组名[] = new 数据类型[m][n]; B:注意下面定义的区别 int x; int y; int x,y; int[] x; int[] y[]; int[] x,y[

二维数组

int[][]arr; arr=new int[5][6];//定义二维数组 int [][]grade=new int [5][6]//直接定义 for each循环:不使用下表就能访问: int=[]mum={12345} for(int a :m){ System.out.print(a)}  //num数组  a 12345;

二维数组与指针

二维数组: int / char / flaot a[n][m]; 可以看做是将一维数组做为基本类型产生的一维数组的数组类型,共n*m个最基本类型.这样看有许多优点(实际上计算机也是这样分配的). 二维数组数组名的注意事项: 1 #include <stdio.h> 2 int main() 3 { 4 int *p,a[3][4]; 5 p = a;//a是二维数组的首地址本质为行指针,原型为 a[][]:无法赋值给普通指针类型 *p: 6 return 0; 7 } 编译就会出现如下错误

二维数组中的查找-牛客网-剑指offer

1.问题描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 2.问题分析 水平方向.垂直方向二重循环查找 3.源代码 package www.nowcoder.com.conquerOffer.array; /** * 二维数组中的查找 * 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整

面试题3 ----二维数组中的查找

题目: 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 在剩下的两行两列4个数字中,位于右上角的刚好就是我们要查找的数字7,于是查找过程就可以结束了. 矩阵的加阴影背景的区域是下一步查找的范围.代码如下: bool Find(int* matrix,int  rows,int columns,int number) { bool found = false; if (matri

qsort 函数的使用——对普通数组、指针数组、二维数组中的元素进行排序

在ANSI C中,qsort函数的原型是 #include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *)); 解释:qsort函数对含有nmemb个元素的数组进行排序,而base指针指向数组的第一个元素.这个数组的元素个数由size指定. compar函数对qsort的比较操作进行定义,所以可以定制数字的比较,字符串的比较,甚至结构体

JavaScript - 一维数组、二维数组基础

<html> <head> <head> <body> <script language="javascript"> // 数组 var arr = ["wjp", 520, 'wcc', 13.14] ; for(var i=0; i<arr.length; i++){ alert(arr[i]); } // 数组为空undefined var arr2 = ["wjp",,51