贪吃蛇和俄罗斯方块

俄罗斯方块

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
 
public class Tetris extends JFrame implements KeyListener {
    public static void main(String[] args) throws Exception {
     //   SwingUtilities.invokeLater(start::initWindow);
        Tetris t=new Tetris();
        t.game_begin();
    }
    //游戏的行数为26,列数为12
    private static final int game_x=26;
    private static final int game_y=12;
 
    //文本域数组
    JTextArea[][] text;
    //二维数组
    int [][] data;
    //显示游戏状态的标签
    JLabel Label1;
    //显示游戏分数的标签
    JLabel Label;
    //提示暂停键的标签
    JLabel label;
    //用于判断游戏是否结束
    boolean isrunning;
    //用于存储所有方块的数组
    int [] allRect;
    //用于存储当前方块的变量
    int rect;
    //线程的休眠时间
    int time=1000;
    //表示方块坐标
    int x,y;
    //该变量用于计算得分
    int score=0;
    //定义一个标志变量,判断游戏是否暂停
    boolean game_pause=false;
    //定义一个变量,用于记录按下暂停的次数
    int pause=0;
 
    public void initWindow(){
        //设置窗口大小
        this.setSize(600,850);
        //设置窗口是否可见
        this.setVisible(true);
        //设置窗口居中
        this.setLocationRelativeTo(null);
        //设置释放窗体
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗体大小不可变
        this.setResizable(false);
        //设置标题
        this.setTitle("俄罗斯方块");
 
    }
    public Tetris(){
        text=new JTextArea[game_x][game_y];
        data=new int[game_x][game_y];
        //初始化游戏状态的标签
        Label1 =new JLabel("游戏状态:正在游戏中!");
        //初始化游戏分数的标签
        Label=new JLabel("游戏得分:0");
        //初始化提示标签
        label=new JLabel("按下s键,即可暂停游戏!");
        initGamePanel();
        initExplainPanel();
        initWindow();
        //初始化游戏开始的标志
        isrunning=true;
        //初始化存放方块的数组
        allRect =new int[]{0x00cc,0x8888,0x000f,0x888f,0xf888,0xf111,0x111f,0x0eee,0xffff,0x0008
                ,0x0888,0x000e,0x0088,0x000c,0x08c8,0x00e4,0x04c4,0x004e,0x08c4,0x006c,0x04c8,0x00c6};
    }
    //初始化游戏界面
    public void initGamePanel(){
        JPanel game_main=new JPanel();
        game_main.setLayout(new GridLayout(game_x,game_y,1,1));
 
        for (int i = 0; i < text.length; i++) {
            for (int j = 0; j < text[i].length; j++) {
                //设置文本域的行列数
                text[i][j]=new JTextArea(game_x,game_y);
                //设置文本域的背景颜色
                text[i][j].setBackground(Color.WHITE);//白色
                //添加键盘监听事件
                text[i][j].addKeyListener(this);
                //初始化游戏边界
                if(j==0 || j==text[i].length-1 || i==text.length-1){
                    text[i][j].setBackground(Color.BLACK);//设置为黑色,这里看个人喜好设置
                    data[i][j]=1;//表示这里有方块
                }
                //设置文本域不可编辑
                text[i][j].setEditable(false);
                //文本区域添加到主面板上去
                game_main.add(text[i][j]);
            }
        }
        //将主面板添加到窗口中
        this.setLayout(new BorderLayout());
        this.add(game_main,BorderLayout.CENTER);//把游戏区域添加到窗口的中间
    }
    //初始化游戏的说明界面
    public void initExplainPanel(){
        //创建游戏的左说明面板
        JPanel explain_left=new JPanel();
        //创建游戏的右说明面板
        JPanel explain_right=new JPanel();
        //初始化格式布局
        explain_left.setLayout(new GridLayout(4,1));
        explain_right.setLayout(new GridLayout(3,1));
        //在左说明面板,添加说明文字
        explain_left.add(new JLabel("按空格键,方块变形"));
        explain_left.add(new JLabel("按左箭头,方块左移"));
        explain_left.add(new JLabel("按右箭头,方块右移"));
        explain_left.add(new JLabel("按下箭头,方块下落"));
        //设置游戏标签的内容为红色字体
        Label1.setForeground(Color.RED);
        //将游戏状态和得分、提示添加到右面板上
        explain_right.add(label);
        explain_right.add(Label);
        explain_right.add(Label1);
        //将左说明面板添加到窗口左侧
        this.add(explain_left,BorderLayout.WEST);
        //将右说明面板添加到窗口右侧
        this.add(explain_right,BorderLayout.EAST);
 
    }
    //开始游戏的方法
    public void game_begin() throws Exception {
        while (true){
            //判断游戏是否结束
            if(!isrunning){
                break;
            }
            //进行游戏
            game_run();
        }
        //在标签位置显示游戏结束
        Label1.setText("游戏状态:游戏结束!");
    }
    //随机生成下落方块形状的方法
    public void ranRect(){
        Random random=new Random();
 
      rect=allRect[random.nextInt(22)];
    }
    //游戏运行的方法
    public void game_run() throws Exception {
        ranRect();
        //方块下落位置
        x=0;
        y=5;
        for (int i = 0; i < game_x; i++) {
            Thread.sleep(time);
            if (game_pause) {
                i--;
            } else {
            //判断方块是否可以下落
            if (!canFall(x, y)) {
                //将data变成1,表示有方块占用
                changData(x, y);
                //循环遍历4层,看是否有行可以消除
                for (int j = x; j < x + 4; j++) {
                    int sum = 0;
                    for (int k = 1; k <= (game_y - 2); k++) {
                        if (data[j][k] == 1) {
                            sum++;
                        }
                    }
                    //判断是否有一行可以被消除
                    if (sum == (game_y - 2)) {
                        //消除J这一行
                        removeRow(j);
                    }
                }
                //判断游戏是否失败
                for (int j = 1; j < (game_y - 2); j++) {
                    if (data[3][j] == 1) {
                        isrunning = false;
                        break;
                    }
                }
                break;//方块无法下落,我们应该重新生成一个方块,并重新遍历26层
            } else {
                //方块可以下落,层数加一
                x++;
                //方块下落一格
                fall(x, y);
            }
        }
        }
    }
    //判断方块是否可以继续下落的方法
    public boolean canFall(int m,int n){
        //定义一个变量
        int temp=0x8000;
        //遍历4*4方格
        for (int i = 0; i <4 ; i++) {
            for (int j = 0; j < 4; j++) {
                if((temp & rect)!=0){
                    //判断该位置的下一行是否有方块
                    if(data[m+1][n]==1){
                        return false;
                    }
                }
                n++;
                temp >>=1;//右移一位
            }
            m++;
            n=n-4;//让n回归首列
        }
        //循环结束,可以下落
        return true;
    }
    //改变不可下降的方块对应的区域的值的方法
    public void changData(int m,int n){
        //定义一个变量
        int temp=0x8000;
        //遍历整个4*4的方块
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if((temp & rect)!=0){
                    data[m][n]=1;
                }
                n++;
                temp >>=1;//右移一位
            }
            m++;
            n=n-4;
        }
    }
    //移除某一行的所有方块,并让上面的方块掉落的方法
    public void removeRow(int row){
        int temp=100;
        for (int i = row; i >=1 ; i--) {
            for (int j = 1; j <=(game_y-2) ; j++) {
                //进行覆盖
                data[i][j]=data[i-1][j];
                
            }
        }
        //刷新游戏区域
        reflesh(row);
        //方块加速
        if(time>temp){
            time-=temp;
        }
        //每消除一行,得分加100
        score+=temp;
        //显示变化后的分数
        Label.setText("游戏得分:"+score);
    }
    //刷新移除某一行后的游戏界面的方法
    public void reflesh(int row){
        //遍历row上面的游戏区域
        for (int i = row; i >=1 ; i--) {
            for (int j = 1; j <=(game_y-2) ; j++) {
                if(data[i][j]==1){//如果是方块,将方块设置为蓝色
                    text[i][j].setBackground(Color.BLUE);
                }else{//如果不是方块,说明是游戏的背景区域
                    text[i][j].setBackground(Color.WHITE);//设置为白色
                }
            }
        }
    }
    //方块向下掉落一层的方法
    public void fall(int m,int n){
        if(m>0){
            //清除上一层方块
            clear(m-1,n);
        }
        //重新绘制方块
        draw(m,n);
    }
    //清除方块掉落后,上一层有颜色的地方的方法
    public void clear(int m,int n){
        //定义一个变量
        int temp=0x8000;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if ((temp & rect) != 0) {
                    text[m][n].setBackground(Color.WHITE);//将其设置成背景颜色,相当于消除
                }
                n++;
                temp >>=1;//右移一位
            }
            m++;
            n=n-4;
        }
    }
    //重新绘制掉落后的方块的方法
    public void draw(int m,int n){
        //定义一个变量
        int temp=0x8000;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if((temp & rect)!=0){
                    text[m][n].setBackground(Color.BLUE);//设置成之前的方块颜色
                }
                n++;
                temp >>=1;//右移一位
            }
            m++;
            n=n-4;
        }
    }
 
    @Override
    public void keyTyped(KeyEvent e) {
        //控制游戏暂停
        if(e.getKeyChar()=='s'){//如果按下s,则游戏暂停
            //判断游戏是否结束
            if(!isrunning){
                return;
            }
            pause++;
            //判断是按下一次,暂停游戏
            if(pause==1){
                game_pause=true;
                Label1.setText("游戏状态:暂停中!");
            }
            //判断是按下两次,继续游戏
            if(pause==2){
                game_pause=false;
                pause=0;//重置暂停次数
                Label1.setText("游戏状态:正在游戏中!");
            }
        }
 
        //控制方块进行变形
        if(e.getKeyChar()==KeyEvent.VK_SPACE){
            //判断游戏是否结束
            if(!isrunning){
                return;
            }
            //判断游戏是否暂停
            if(game_pause){
                return;
            }
            //定义变量,存储目前方块的索引
            int old;
            for (old = 0; old < allRect.length; old++) {
                //判断是否是当前方块
                if(rect==allRect[old]){
                    break;
                }
            }
            //定义变量,存储变形后的方块
            int next;
            //判断是完整方块
            if(old==0||old==7||old==8||old==9){
                return;
            }
            //清除当前方块
            clear(x,y);
            if(old==1||old==2){
                next=allRect[old==1?2:1];
                //如果可以变形
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old>=3&&old<=6){
                next=allRect[old+1>6?3:old+1];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old==10||old==11){
                next=allRect[old==10?11:10];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old==12||old==13){
                next=allRect[old==12?13:12];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old>=14&&old<=17){
                next=allRect[old+1>17?14:old+1];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old==18||old==19){
                next=allRect[old==18?19:18];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            if(old==20||old==21){
                next=allRect[old==20?21:20];
                if(canTurn(next,x,y)){
                    rect=next;
                }
            }
            //重新绘制变形后的方块
            draw(x,y);
        }
    }
    public boolean canTurn(int a,int m,int n){
        //创建变量
        int temp=0x8000;
        //遍历整个方块
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if ((temp & rect) != 0) {
                    if(data[m][n]==1){
                        return false;
                    }
                }
                n++;
                temp >>=1;
            }
            m++;
            n=n-4;
        }
        //可以变形
        return true;
    }
 
    @Override
    public void keyPressed(KeyEvent e) {
        //方块进行左移
        if(e.getKeyCode()==37){//左箭头对应的数值为37
            //判断游戏是否结束
            if(!isrunning){
                return;
            }
            //判断游戏是否暂停
            if(game_pause){
                return;
            }
            //方块是否碰到左墙壁
            if(y<=1){
                return;
            }
            //方块的左边是否有方块
            int temp=0x8000;
            for (int i = x; i <x+4 ; i++) {
                for (int j = y; j <y+4 ; j++) {
                    if((temp & rect)!=0){
                        if(data[i][j-1]==1){
                            return;
                        }
                    }
                    temp >>=1;
                }
            }
            //清除目前方块
            clear(x,y);
            y--;//向左移动
            draw(x,y);//重新绘制出向左移动后的方块
        }
        //方块进行右移
        if(e.getKeyCode()==39) {//右箭头对应的数值为39
            //判断游戏是否结束
            if(!isrunning){
                return;
            }
            //判断游戏是否暂停
            if(game_pause){
                return;
            }
            int temp=0x8000;
            int m=x;
            int n=y;
            //存储最右边的坐标值
            int num=1;
            for (int i = 0; i < 4; i++) {
                for (int j = 0; j < 4; j++) {
                    if ((temp & rect) != 0) {
                        if(n>num){
                            num=n;
                        }
                    }
                    n++;
                    temp >>=1;
                }
                m++;
                n=n-4;
            }
            //判断是否碰到右墙壁
            if(num>=(game_y-2)){
                return;
            }
            //判断方块右移途中是否碰到其他方块
            temp=0x8000;
            for (int i = x; i <x+4 ; i++) {
                for (int j = y; j < y + 4; j++) {
                    if ((temp & rect) != 0) {
                        if(data[i][j+1]==1){
                            return;
                        }
                    }
                    temp>>=1;
                }
            }
            //清除当前方块
            clear(x,y);
            y++;//右移一位
            draw(x,y);//重新绘制出向右移动后的方块
        }
        //方块进行下落
        if(e.getKeyCode()==40) {//下箭头对应的数值为40
            //判断游戏是否结束
            if (!isrunning) {
                return;
            }
            //判断游戏是否暂停
            if(game_pause){
                return;
            }
            //判断方块是否可以下落
            if(!canFall(x,y)){
                return;
            }
            //清除当前方块
            clear(x,y);
            //改变方块坐标
            x++;
            draw(x,y);//重新绘制出向右移动后的方块
        }
    }
 
    @Override
    public void keyReleased(KeyEvent e) {
 
    }
}

