贪吃蛇小游戏代码

框架区 

package 结果;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
 
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
 
public class SnakeJPanel extends JPanel implements ActionListener{
	
	private boolean start;//当前游戏状态
	
	private int speed;//速度
	
    private boolean exist;//当前是否存在食物
    
    private int foodType;//食物种类
    
    private int x;//豆子的横坐标
    private int y;//豆子的纵坐标
	
	private ArrayList<int[]> localList;//蛇
	
	
	public String direction;//方向
	
	private String direction2;//引导方向
	
	public boolean flag;
	
	Random rand = new Random();
 
	private ImageIcon up;
 
	private ImageIcon down;
 
	private ImageIcon right;
 
	private ImageIcon left;
 
	private ImageIcon body;
 
	private ImageIcon food;
 
	private ImageIcon title;
	
	Timer time;
	
	private int score;//当前得分情况
	
	private int num;//吃到的食物个数
	
//    private Image offScreenImage;  //图形缓存
	
	
	//图片绘制
	@Override
	public void paint(Graphics g) {
		
		direction = direction2;
		
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 900, 700);
		
		//绘制游戏框
		//标题框
//		g.drawRect(25, 30, 800, 75);
		title.paintIcon(this, g, 25, 10);
		
		//内容框
		g.setColor(Color.black);
		g.fillRect(25, 75, 850, 600);
		
		//绘制食物的坐标位置
		if(!exist) {//如果当前不存在豆子,随机绘制一个豆子	
			if(num % 5 == 0) {
				foodType = 1;
			}else {
				foodType = 0;
			}
			boolean isProduce = true;
			while(isProduce) {
				isProduce = false;
				x = rand.nextInt(33) * 25 + 25;		
				y = rand.nextInt(23) * 25 + 75;			
				for (int[] arr:localList) {
					if(x == arr[0] && y == arr[1]) {	
						isProduce = true;
						break;	
					}
				}
				
			}			
			System.out.println(x + "---" + y);
		}
		
		 if(eat()) {
	        exist = false;
		 }else {
			exist = true;
		 }
		 
		 
		if(foodType == 0) {
			//绘制食物
			g.setColor(Color.blue);
//			g.fillRect(x, y, 25, 25);
			g.drawImage(food.getImage(),x, y, 25, 25,null);
		}else {
			//绘制食物
			g.setColor(Color.WHITE);
			g.fillRect(x, y, 25, 25);
//			g.drawImage(food.getImage(),x, y, 25, 25,null);
		}
	
			
		//绘制头
		g.setColor(Color.red);
//		g.fillRect(localList.get(0)[0], localList.get(0)[1], 25, 25);	
		ImageIcon head = null;
		//判断当前方向
		if(direction.equals("R")) {
			 head = right;
		}else if(direction.equals("L")) {
			 head = left;
		}else if(direction.equals("U")) {
			 head = up;
		}else if(direction.equals("D")) {
			 head = down;
		}		
//		g.drawImage(head.getImage(), localList.get(0)[0], localList.get(0)[1], 25, 25,null);
		head.paintIcon(this, g,localList.get(0)[0], localList.get(0)[1]);
		
		//绘制身体
		g.setColor(Color.white);
		for (int i = 1; i < localList.size(); i++) {
//			g.fillRect(localList.get(i)[0], localList.get(i)[1], 25, 25);
//			g.drawImage(body.getImage(), localList.get(i)[0], localList.get(i)[1], 25, 25,null);
			body.paintIcon(this, g, localList.get(i)[0], localList.get(i)[1]);
		}
//		g.fillRect(localList.get(1)[0], localList.get(1)[1], 25, 25);
//		g.fillRect(localList.get(2)[0], localList.get(2)[1], 25, 25);
			
		
		//绘制分数和长度
		//长度
		g.setColor(Color.GREEN);
		g.setFont(new Font("宋体", Font.BOLD, 18));
		g.drawString("长度:" + (localList.size() - 1), 25, 30);
		
		//分数
		g.drawString("分数:" + score, 25, 48);
		
