贪吃蛇小游戏(Java)

申明 非原创

今天蛮开心的,之前学Java都是毫无路线的那种。就想着做个小游戏感受一下。就去b站搜到了狂神说java的视频,就照着视频一步一步做下来了。

侵删

游戏画面
在这里插入图片描述

下面是代码目录,分了三个类,还有一个存数据的第三方。
在这里插入图片描述
首先是StartGames,实现静态的游戏开始界面

package snake;




import javax.swing.JFrame;

public class StartGames {
   public static void main(String[] args){
	JFrame frame = new JFrame("李臣楠  贪吃蛇小游戏");
	frame.setBounds(10, 10, 900, 720);
	frame.setResizable(false);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
	frame.add(new GamePanel());
	
	frame.setVisible(true);
   }
   
   
   
}

然后是获取图片的一个类

package snake;

import java.net.URL;

import javax.swing.ImageIcon;



public class Date {
     public static URL headreURL = Date.class.getResource("/statics/header1.png");
     public static ImageIcon header = new ImageIcon(headreURL);
     
     public static URL upURL = Date.class.getResource("/statics/up.png");
     public static URL downURL = Date.class.getResource("/statics/down.png");
     public static URL LeftURL = Date.class.getResource("/statics/left.png");
     public static URL rightURL = Date.class.getResource("/statics/right.png");
     public static ImageIcon up = new ImageIcon(upURL);
     public static ImageIcon down = new ImageIcon(downURL);
     public static ImageIcon Left= new ImageIcon(LeftURL);
     public static ImageIcon right = new ImageIcon(rightURL);
     
     public static URL bodyURL = Date.class.getResource("/statics/body.png");
     public static ImageIcon body = new ImageIcon(bodyURL);
     
     public static URL foodURL = Date.class.getResource("/statics/food.png");
     public static ImageIcon food = new ImageIcon(foodURL);
     
     public static URL backgroundURL = Date.class.getResource("/statics/background.jpg");
     public static ImageIcon background = new ImageIcon(backgroundURL);
}

最后是实现功能的面板

package snake;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;
public class GamePanel extends JPanel implements KeyListener, ActionListener {
	
	int lenth;
	int[] snakeX = new int[600];
	int[] snakeY = new int[500];
	String fx;
	
	
	
	boolean isStart = false;
	
	Timer  timer = new Timer(100, this);
	
	int foodx;
	int foody;
	Random random = new Random();
	
	boolean isFail = false;
	
	int score;
	
	public GamePanel(){
		init();
		this.setFocusable(true);
		this.addKeyListener(this);
		timer.start();
}
	
	public void init() {
		lenth=3;
		snakeX[0]=100;snakeY[0]=100;
		snakeX[1]=75;snakeY[1]=100;
		snakeX[2]=50;snakeY[2]=100;
		fx="R";
		
		foodx = 25 + 25*random.nextInt(34);
		foody = 75 + 25*random.nextInt(24);
		score=0;
		
	}
	
	
	
	
	@Override
	protected void paintComponent(Graphics g) {
		// TODO Auto-generated method stub
		super.paintComponent(g);		
		this.setBackground( Color.white);
		Date.header.paintIcon(this, g, 25, 11);
		g.fillRect(25, 75, 850, 600);
		Date.background.paintIcon(this, g, 0, 75);
		
	    if(fx.equals("R")){
		Date.right.paintIcon(this, g, snakeX[0], snakeY[0]);
		}else if(fx.equals("L")){
		Date.Left.paintIcon(this, g, snakeX[0], snakeY[0]);
		}else if(fx.equals("U")){
			Date.up.paintIcon(this, g, snakeX[0], snakeY[0]);
		}else if(fx.equals("D")){
			Date.down.paintIcon(this, g, snakeX[0], snakeY[0]);
		}
				
		for(int i=1;i<lenth;i++){
			Date.body.paintIcon(this, g, snakeX[i], snakeY[i]);
		}
		
		g.setColor(Color.black);
		g.setFont(new Font("微软雅黑", Font.BOLD, 18));
		g.drawString("长度:"+lenth,800,35);
		g.drawString("分数:"+score,800,55);
		
		Date.food.paintIcon(this, g, foodx, foody);
		
		if(isStart==false){
			g.setColor(Color.white);
			g.setFont(new Font("微软雅黑",Font.BOLD,40));
			g.drawString("按下空格开始游戏", 300, 300);
		}
		
		if(isFail){
			g.setColor(Color.RED);
			g.setFont(new Font("微软雅黑",Font.BOLD,40));
			g.drawString("游戏失败,按下空格重新开始", 200, 300);
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		int KeyCode = e.getKeyCode();
		if(KeyCode==KeyEvent.VK_SPACE){
			if(isFail){
				isFail = false;
				init();
		}else{
			isStart= !isStart;
		}
			repaint();
		}
	
		if(KeyCode==KeyEvent.VK_LEFT){
			fx="L";
		}else if(KeyCode==KeyEvent.VK_RIGHT){
			fx="R";
		}else if(KeyCode==KeyEvent.VK_UP){
			fx="U";
		}else if(KeyCode==KeyEvent.VK_DOWN){
			fx="D";
		}
		
			
	}

	
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(isStart&&isFail==false){
			for(int i= lenth-1;i>0;i--){
			snakeX[i]=snakeX[i-1];
			snakeY[i]=snakeY[i-1];
		}
		if(fx.equals("R")){
			snakeX[0]=snakeX[0]+25;
			if(snakeX[0]>850){ snakeX[0]=25;}
			}else if(fx.equals("L")){
				snakeX[0]=snakeX[0]-25;
				if(snakeX[0]<25){ snakeX[0]=850;}
			}else if(fx.equals("U")){
			    snakeY[0]=snakeY[0]-25;
			    if(snakeY[0]<75){ snakeY[0]=650;}
	        }else if(fx.equals("D")){
		        snakeY[0]=snakeY[0]+25;
		        if(snakeY[0]>650){ snakeY[0]=75;}
     }	
		
		if(snakeX[0]==foodx&&snakeY[0]==foody){
			lenth++;
			snakeX[lenth-1]=foodx-1;
			snakeY[lenth-1]=foody-1;
			score= score+10;
			foodx = 25 + 25*random.nextInt(34);
			foody = 75 + 25*random.nextInt(24);
		}
		
		
		for(int i=0;i<lenth;i++){
			if(foodx==snakeX[i]&&foody==snakeY[i]){
				foodx=25+25*random.nextInt(34);
				foody=75+25*random.nextInt(24);
					
				}
			
			}
		
		for(int i=1;i<lenth;i++){
			if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
				isFail = true;
			}
		}
		repaint();
	}
	timer.start();
    
	
 }
}	

因为刚学没多久,对于游戏是如何实现的我也没有很深的理解,只对狂神的代码做了点非常小的改动,强力推荐狂神的视频,B站搜狂神说java就可以。有不懂的可以留言,尽量回答。

可以运行! (以下代码只是其中的一个类) 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); } } }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值