贪吃蛇小游戏(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就可以。有不懂的可以留言,尽量回答。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
很高兴回答你的问题。以下是一个简单的贪吃蛇小游戏JAVA代码实现: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JPanel implements ActionListener { private final int WIDTH = 300; private final int HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private final int DELAY = 140; private int x[] = new int[ALL_DOTS]; private int y[] = new int[ALL_DOTS]; private int dots; private int apple_x; private int apple_y; private boolean leftDirection = false; private boolean rightDirection = true; private boolean upDirection = false; private boolean downDirection = false; private boolean inGame = true; private Timer timer; private Image ball; private Image apple; private Image head; public SnakeGame() { addKeyListener(new TAdapter()); setBackground(Color.black); setPreferredSize(new Dimension(WIDTH, HEIGHT)); ImageIcon iid = new ImageIcon(this.getClass().getResource("dot.png")); ball = iid.getImage(); ImageIcon iia = new ImageIcon(this.getClass().getResource("apple.png")); apple = iia.getImage(); ImageIcon iih = new ImageIcon(this.getClass().getResource("head.png")); head = iih.getImage(); initGame(); } public void initGame() { dots = 3; for (int z = ; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } locateApple(); timer = new Timer(DELAY, this); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } public void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = ; z < dots; z++) { if (z == ) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } public void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2); } public void checkApple() { if ((x[] == apple_x) && (y[] == apple_y)) { dots++; locateApple(); } } public void move() { for (int z = dots; z > ; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[] -= DOT_SIZE; } if (rightDirection) { x[] += DOT_SIZE; } if (upDirection) { y[] -= DOT_SIZE; } if (downDirection) { y[] += DOT_SIZE; } } public void checkCollision() { for (int z = dots; z > ; z--) { if ((z > 4) && (x[] == x[z]) && (y[] == y[z])) { inGame = false; } } if (y[] >= HEIGHT) { inGame = false; } if (y[] < ) { inGame = false; } if (x[] >= WIDTH) { inGame = false; } if (x[] < ) { inGame = false; } if (!inGame) { timer.stop(); } } public void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); } public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } } } } ``` 希望这个代码能够帮助到你。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值