		if(!start) {//如果游戏未启动,结束移动和重绘
			g.setColor(Color.white);
			g.setFont(new Font("宋体", Font.BOLD, 30));
			g.drawString("暂停/开始(请按任意键开始,空格键暂停)", 150, 300);
			time.stop();
			
		}else {
			time.start();
		}
			
//		speed();
		//移动后进行下一次绘制		
//      move();//移动
//		repaint();//重新绘制		
	}
	
//	//解决闪烁问题
//	//如果为JFrame 为重量级  程序不会调用update()方法
//	//如果为Frame 为轻量级  重写update()方法 做双缓冲
//	//如果为JPanel 不会闪烁
//	  @Override
//	    public void update(Graphics g)
//	    {
//	    	System.out.println("update");
//	           if(offScreenImage == null)
//	              offScreenImage = this.createImage(900, 700);  //新建一个图像缓存空间,这里图像大小为800*600
//	              Graphics gImage = offScreenImage.getGraphics();  //把它的画笔拿过来,给gImage保存着
//	              paint(gImage);                                   //将要画的东西画到图像缓存空间去
//	              g.drawImage(offScreenImage, 0, 0, null);         //然后一次性显示出来
//	    }
	
 
	@Override
	public void actionPerformed(ActionEvent e) {	    
	    //移动后进行下一次绘制		
        move();//移动
	    repaint();//重新绘制		
		
	}
 
	/**
	 * 绘制速度
	 */
//	private void speed() {
//		try {//按一定速度进行移动
//			Thread.sleep(speed);//控制移动速度
//		} catch (InterruptedException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
//	}
 
	/**
	 * 初始化图片
	 */
	private void drawImage() {
		up = new ImageIcon("src/图片/up.png");
		down = new ImageIcon("src/图片/down.png");
		right = new ImageIcon("src/图片/right.png");
		left = new ImageIcon("src/图片/left.png");
		body = new ImageIcon("src/图片/body.png");
		food = new ImageIcon("src/图片/food.png");
		title = new ImageIcon("src/图片/title.jpg");
	}
	
	private boolean eat() {
		if(localList.get(0)[0] == x && localList.get(0)[1] == y) {//如果当前蛇头吃到了豆子
			System.out.println("eat");
			num++;
			if(foodType == 0) {
				score += 10;
			}else {
				score += (rand.nextInt(5) * 10 + 10);
			}
			int last = localList.size() - 1;//蛇尾			
			//在蛇尾后面添加一节身体
			localList.add(new int[] {localList.get(last)[0],localList.get(last)[1]});
			return true;
		}
		return false;
	}
 
	//移动方法
	public void move() {
		//判断是否游戏结束
		if(isbody()) {
			System.out.println("game over");
			start = false;//结束游戏移动
			JOptionPane.showMessageDialog(null,"游戏已结束!");
			time.stop();
			init();		
		}
			
		if(flag && localList != null) {//如果长度不为空且游戏未结束				
			int last = localList.size() - 1;//记录蛇尾
			
			for (int i = last; i > 0; i--) {//从蛇尾开始,每节身体移动到前一节身体的位置上
				localList.set(i,new int[] {localList.get(i - 1)[0],localList.get(i - 1)[1]});
			}
			
			//记录头位置
			int[] local = localList.get(0);
			//判断当前方向,并进行模拟移动,判断是否与边界重合
			if(direction.equals("R")) {
				if(local[0] >= 850) {
					local[0] = 25;
				}else {
					local[0] += 25;
				}
				
			}else if(direction.equals("L")) {
				if(local[0] <= 25) {
					local[0] = 850;
				}else {
					local[0] -= 25;
				}
				
			}else if(direction.equals("U")) {
				
				if(local[1] <= 75) {
					local[1] = 650;
				}else {
					local[1] -= 25;
				}
				
			}else if(direction.equals("D")) {
				if(local[1] >= 650) {
					local[1] = 75;
				}else {
					local[1] += 25;
				}
				
			}			
						
			//更改头的位置
			localList.set(0, local);		
		}	
	}
	
	//判断下一步是否为蛇身
	private boolean isbody() {
		// TODO 自动生成的方法存根
		//记录头位置
		int x = localList.get(0)[0];
		int y = localList.get(0)[1];
 
		//判断当前方向,并进行模拟移动,判断是否与边界重合
		if(direction.equals("R")) {
			x += 25;
		}else if(direction.equals("L")) {
			x -= 25;
		}else if(direction.equals("U")) {
			y -= 25;
		}else if(direction.equals("D")) {
			y += 25;
		}			
		
		for (int i = 1; i < localList.size(); i++) {
			if(localList.get(i)[0] == x && localList.get(i)[1] == y) {
				return true;
			}
		}
		return false;
 
	}
	
