Use java to implement a simple snake game
GUI programming to implement the Snake game
(Recommended tutorial: java course)
1. Write the main method Implement startup class
2. Prepare material pictures and write data classes
3. Main part of the code: implement game initialization, keyboard and event monitoring and other functions on the panel
4. Code running renderings
5. GitHub source code link
1. Write the main method to implement the startup class
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. Prepare material pictures and write data classes
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. The main part of the code: implement game initialization, keyboard and event monitoring and other functions on the 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. Code running renderings
Initialization interface:
The above is the detailed content of Use java to implement a simple snake game. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
