Java games snake code

Snake Game using Java Swing and Java AWT in Java

Hi, Today we are learning to build a simple snake game in java using Java-Swing and Java AWT. Java-Swing is a lightweight and cross-platform toolkit used to provide GUI to java programs.

Java AWT is an API that is used for providing GUI to Java applications. But Java AWT is platform-dependent and heavyweight.

In this project, we are using swing for the GUI of the Game, and AWT is used for some predefined methods which are available in it.

Let’s discuss the code and logic’s to build this Game.

So to build this game we are programing 3 java classes that are:-

SnakeFrame For creating Java Swing Application window

SnakePanel This class is used for updating the length of the snake and randomly painting food on the screen and also moving the snake according to the keyboard inputs.

There is another class inside the Snake Panel class MyKey Class that class is used to handle keyboard inputs.

First, we are programing the Snake Frame class.

import javax.swing.JFrame; public class SnakeFrame extends JFrame < SnakeFrame()< this.add(new SankePanel()); this.setTitle("Snake"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); >>

In this class, we are creating a JFrame and setting its title, and also creating a Snake panel object.

Now we are coding for the Jpanel in this class we creating some functions to perform different functionalities like move, start game, etc.

First, we are creating a constructor of the panel class and creating the Game_start function.

SankePanel() < this.setPreferredSize(new Dimension(S_Width,S_Height)); this.setBackground(Color.gray); this.setFocusable(true); this.addKeyListener(new MyKey()); random = new Random(); Game_start(); >public void Game_start()

Now we will code for the draw function and paint function.