//	//判断下一步是否为边界
//	private boolean isborder() {
//		// TODO 自动生成的方法存根
//		//记录头位置
//		// TODO 自动生成的方法存根
//		//记录头位置
//		int x = localList.get(0)[0];
//		int y = localList.get(0)[1];
//
//		//判断当前方向,并进行模拟移动,判断是否与边界重合
//		if(direction.equals("R")) {
//			x += 25;
//		}else if(direction.equals("L")) {
//			x -= 25;
//		}else if(direction.equals("U")) {
//			y -= 25;
//		}else if(direction.equals("D")) {
//			y += 25;
//		}	
//				
//		if(x < 25 || x > (33 * 25 + 25)) {
//			return true;//当x坐标超出边界,则返回true
//		}
//		if(y < 105 || y > (23 * 25 + 105)) {
//			return true;//当y坐标超出边界,则返回true
//		}
//		return false;//蛇头移动后未超出边界,返回false
//		
//	}
 
	/**
	 * Create the frame.
	 */
	public SnakeJPanel(int speed) {
		
		this.speed = speed; //初始化速度
		
		//初始化游戏面板的基本信息
		this.setSize(900, 700);
		this.setLocation(0, 30);
		this.setFocusable(true);
		
		init();//初始化界面
		drawImage();//绘制图片
		moveByKey();//给界面添加一个键盘监听
				
	}
 
	/*
	 * 键盘监听
	 * 通过键盘输入上下左右来控制当前蛇头移动的方向
	 * 先判断当前蛇头方向,再来改变引导方向
	 * 当进行绘制时再修改蛇的方向
	 * 保证不会因为在短时间内快速变换方向导致蛇头逆向转向
	 */
	private void moveByKey() {
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				int key = e.getKeyCode();
				//边界值判断
				switch(key) {
				case 65:
				case 37:{//向左走
					if(!direction.equals("R")) {
						direction2 = "L";
						
					}
					break;
				}				
				case 87:
				case 38:{//向上走
					if(!direction.equals("D")) {
						direction2 = "U";
					}				
					break;
				}				
				case 68:
				case 39:{//向右走
					if(!direction.equals("L")) {
						direction2 = "R";
					}
					break;
				}
				case 83:
				case 40:{//向下走
					if(!direction.equals("U")) {
						direction2 = "D";
					}					
					break;
				}
				case KeyEvent.VK_SPACE:{//如果当前键盘输入为空格
					start = !start;//调整游戏状态
					System.out.println("暂停/开始");
					repaint();//重绘
				}
				}
				
				//任意键开始
				if(!start && key != KeyEvent.VK_SPACE) {//如果当前状态为暂停状态,且键盘输入不是空格
					start = true;
					repaint();//重绘
					
				}				
			}
		});
	}
 
	/**
	 * 初始化游戏基本信息
	 */
	private void init() {
		start = false;
 
		exist = true;
 
		direction2 = "U";
 
		flag = true;
 
		localList = new ArrayList<int[]>();
 
		localList.add(0,new int[] {75,125});//蛇头
		localList.add(1,new int[] {75,150});//蛇身1
		localList.add(2,new int[] {75,175});//蛇身2
 
		//创建第一个食物的位置
		//通过循环保证当前生成的食物不在身体所在的坐标上
		boolean isProduce = true;
		while(isProduce) {//循环生成食物坐标
			isProduce = false;//结束本次循环
			x = rand.nextInt(33) * 25 + 25;		
			y = rand.nextInt(23) * 25 + 75;			
			for (int[] arr:localList) {//循环遍历蛇头及蛇身的坐标
				if(x == arr[0] && y == arr[1]) {//如果食物坐标和蛇的某一节坐标重合
					isProduce = true;//跳转循环状态,继续下一次食物生成
					break;	
				}
			}
			//蛇身遍历完成,没有重合坐标,结束食物坐标生成
							
		}
 
		time = new Timer(speed, this);
		setLayout(null);
 
		score = 0;
 
		num = 0;
		
		foodType = 0;
		
//		repaint();
		
	}
 
 
}
package 结果;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
 
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
 
