java贪吃蛇代码_java贪吃蛇游戏实现代码

GUI编程实现贪吃蛇小游戏,供大家参考,具体内容如下

1、编写主方法实现启动类

2、准备好素材图片,编写数据类

3、代码主体部分:在panel面板上实现游戏初始化,键盘和事件的监听等功能

4、代码运行效果图

5、GitHub源码链接

1、编写主方法实现启动类

import javax.swing.*;

//主启动类

public class StartGame {

public static void main(String[] args) {

JFrame jFrame = new JFrame("贪吃蛇小游戏");

jFrame.setBounds(10,10,900,720);

jFrame.setResizable(false); //设置窗口大小不可变

jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//面板

jFrame.add(new GamePanel());

jFrame.setVisible(true);

}

}

2、准备好素材图片,编写数据类

import javax.swing.*;

import java.net.URL;

public class Data {

//头部图片

public static URL headerURL = Data.class.getResource("statics/header.png");

public static ImageIcon header = new ImageIcon(headerURL);

//头部上下左右

public static URL upURL = Data.class.getResource("statics/up.png");

public static URL downURL = Data.class.getResource("statics/down.png");

public static URL leftURL = Data.class.getResource("statics/left.png");

public static URL rightURL = Data.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 = Data.class.getResource("statics/body.png");

public static ImageIcon body = new ImageIcon(bodyURL);

//食物

public static URL foodURL = Data.class.getResource("statics/food.png");

public static ImageIcon food = new ImageIcon(foodURL);

}

3、代码主体部分:在panel面板上实现游戏初始化,键盘和事件的监听等功能

package com.abc.snake;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.Random;

//游戏的面板

public class GamePanel extends JPanel implements KeyListener, ActionListener {

//定义蛇的数据结构

int length; //蛇的长度

int[] snakeX = new int[600]; //蛇的x坐标 25*25

int[] snakeY = new int[500]; //蛇的y坐标 25*25

String fx;

//食物

int foodx;

int foody;

Random random = new Random();

int score; //游戏分数

//游戏当前的状态

boolean isStart = false;

boolean isFail = false;

//定时器

Timer timer = new Timer(100,this);//100毫秒刷新一次

//构造方法

public GamePanel() {

init();//初始化

this.setFocusable(true); //获得焦点事件

this.addKeyListener(this); //获得键盘监听事件

timer.start(); //游戏一开始 定时器就启动

}

//初始化方法

public void init(){

length = 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) {

super.paintComponent(g);//清屏

this.setBackground(Color.white);//设置面板背景色

Data.header.paintIcon(this,g,25,11);//头部

g.fillRect(25,75,850,600);//默认的黑色游戏区域

//绘制小蛇

if (fx.equals("R")){

Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向右

}else if (fx.equals("L")){

Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向左

}else if (fx.equals("U")){

Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向上

}else if (fx.equals("D")){

Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向下

}

for (int i = 1; i < length; i++) {

Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);

}

//食物

Data.food.paintIcon(this,g,foodx,foody);

//积分

g.setColor(Color.white);

g.setFont(new Font("微软雅黑",Font.BOLD,18));

g.drawString("长度 "+length,750,35);

g.drawString("分数 "+score,750,50);

//游戏状态

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("游戏失败,按下空格重新开始",300,300);

}

}

//键盘监听事件

@Override

public void keyPressed(KeyEvent e) {

int keyCode = e.getKeyCode(); //获取按键

if (keyCode == KeyEvent.VK_SPACE){

if (isFail){

//重新开始

isFail=false;

init();

}else {

isStart =! isStart;

}

repaint();

}

//键盘控制小蛇移动

if (keyCode==KeyEvent.VK_UP){

fx="U";

}else if (keyCode==KeyEvent.VK_DOWN){

fx="D";

}else if (keyCode==KeyEvent.VK_LEFT){

fx="L";

}else if (keyCode==KeyEvent.VK_RIGHT){

fx="R";

}

}

//事件监听

@Override

public void actionPerformed(ActionEvent e) {

if (isStart && isFail ==false){//如果游戏是开始状态,就让小蛇动起来

//移动

for (int i = length-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){

length++;

score = score + 10;

//再次随机食物

foodx = 25 + 25*random.nextInt(34);

foody = 75 + 25*random.nextInt(24);

}

//失败判定,撞到自己

for (int i = 1; i < length; i++) {

if (snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){

isFail=true;

}

}

repaint();

}

timer.start();

}

@Override

public void keyTyped(KeyEvent e) {

}

@Override

public void keyReleased(KeyEvent e) {

}

}

4、代码运行效果图

初始化界面:

fd9c565e58b3c800313c813c03eed1da.png

游戏中界面:

946c0e58c7aff0b3585a91940bc99d04.png

游戏结束界面:

a3dc27e12bfce3979e0331ccb5e0a1d3.png

更多有趣的经典小游戏实现专题,分享给大家:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里给出一个简单的 Java 贪吃蛇游戏代码,仅供参考: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; 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 int DELAY = 140; private final int x[] = new int[ALL_DOTS]; private final 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() { initGame(); initUI(); } private void initUI() { addKeyListener(new TAdapter()); setBackground(Color.black); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setFocusable(true); loadImages(); timer = new Timer(DELAY, this); timer.start(); pack(); setLocationRelativeTo(null); setTitle("Snake Game"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private void loadImages() { ImageIcon iid = new ImageIcon(getClass().getResource("dot.png")); ball = iid.getImage(); ImageIcon iia = new ImageIcon(getClass().getResource("apple.png")); apple = iia.getImage(); ImageIcon iih = new ImageIcon(getClass().getResource("head.png")); head = iih.getImage(); } private void initGame() { dots = 3; for (int z = 0; z < dots; z++) { x[z] = 50 - z * DOT_SIZE; y[z] = 50; } locateApple(); timer = new Timer(DELAY, this); timer.start(); } private 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)); } private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } private void move() { for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[0] -= DOT_SIZE; } if (rightDirection) { x[0] += DOT_SIZE; } if (upDirection) { y[0] -= DOT_SIZE; } if (downDirection) { y[0] += DOT_SIZE; } } private void checkCollision() { for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if (!inGame) { timer.stop(); } } private void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = 0; z < dots; z++) { if (z == 0) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } private 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); } @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { @Override 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; } } } public static void main(String[] args) { new SnakeGame(); } } ``` 希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值