public void paintComponent(Graphics graphic) < super.paintComponent(graphic); draw(graphic); >public void draw(Graphics graphic) < if(game_flag)< graphic.setColor(Color.yellow); graphic.fillOval(foodX, foodY,Game_unit_size,Game_unit_size); for(int i=0;ielse < graphic.setColor(new Color(50,180,0)); graphic.fillRect(x_snake[i],y_snake[i],Game_unit_size,Game_unit_size); >> graphic.setColor(Color.blue); graphic.setFont(new Font("Ink Free",Font.BOLD,40)); FontMetrics font_me=getFontMetrics(graphic.getFont()); graphic.drawString("Score:"+foodEAten,(S_Width-font_me.stringWidth("Score:"+foodEAten))/2,graphic.getFont().getSize()); > else < gameOver(graphic); >>

Now we are creating a MyKey class for keyboard inputs.

public class MyKey extends KeyAdapter < @Override public void keyPressed(KeyEvent e) < switch (e.getKeyCode()) < case KeyEvent.VK_LEFT: if(dir!='R')< dir='L'; >break; case KeyEvent.VK_UP: if (dir != 'D') < dir = 'U'; >break; case KeyEvent.VK_RIGHT: if (dir != 'L') < dir = 'R'; >break; case KeyEvent.VK_DOWN: if (dir != 'U') < dir = 'D'; >break; case KeyEvent.VK_R: if(!game_flag) < foodEAten=0; bodylength=2; dir='R'; Arrays.fill(x_snake,0); Arrays.fill(y_snake,0); Game_start(); >break; > > >

This class extends the KeyAdapter Class of the Java AWT event package. Now we have to code for the food of the snake, movement of the snake, and also for game over.

public void newfoodPosition() public void food_EatenOrNot() > public void checkHit() < // for checking if by mistake snake bite itself and if it collides with walls for (int i=bodylength;i>0;i--) > if(x_snake[0] <0) if(x_snake[0]>S_Width) < game_flag=false;>if (y_snake[0] < 0) < game_flag = false;>if (y_snake[0] > S_Height) < game_flag = false;>if(!game_flag) < timer.stop();>> public void gameOver(Graphics graphic) 

Now finally we require a function that calls check functions, again and again, to check the movements of the snake for we have extended ActionListner class in GamePlane class.

@Override public void actionPerformed(ActionEvent arg0) < if (game_flag) < move(); food_EatenOrNot(); checkHit(); >repaint(); >

Woohoo, we finally understand the logic behind this game so let’s copy the complete codes of each class and play our own build snake game.

SnakeGame.java(Main Class)

SnakeFrame.java(Frame class)

import javax.swing.JFrame; public class SnakeFrame extends JFrame < SnakeFrame()< this.add(new SankePanel()); this.setTitle("Snake"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); >>

SnakePanel.java(Panel Class)

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Arrays; import java.util.Random; public class SankePanel extends JPanel implements ActionListener < static final int S_Width=1200; static final int S_Height=600; static final int Game_unit_size=50; Timer timer; Random random; int foodEAten; int foodX; int foodY; int bodylength = 2; boolean game_flag = false; char dir = 'R'; static final int DELAY = 160; static final int G_Size=(S_Width*S_Height)/(Game_unit_size*Game_unit_size); final int x_snake[]=new int[G_Size]; final int y_snake[]=new int[G_Size]; SankePanel()< this.setPreferredSize(new Dimension(S_Width,S_Height)); this.setBackground(Color.gray); this.setFocusable(true); this.addKeyListener(new MyKey()); random = new Random(); Game_start(); >public void Game_start() < newfoodPosition(); game_flag=true; timer=new Timer(DELAY,this); timer.start(); >public void paintComponent(Graphics graphic) < super.paintComponent(graphic); draw(graphic); >public void draw(Graphics graphic) < if(game_flag)< graphic.setColor(Color.yellow); graphic.fillOval(foodX, foodY,Game_unit_size,Game_unit_size); for(int i=0;ielse < graphic.setColor(new Color(50,180,0)); graphic.fillRect(x_snake[i],y_snake[i],Game_unit_size,Game_unit_size); >> graphic.setColor(Color.blue); graphic.setFont(new Font("Ink Free",Font.BOLD,40)); FontMetrics font_me=getFontMetrics(graphic.getFont()); graphic.drawString("Score:"+foodEAten,(S_Width-font_me.stringWidth("Score:"+foodEAten))/2,graphic.getFont().getSize()); > else < gameOver(graphic); >> public void move() < for(int i=bodylength;i>0;i--) < x_snake[i]=x_snake[i-1]; y_snake[i]=y_snake[i-1]; >switch (dir) < case 'U': y_snake[0]=y_snake[0]-Game_unit_size; break; case 'L': x_snake[0] = x_snake[0] - Game_unit_size; break; case 'D': y_snake[0] = y_snake[0] + Game_unit_size; break; case 'R': x_snake[0] = x_snake[0] + Game_unit_size; break; >> public void newfoodPosition() public void food_EatenOrNot() > public void checkHit() < // for checking if by mistake snake bite itself and if it collides with walls for (int i=bodylength;i>0;i--) > if(x_snake[0] <0) if(x_snake[0]>S_Width) < game_flag=false;>if (y_snake[0] < 0) < game_flag = false;>if (y_snake[0] > S_Height) < game_flag = false;>if(!game_flag) < timer.stop();>> public void gameOver(Graphics graphic) public class MyKey extends KeyAdapter < @Override public void keyPressed(KeyEvent e) < switch (e.getKeyCode()) < case KeyEvent.VK_LEFT: if(dir!='R')< dir='L'; >break; case KeyEvent.VK_UP: if (dir != 'D') < dir = 'U'; >break; case KeyEvent.VK_RIGHT: if (dir != 'L') < dir = 'R'; >break; case KeyEvent.VK_DOWN: if (dir != 'U') < dir = 'D'; >break; case KeyEvent.VK_R: if(!game_flag) < foodEAten=0; bodylength=2; dir='R'; Arrays.fill(x_snake,0); Arrays.fill(y_snake,0); Game_start(); >break; > > > @Override public void actionPerformed(ActionEvent arg0) < if (game_flag) < move(); food_EatenOrNot(); checkHit(); >repaint(); > >

Output

In the image below, you can see the output result of our code.

snakeGame

Thank you for reading this blog.

Источник

Java Snake

In this part of the Java 2D games tutorial, we create a Java Snake game clone. Source code and images can be found at the author’s Github Java-Snake-Game repository.

Snake

Snake is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple its body grows. The snake must avoid the walls and its own body. This game is sometimes called Nibbles.

Development of Java Sname game

The size of each of the joints of a snake is 10 px. The snake is controlled with the cursor keys. Initially, the snake has three joints. If the game is finished, the «Game Over» message is displayed in the middle of the board.

package com.zetcode; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener < private final int B_WIDTH = 300; private final int B_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 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 Board() < initBoard(); >private void initBoard() < addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT)); loadImages(); initGame(); >private void loadImages() < ImageIcon iid = new ImageIcon("src/resources/dot.png"); ball = iid.getImage(); ImageIcon iia = new ImageIcon("src/resources/apple.png"); apple = iia.getImage(); ImageIcon iih = new ImageIcon("src/resources/head.png"); head = iih.getImage(); >private void initGame() < dots = 3; for (int z = 0; z < dots; z++) < x[z] = 50 - z * 10; y[z] = 50; >locateApple(); timer = new Timer(DELAY, this); timer.start(); > @Override public void paintComponent(Graphics g) < super.paintComponent(g); doDrawing(g); >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, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2); >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] >= B_HEIGHT) < inGame = false; >if (y[0] < 0) < inGame = false; >if (x[0] >= B_WIDTH) < inGame = false; >if (x[0] < 0) < inGame = false; >if (!inGame) < timer.stop(); >> 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)); >@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; >> > >