public class SnakeJPanel extends JPanel implements ActionListener{
	
	private boolean start;//当前游戏状态
	
	private int speed;//速度
	
    private boolean exist;//当前是否存在食物
    
    private int foodType;//食物种类
    
    private int x;//豆子的横坐标
    private int y;//豆子的纵坐标
	
	private ArrayList<int[]> localList;//蛇
	
	
	public String direction;//方向
	
	private String direction2;//引导方向
	
	public boolean flag;
	
	Random rand = new Random();
 
	private ImageIcon up;
 
	private ImageIcon down;
 
	private ImageIcon right;
 
	private ImageIcon left;
 
	private ImageIcon body;
 
	private ImageIcon food;
 
	private ImageIcon title;
	
	Timer time;
	
	private int score;//当前得分情况
	
	private int num;//吃到的食物个数
	
//    private Image offScreenImage;  //图形缓存
	
	
	//图片绘制
	@Override
	public void paint(Graphics g) {
		
		direction = direction2;
		
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 900, 700);
		
		//绘制游戏框
		//标题框
//		g.drawRect(25, 30, 800, 75);
		title.paintIcon(this, g, 25, 10);
		
		//内容框
		g.setColor(Color.black);
		g.fillRect(25, 75, 850, 600);
		
		//绘制食物的坐标位置
		if(!exist) {//如果当前不存在豆子,随机绘制一个豆子	
			if(num % 5 == 0) {
				foodType = 1;
			}else {
				foodType = 0;
			}
			boolean isProduce = true;
			while(isProduce) {
				isProduce = false;
				x = rand.nextInt(33) * 25 + 25;		
				y = rand.nextInt(23) * 25 + 75;			
				for (int[] arr:localList) {
					if(x == arr[0] && y == arr[1]) {	
						isProduce = true;
						break;	
					}
				}
				
			}			
			System.out.println(x + "---" + y);
		}
		
		 if(eat()) {
	        exist = false;
		 }else {
			exist = true;
		 }
		 
		 
		if(foodType == 0) {
			//绘制食物
			g.setColor(Color.blue);
//			g.fillRect(x, y, 25, 25);
			g.drawImage(food.getImage(),x, y, 25, 25,null);
		}else {
			//绘制食物
			g.setColor(Color.WHITE);
			g.fillRect(x, y, 25, 25);
//			g.drawImage(food.getImage(),x, y, 25, 25,null);
		}
	
			
		//绘制头
		g.setColor(Color.red);
//		g.fillRect(localList.get(0)[0], localList.get(0)[1], 25, 25);	
		ImageIcon head = null;
		//判断当前方向
		if(direction.equals("R")) {
			 head = right;
		}else if(direction.equals("L")) {
			 head = left;
		}else if(direction.equals("U")) {
			 head = up;
		}else if(direction.equals("D")) {
			 head = down;
		}		
//		g.drawImage(head.getImage(), localList.get(0)[0], localList.get(0)[1], 25, 25,null);
		head.paintIcon(this, g,localList.get(0)[0], localList.get(0)[1]);
		
		//绘制身体
		g.setColor(Color.white);
		for (int i = 1; i < localList.size(); i++) {
//			g.fillRect(localList.get(i)[0], localList.get(i)[1], 25, 25);
//			g.drawImage(body.getImage(), localList.get(i)[0], localList.get(i)[1], 25, 25,null);
			body.paintIcon(this, g, localList.get(i)[0], localList.get(i)[1]);
		}
//		g.fillRect(localList.get(1)[0], localList.get(1)[1], 25, 25);
//		g.fillRect(localList.get(2)[0], localList.get(2)[1], 25, 25);
			
		
		//绘制分数和长度
		//长度
		g.setColor(Color.GREEN);
		g.setFont(new Font("宋体", Font.BOLD, 18));
		g.drawString("长度:" + (localList.size() - 1), 25, 30);
		
		//分数
		g.drawString("分数:" + score, 25, 48);
		
