Two months later , I didn't go on studying Java, Today, let's take the snake game to practice !
Rules of the snake game :
1. Press the space bar ( The game is not over ) The game stops or starts ;
2. Press the space bar ( After the game ) Then the game starts again ;
3. When the head of the snake hits the body, the snake dies ( game over );
4. The snake dies when its head hits the wall ( game over );
Game interface effect :
We can see how much food our snake eats , And game scores . The following is the effect of the game :
Source code ( Comments super detailed , be careful ImageDate In class material It's a package name , There are pictures of game materials ):
package program_code; import java.awt.Color; import java.awt.Font; import
java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import
java.awt.event.KeyListener; import java.net.URL; import
java.rmi.server.SkeletonMismatchException; import java.util.Random; import
java.util.Timer; import javax.naming.InitialContext; import
javax.naming.InsufficientResourcesException; import
javax.naming.directory.DirContext; import javax.swing.ImageIcon; import
javax.swing.JFrame; import javax.swing.JPanel; import javax.xml.crypto.Data;
public class Main { public static void main(String[] args) { // Initialize Snake game interface
JFrame frame = new JFrame(" Snake games --bingongzi"); // Create a form object frame.setSize(900,
800); // Set the form size to 900x800 frame.setLocationRelativeTo(null); // Format form to center
frame.setResizable(false); // The setting form cannot be changed frame.add(new GamePanel());// Add a panel to the form
frame.setVisible(true); // Set form visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // End the application where the window is located } } //
Store pictures class ImageData { // panel logo url: Locate the address of the picture ImageIcon: according to url Get pictures //
Class<T> in public URL getResource(String name) Find a resource with the given name . private static URL
headerurl = ImageData.class.getResource("/material/header.jpg"); public static
ImageIcon header = new ImageIcon(headerurl); // Get the picture of snake head up private static URL
upurl = ImageData.class.getResource("/material/up.png"); public static
ImageIcon up = new ImageIcon(upurl); // Get a picture of the snake head to the right private static URL righturl =
ImageData.class.getResource("/material/right.png"); public static ImageIcon
right = new ImageIcon(righturl); // Get a picture of the snake head down private static URL downurl =
ImageData.class.getResource("/material/down.png"); public static ImageIcon down
= new ImageIcon(downurl); // Get a picture of the snake head to the left private static URL lefturl =
ImageData.class.getResource("/material/left.png"); public static ImageIcon left
= new ImageIcon(lefturl); // Get a picture of the snake private static URL bodyurl =
ImageData.class.getResource("/material/body.png"); public static ImageIcon body
= new ImageIcon(bodyurl); // Get pictures of food private static URL foodurl =
ImageIcon.class.getResource("/material/food.png"); public static ImageIcon food
= new ImageIcon(foodurl); } // Making game interface with panel class GamePanel extends JPanel
implements KeyListener, ActionListener { int len; // Define the length of the snake int[] snakeX =
new int[35]; // Define the abscissa of the snake x int[] snakeY = new int[28]; // Define the ordinate of the snake y String dir =
"R";// Snakehead direction :R: towards the right ,D: down ,L: towards the left ,U: Up boolean isStart = false;// Indicates whether the snake game starts or not , Initialization has not started yet
javax.swing.Timer timer = new javax.swing.Timer(200, this);// timer , The first parameter : Timed execution events
int foodX;// Define the abscissa of the food int foodY;// Define the ordinate of the food int score;// Define game score Random random =
new Random();// Creating a random number object boolean isOver = false;// Indicates whether the game has failed , end // Initialize the above variable data
public GamePanel() { Init(); this.setFocusable(true);// Get focus event
this.addKeyListener(this);// Add keyboard monitoring event timer.start(); // Time to start } // Initialize game data
public void Init() { len = 3;// On the static interface before the game starts , Plus snakeheads , There are three sections ( Snake body ) The length of the snake is 3 // Initialize snakehead position
snakeX[0] = 200; snakeY[0] = 200; // Initialize the first snake position snakeX[1] = 175; snakeY[1] =
200; // Initialize the second snake position snakeX[2] = 150; snakeY[2] = 200; dir = "R";// Initialization snake head direction right //
Randomly generated food coordinates foodX = 50 + 25 * random.nextInt(32); foodY = 100 + 25 *
random.nextInt(25); // Game points initialized to 0 score = 0; } // Drawing panel @Override protected void
paintComponent(Graphics g) { // TODO Auto-generated method stub
super.paintComponent(g); // Clear screen effect this.setBackground(Color.white); // Set the background color of the panel
ImageData.header.paintIcon(this, g, 25, 10); // Draw a picture of the panel head (logo) g.fillRect(25,
75, 850, 675); // Draw game area // Draw the game points plate g.setColor(Color.RED); g.setFont(new
Font(" Song style ", Font.BOLD, 20)); g.drawString(" length :" + len, 680, 30);
g.drawString(" fraction :" + score, 680, 55); // Control the direction and position of snake head if (dir.equals("R")) {//
When the snake heads to the right ImageData.right.paintIcon(this, g, snakeX[0], snakeY[0]); } else if
(dir.equals("D")) {// When the snake's head is down ImageData.down.paintIcon(this, g, snakeX[0],
snakeY[0]); } else if (dir.equals("L")) {// When the snake heads to the left
ImageData.left.paintIcon(this, g, snakeX[0], snakeY[0]); } else if
(dir.equals("U")) {// When the snake's head is up ImageData.up.paintIcon(this, g, snakeX[0],
snakeY[0]); } // Draw the snake for (int i = 1; i < len; i++) {
ImageData.body.paintIcon(this, g, snakeX[i], snakeY[i]); }
ImageData.food.paintIcon(this, g, foodX, foodY);// Draw food according to random coordinates // Tips before the game starts if
(isStart == false) { g.setColor(Color.white); g.setFont(new Font(" Song style ",
Font.BOLD, 40)); g.drawString(" Press the space bar to start the game ", 245, 400); g.drawString(" It's hard to eat one food 10 branch ",
265, 450); } // The game failed , end if (isOver) { g.setColor(Color.RED); ; g.setFont(new
Font(" Song style ", Font.BOLD, 40)); g.drawString(" The game failed , Press the space bar to restart the game ", 100, 400);
g.drawString(" It's hard to eat one food 10 branch ", 260, 450); } } // Keyboard monitoring events : Press the button to control whether the game starts or not @Override public
void keyPressed(KeyEvent e) { // TODO Auto-generated method stub // Keyboard pressed not released int
keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_SPACE) { if (isOver) {//
Restart the game when it fails isOver = false; Init(); // new GamePanel();// Re enter the game } else {//
When the game is over , Press the space bar to pause the game // If you press the space bar isStart = !isStart;// Reverse the control game switch } repaint();//
Redraw interface } // Press the button up and down to control the head direction of the snake if (keyCode == KeyEvent.VK_RIGHT) { if
(dir.equals("L") == false) { dir = "R";// If the snake is not moving to the left , You can move to the right } } else if
(keyCode == KeyEvent.VK_DOWN) { if (dir.equals("U") == false) { dir = "D";//
If the current direction of the snake's movement is not upward , You can move down } } else if (keyCode == KeyEvent.VK_LEFT) { if
(dir.equals("R") == false) { dir = "L";// If the snake is not moving to the right , You can move to the left } } else if
(keyCode == KeyEvent.VK_UP) { if (dir.equals("D") == false) { dir = "U";//
If the snake is not moving to the right , You can move to the left } } } @Override public void keyTyped(KeyEvent e) { }
@Override public void keyReleased(KeyEvent e) { } // Operation performed by timer @Override public
void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //
If the game is in the start state , And it's not over , Then the snake can move if (isStart == true && isOver == false) { //
Move right : Let the latter move to the position of the former for (int i = len - 1; i > 0; i--) { snakeX[i] = snakeX[i -
1]; snakeY[i] = snakeY[i - 1]; } // The head of the snake moves in the direction controlled by the key if (dir.equals("R")) {
snakeX[0] = snakeX[0] + 25;// Snake head moves one unit to the right :25 It's a unit if (snakeX[0] >= 850) { //
snakeX[0] = 50;// If the snake's head goes beyond the boundary, the snake comes out from the left side of the wall isOver = true;// Snake hits wall , The game failed } } else if
(dir.equals("D")) {// Snake head moves down one unit snakeY[0] = snakeY[0] + 25; if (snakeY[0] >=
725) { // snakeY[0] = 100;// If the snake's head goes beyond the boundary, the snake comes out from the top of the wall isOver = true;// Snake hits wall , The game failed }
} else if (dir.equals("L")) {// Snake head moves one unit to the left snakeX[0] = snakeX[0] - 25; if
(snakeX[0] <= 25) { // snakeX[0] = 850;// If the snake's head goes beyond the boundary, the snake comes out from the right side of the wall isOver = true;//
Snake hits wall , The game failed } } else if (dir.equals("U")) {// Snake head moves up one unit snakeY[0] = snakeY[0] -
25; if (snakeY[0] <= 75) { // snakeY[0] = 725;// If the snake's head goes beyond the boundary, the snake comes out from the bottom of the wall isOver =
true;// Snake hits wall , The game failed } } // If the snakehead reaches the food position , Eat the food if (snakeX[0] == foodX && snakeY[0]
== foodY) { len++; // Add one to the length of the snake score += 10;// Score plus 10 // Update food coordinates foodX = 50 + 25 *
random.nextInt(32); foodY = 100 + 25 * random.nextInt(24); } // Cycle to judge whether the snake head hit the snake
for (int i = 1; i < len; i++) { if (snakeX[0] == snakeX[i] && snakeY[0] ==
snakeY[i]) { isOver = true;// If the snake head hits the snake, the game ends } } //repaint(); repaint(25, 0,
850, 745);// Constantly update the game area page , Achieve animation effect timer.start();// Start timer } } }
The pictures used in the game are as follows ( Snake body , Snake head down , food ,logo, Snake head to the left , Snake head to the right , Upward snakehead ):
Technology