First we will define the constants used in our game.

private final int B_WIDTH = 300; private final int B_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;

The B_WIDTH and B_HEIGHT constants determine the size of the board. The DOT_SIZE is the size of the apple and the dot of the snake. The ALL_DOTS constant defines the maximum number of possible dots on the board (900 = (300*300)/(10*10)). The RAND_POS constant is used to calculate a random position for an apple. The DELAY constant determines the speed of the game.

private final int x[] = new int[ALL_DOTS]; private final int y[] = new int[ALL_DOTS];

These two arrays store the x and y coordinates of all joints of a snake.

In the loadImages() method we get the images for the game. The ImageIcon class is used for displaying PNG images.

private void initGame() < dots = 3; for (int z = 0; z < dots; z++) < x[z] = 50 - z * 10; y[z] = 50; >locateApple(); timer = new Timer(DELAY, this); timer.start(); >

In the initGame() method we create the snake, randomly locate an apple on the board, and start the timer.

If the apple collides with the head, we increase the number of joints of the snake. We call the locateApple() method which randomly positions a new apple object.

In the move() method we have the key algorithm of the game. To understand it, look at how the snake is moving. We control the head of the snake. We can change its direction with the cursor keys. The rest of the joints move one position up the chain. The second joint moves where the first was, the third joint where the second was etc.

This code moves the joints up the chain.

This line moves the head to the left.

In the checkCollision() method, we determine if the snake has hit itself or one of the walls.

for (int z = dots; z > 0; z--) < if ((z >4) && (x[0] == x[z]) && (y[0] == y[z])) < inGame = false; >>

If the snake hits one of its joints with its head the game is over.

The game is finished if the snake hits the bottom of the board.

package com.zetcode; import java.awt.EventQueue; import javax.swing.JFrame; public class Snake extends JFrame < public Snake() < initUI(); >private void initUI() < add(new Board()); setResizable(false); pack(); setTitle("Snake"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); >public static void main(String[] args) < EventQueue.invokeLater(() ->< JFrame ex = new Snake(); ex.setVisible(true); >); > >

The setResizable() method affects the insets of the JFrame container on some platforms. Therefore, it is important to call it before the pack() method. Otherwise, the collision of the snake’s head with the right and bottom borders might not work correctly. Figure: Snake

This was the Snake game in Java.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple snake game in java — Well documented

License

hexadeciman/Snake

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A simple snake game in java . Using Threads and Java Swing to display the game. The code is well commented, if you have any questions or want to continue this project feel free to do so 👌

alt tag

Buy Me A Coffee

  • Just download the SnakeGame.jar file
  • Run it
  • Start playing with the arrows keys.
  • If you lose, just close it and re-open it (I will add a restart button possibly)

Источник

Читайте также:  What is java ee web profile
Оцените статью