		if(!start) {//如果游戏未启动,结束移动和重绘
			g.setColor(Color.white);
			g.setFont(new Font("宋体", Font.BOLD, 30));
			g.drawString("暂停/开始(请按任意键开始,空格键暂停)", 150, 300);
			time.stop();
			
		}else {
			time.start();
		}
			
//		speed();
		//移动后进行下一次绘制		
//      move();//移动
//		repaint();//重新绘制		
	}
	
//	//解决闪烁问题
//	//如果为JFrame 为重量级  程序不会调用update()方法
//	//如果为Frame 为轻量级  重写update()方法 做双缓冲
//	//如果为JPanel 不会闪烁
//	  @Override
//	    public void update(Graphics g)
//	    {
//	    	System.out.println("update");
//	           if(offScreenImage == null)
//	              offScreenImage = this.createImage(900, 700);  //新建一个图像缓存空间,这里图像大小为800*600
//	              Graphics gImage = offScreenImage.getGraphics();  //把它的画笔拿过来,给gImage保存着
//	              paint(gImage);                                   //将要画的东西画到图像缓存空间去
//	              g.drawImage(offScreenImage, 0, 0, null);         //然后一次性显示出来
//	    }
	
 
	@Override
	public void actionPerformed(ActionEvent e) {	    
	    //移动后进行下一次绘制		
        move();//移动
	    repaint();//重新绘制		
		
	}
 
	/**
	 * 绘制速度
	 */
//	private void speed() {
//		try {//按一定速度进行移动
//			Thread.sleep(speed);//控制移动速度
//		} catch (InterruptedException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
//	}
 
	/**
	 * 初始化图片
	 */
	private void drawImage() {
		up = new ImageIcon("src/图片/up.png");
		down = new ImageIcon("src/图片/down.png");
		right = new ImageIcon("src/图片/right.png");
		left = new ImageIcon("src/图片/left.png");
		body = new ImageIcon("src/图片/body.png");
		food = new ImageIcon("src/图片/food.png");
		title = new ImageIcon("src/图片/title.jpg");
	}
	
	private boolean eat() {
		if(localList.get(0)[0] == x && localList.get(0)[1] == y) {//如果当前蛇头吃到了豆子
			System.out.println("eat");
			num++;
			if(foodType == 0) {
				score += 10;
			}else {
				score += (rand.nextInt(5) * 10 + 10);
			}
			int last = localList.size() - 1;//蛇尾			
			//在蛇尾后面添加一节身体
			localList.add(new int[] {localList.get(last)[0],localList.get(last)[1]});
			return true;
		}
		return false;
	}
 
	//移动方法
	public void move() {
		//判断是否游戏结束
		if(isbody()) {
			System.out.println("game over");
			start = false;//结束游戏移动
			JOptionPane.showMessageDialog(null,"游戏已结束!");
			time.stop();
			init();		
		}
			
		if(flag && localList != null) {//如果长度不为空且游戏未结束				
			int last = localList.size() - 1;//记录蛇尾
			
			for (int i = last; i > 0; i--) {//从蛇尾开始,每节身体移动到前一节身体的位置上
				localList.set(i,new int[] {localList.get(i - 1)[0],localList.get(i - 1)[1]});
			}
			
			//记录头位置
			int[] local = localList.get(0);
			//判断当前方向,并进行模拟移动,判断是否与边界重合
			if(direction.equals("R")) {
				if(local[0] >= 850) {
					local[0] = 25;
				}else {
					local[0] += 25;
				}
				
			}else if(direction.equals("L")) {
				if(local[0] <= 25) {
					local[0] = 850;
				}else {
					local[0] -= 25;
				}
				
			}else if(direction.equals("U")) {
				
				if(local[1] <= 75) {
					local[1] = 650;
				}else {
					local[1] -= 25;
				}
				
			}else if(direction.equals("D")) {
				if(local[1] >= 650) {
					local[1] = 75;
				}else {
					local[1] += 25;
				}
				
			}			
						
			//更改头的位置
			localList.set(0, local);		
		}	
	}
	
	//判断下一步是否为蛇身
	private boolean isbody() {
		// TODO 自动生成的方法存根
		//记录头位置
		int x = localList.get(0)[0];
		int y = localList.get(0)[1];
 
		//判断当前方向,并进行模拟移动,判断是否与边界重合
		if(direction.equals("R")) {
			x += 25;
		}else if(direction.equals("L")) {
			x -= 25;
		}else if(direction.equals("U")) {
			y -= 25;
		}else if(direction.equals("D")) {
			y += 25;
		}			
		
		for (int i = 1; i < localList.size(); i++) {
			if(localList.get(i)[0] == x && localList.get(i)[1] == y) {
				return true;
			}
		}
		return false;
 
	}
	