运行结果:

贪吃蛇

package GreedySnake;
 
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/GreedySnake/up.png");
		down = new ImageIcon("src/GreedySnake/down.png");
		right = new ImageIcon("src/GreedySnake/right.png");
		left = new ImageIcon("src/GreedySnake/left.png");
		body = new ImageIcon("src/GreedySnake/body.png");
		food = new ImageIcon("src/GreedySnake/food.png");
		title = new ImageIcon("src/GreedySnake/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 GreedySnake;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
 
public class SnakeStart {
	public static void main(String[] args) {
		
		int speed = 0;
		String showInputDialog = null;//初始化时间
		//得到速度
		while(true) {
			showInputDialog = JOptionPane.showInputDialog("蛇移动速度(1 - 5)","3");
			
			if(showInputDialog == null) {
				showInputDialog = "3";//默认速度
				break;
			}
			if(showInputDialog.length() > 1) {
				continue;
			}
			char[] a = showInputDialog.toCharArray();
			if(a[0] >= '1' && a[0] <= '5') {
				break;
			}
		}
			
		speed = Integer.parseInt(showInputDialog) * 50;
		
		
		SnakeJPanel snakeJPanel = new SnakeJPanel(speed);
		
		//创建一个JFrame窗口,将游戏面板添加进行窗口中
		JFrame jFrame = new JFrame();
		//设置窗口的某些属性
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setSize(920, 750);
	    jFrame.add(snakeJPanel);
	    jFrame.setLocationRelativeTo(null);
	    jFrame.setVisible(true);
	}
 
}

运行结果:

猜你喜欢

转载自blog.csdn.net/nmy15570188135/article/details/134409769