//	//判断下一步是否为边界
//	private boolean isborder() {
//		// TODO 自动生成的方法存根
//		//记录头位置
//		// TODO 自动生成的方法存根
//		//记录头位置
//		int x = localList.get(0)[0];
//		int y = localList.get(0)[1];
//
//		//判断当前方向,并进行模拟移动,判断是否与边界重合
//		if(direction.equals("R")) {
//			x += 25;
//		}else if(direction.equals("L")) {
//			x -= 25;
//		}else if(direction.equals("U")) {
//			y -= 25;
//		}else if(direction.equals("D")) {
//			y += 25;
//		}	
//				
//		if(x < 25 || x > (33 * 25 + 25)) {
//			return true;//当x坐标超出边界,则返回true
//		}
//		if(y < 105 || y > (23 * 25 + 105)) {
//			return true;//当y坐标超出边界,则返回true
//		}
//		return false;//蛇头移动后未超出边界,返回false
//		
//	}
 
	/**
	 * Create the frame.
	 */
	public SnakeJPanel(int speed) {
		
		this.speed = speed; //初始化速度
		
		//初始化游戏面板的基本信息
		this.setSize(900, 700);
		this.setLocation(0, 30);
		this.setFocusable(true);
		
		init();//初始化界面
		drawImage();//绘制图片
		moveByKey();//给界面添加一个键盘监听
				
	}
 
	/*
	 * 键盘监听
	 * 通过键盘输入上下左右来控制当前蛇头移动的方向
	 * 先判断当前蛇头方向,再来改变引导方向
	 * 当进行绘制时再修改蛇的方向
	 * 保证不会因为在短时间内快速变换方向导致蛇头逆向转向
	 */
	private void moveByKey() {
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				int key = e.getKeyCode();
				//边界值判断
				switch(key) {
				case 65:
				case 37:{//向左走
					if(!direction.equals("R")) {
						direction2 = "L";
						
					}
					break;
				}				
				case 87:
				case 38:{//向上走
					if(!direction.equals("D")) {
						direction2 = "U";
					}				
					break;
				}				
				case 68:
				case 39:{//向右走
					if(!direction.equals("L")) {
						direction2 = "R";
					}
					break;
				}
				case 83:
				case 40:{//向下走
					if(!direction.equals("U")) {
						direction2 = "D";
					}					
					break;
				}
				case KeyEvent.VK_SPACE:{//如果当前键盘输入为空格
					start = !start;//调整游戏状态
					System.out.println("暂停/开始");
					repaint();//重绘
				}
				}
				
				//任意键开始
				if(!start && key != KeyEvent.VK_SPACE) {//如果当前状态为暂停状态,且键盘输入不是空格
					start = true;
					repaint();//重绘
					
				}				
			}
		});
	}
 
	/**
	 * 初始化游戏基本信息
	 */
	private void init() {
		start = false;
 
		exist = true;
 
		direction2 = "U";
 
		flag = true;
 
		localList = new ArrayList<int[]>();
 
		localList.add(0,new int[] {75,125});//蛇头
		localList.add(1,new int[] {75,150});//蛇身1
		localList.add(2,new int[] {75,175});//蛇身2
 
		//创建第一个食物的位置
		//通过循环保证当前生成的食物不在身体所在的坐标上
		boolean isProduce = true;
		while(isProduce) {//循环生成食物坐标
			isProduce = false;//结束本次循环
			x = rand.nextInt(33) * 25 + 25;		
			y = rand.nextInt(23) * 25 + 75;			
			for (int[] arr:localList) {//循环遍历蛇头及蛇身的坐标
				if(x == arr[0] && y == arr[1]) {//如果食物坐标和蛇的某一节坐标重合
					isProduce = true;//跳转循环状态,继续下一次食物生成
					break;	
				}
			}
			//蛇身遍历完成,没有重合坐标,结束食物坐标生成
							
		}
 
		time = new Timer(speed, this);
		setLayout(null);
 
		score = 0;
 
		num = 0;
		
		foodType = 0;
		
//		repaint();
		
	}
 
 
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CJds_snakeView类 Struct list { int x; int y; }; 点结构,x表示横坐标,y表示纵坐标。 成员变量: int start;start=1开始游戏,start=0停止游戏。 int difficulty;表示游戏难度,等于10表示容易,等于6表示普通,等于3表示困难,等于2表示特困。 int last_aspect;表示蛇之前前进的方向,用于判断防止蛇逆行的。 int can_new;表示是否添加新食物。等于1表示产生新的食物,等于0表示产生之后不不要再产生食物。 int count;表示蛇的节数; CRect rct;表示矩形方格; list a[100];保存蛇的长度; list b;用来保存蛇头的坐标位置; int aspect;表示蛇前进的方向 等于0表示蛇向右前进; 等于1表示蛇向下前进; 等于2表示蛇向左前进; 等于3表示蛇向上前进; int xx;表示食物的x坐标; int yy;表示食物的y坐标; 成员函数: void Init();初始化蛇的节数,并确定了节数的坐标位置。首先初始化蛇的前进方向aspect=0是向右前进的,last_aspect=0用来保存蛇当前前进的方向。并且初始化蛇的节数为4节,并指明了它们的坐标位置。can_new=1表示产生一个新的食物。 void aliveordie();判断蛇是死还是活着。有两种情况,一种是蛇自己撞到自己,表示死了,start=0从新开始游戏,另一种是超出了界面(20,20,420,420)撞到了墙start=0也从新开始游戏。 double random(double start,double end);在start和end坐标之间产生随即数; 消息处理事件: (1)void onTimer(UINT nIDEvent);在OnCreate()创建计时器SetTimer(),来触发OnTimer事件,所以要首先销毁时间计时器,然后调用aliveordie()函数判断蛇的生死情况,CString str_count; str_count.Format("分数:%d",count-4)显示蛇的节数,TextOut()指出坐标输出文本,创建设备上下文,和创建位图。然后把位图选择到设备上下文上,填充颜色为白色。 在位图上绘制两个矩形线框: Rectangle(CRect(10,10,440,440)); Rectangle(CRect(20,20,430,430)); 显示位图(BitBlt(0,0,1000,1000,&MenDC,0,0,SRCCOPY)); 判断如果游戏开始(start==1),b.x=a[0].x用b.x来保存蛇头的横坐标;b.y=a[0].y用b.y来保存蛇头的纵坐标。如果aspect==0表示蛇向右前进,aspect=1表示蛇向下前进,aspect==2表示蛇向左前进,aspect==3表示蛇向上前进,a[1].x=b.x;a[1].y=b.y;把蛇头的坐标付给了a[1],说明蛇头改变了前进的方向。绘制蛇头矩形方格,并且设置蛇头的颜色为红色,蛇身是三个黄色的矩形方格。if (a[0].x==xx && a[0].y==yy)判断蛇头的位置与食物的关系,现在的情况说明蛇吃了食物,蛇的节数加一,各个节数的坐标向前进一位。调用random()函数产生随即的食物,然后判断食物随即产生的位置与蛇的位置,如果产生的食物在蛇身体上,要从新调用random()函数随即再产生食物。产生的食物颜色为绿色。int m_timer=SetTimer(1,difficulty*30,NULL);计时间隔,计时间隔的快慢是根据难易程度的不而确定的。销毁位图、销毁设备上下文。 (2)OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);判断蛇当前前进的方向,当aspect返回0,表示蛇前进的方向是向右,当aspect返回1,表示蛇前进的方向是下,当aspect返回2,表示蛇前进的方向是向左,当aspect返回3,表示蛇前进的方向是向上。 (3)点击菜单按钮调用以下函数: OnDifficultyEasy();OnDifficultyHard();OnDifficultyNormal();OnDifficultyVeryhard();OnButtonStart();

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值