Advertisement
LegendSujay2019

Making snake game from java

Nov 7th, 2020
2,399
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.65 KB | None | 0 0
  1. //board.java//
  2. package com.zetcode;
  3.  
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.Font;
  7. import java.awt.FontMetrics;
  8. import java.awt.Graphics;
  9. import java.awt.Image;
  10. import java.awt.Toolkit;
  11. import java.awt.event.ActionEvent;
  12. import java.awt.event.ActionListener;
  13. import java.awt.event.KeyAdapter;
  14. import java.awt.event.KeyEvent;
  15. import javax.swing.ImageIcon;
  16. import javax.swing.JPanel;
  17. import javax.swing.Timer;
  18.  
  19. public class Board extends JPanel implements ActionListener {
  20.  
  21.     private final int B_WIDTH = 300;
  22.     private final int B_HEIGHT = 300;
  23.     private final int DOT_SIZE = 10;
  24.     private final int ALL_DOTS = 900;
  25.     private final int RAND_POS = 29;
  26.     private final int DELAY = 140;
  27.  
  28.     private final int x[] = new int[ALL_DOTS];
  29.     private final int y[] = new int[ALL_DOTS];
  30.  
  31.     private int dots;
  32.     private int apple_x;
  33.     private int apple_y;
  34.  
  35.     private boolean leftDirection = false;
  36.     private boolean rightDirection = true;
  37.     private boolean upDirection = false;
  38.     private boolean downDirection = false;
  39.     private boolean inGame = true;
  40.  
  41.     private Timer timer;
  42.     private Image ball;
  43.     private Image apple;
  44.     private Image head;
  45.  
  46.     public Board() {
  47.        
  48.         initBoard();
  49.     }
  50.    
  51.     private void initBoard() {
  52.  
  53.         addKeyListener(new TAdapter());
  54.         setBackground(Color.black);
  55.         setFocusable(true);
  56.  
  57.         setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
  58.         loadImages();
  59.         initGame();
  60.     }
  61.  
  62.     private void loadImages() {
  63.  
  64.         ImageIcon iid = new ImageIcon("src/resources/dot.png");
  65.         ball = iid.getImage();
  66.  
  67.         ImageIcon iia = new ImageIcon("src/resources/apple.png");
  68.         apple = iia.getImage();
  69.  
  70.         ImageIcon iih = new ImageIcon("src/resources/head.png");
  71.         head = iih.getImage();
  72.     }
  73.  
  74.     private void initGame() {
  75.  
  76.         dots = 3;
  77.  
  78.         for (int z = 0; z < dots; z++) {
  79.             x[z] = 50 - z * 10;
  80.             y[z] = 50;
  81.         }
  82.        
  83.         locateApple();
  84.  
  85.         timer = new Timer(DELAY, this);
  86.         timer.start();
  87.     }
  88.  
  89.     @Override
  90.     public void paintComponent(Graphics g) {
  91.         super.paintComponent(g);
  92.  
  93.         doDrawing(g);
  94.     }
  95.    
  96.     private void doDrawing(Graphics g) {
  97.        
  98.         if (inGame) {
  99.  
  100.             g.drawImage(apple, apple_x, apple_y, this);
  101.  
  102.             for (int z = 0; z < dots; z++) {
  103.                 if (z == 0) {
  104.                     g.drawImage(head, x[z], y[z], this);
  105.                 } else {
  106.                     g.drawImage(ball, x[z], y[z], this);
  107.                 }
  108.             }
  109.  
  110.             Toolkit.getDefaultToolkit().sync();
  111.  
  112.         } else {
  113.  
  114.             gameOver(g);
  115.         }        
  116.     }
  117.  
  118.     private void gameOver(Graphics g) {
  119.        
  120.         String msg = "Game Over";
  121.         Font small = new Font("Helvetica", Font.BOLD, 14);
  122.         FontMetrics metr = getFontMetrics(small);
  123.  
  124.         g.setColor(Color.white);
  125.         g.setFont(small);
  126.         g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
  127.     }
  128.  
  129.     private void checkApple() {
  130.  
  131.         if ((x[0] == apple_x) && (y[0] == apple_y)) {
  132.  
  133.             dots++;
  134.             locateApple();
  135.         }
  136.     }
  137.  
  138.     private void move() {
  139.  
  140.         for (int z = dots; z > 0; z--) {
  141.             x[z] = x[(z - 1)];
  142.             y[z] = y[(z - 1)];
  143.         }
  144.  
  145.         if (leftDirection) {
  146.             x[0] -= DOT_SIZE;
  147.         }
  148.  
  149.         if (rightDirection) {
  150.             x[0] += DOT_SIZE;
  151.         }
  152.  
  153.         if (upDirection) {
  154.             y[0] -= DOT_SIZE;
  155.         }
  156.  
  157.         if (downDirection) {
  158.             y[0] += DOT_SIZE;
  159.         }
  160.     }
  161.  
  162.     private void checkCollision() {
  163.  
  164.         for (int z = dots; z > 0; z--) {
  165.  
  166.             if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
  167.                 inGame = false;
  168.             }
  169.         }
  170.  
  171.         if (y[0] >= B_HEIGHT) {
  172.             inGame = false;
  173.         }
  174.  
  175.         if (y[0] < 0) {
  176.             inGame = false;
  177.         }
  178.  
  179.         if (x[0] >= B_WIDTH) {
  180.             inGame = false;
  181.         }
  182.  
  183.         if (x[0] < 0) {
  184.             inGame = false;
  185.         }
  186.        
  187.         if (!inGame) {
  188.             timer.stop();
  189.         }
  190.     }
  191.  
  192.     private void locateApple() {
  193.  
  194.         int r = (int) (Math.random() * RAND_POS);
  195.         apple_x = ((r * DOT_SIZE));
  196.  
  197.         r = (int) (Math.random() * RAND_POS);
  198.         apple_y = ((r * DOT_SIZE));
  199.     }
  200.  
  201.     @Override
  202.     public void actionPerformed(ActionEvent e) {
  203.  
  204.         if (inGame) {
  205.  
  206.             checkApple();
  207.             checkCollision();
  208.             move();
  209.         }
  210.  
  211.         repaint();
  212.     }
  213.  
  214.     private class TAdapter extends KeyAdapter {
  215.  
  216.         @Override
  217.         public void keyPressed(KeyEvent e) {
  218.  
  219.             int key = e.getKeyCode();
  220.  
  221.             if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
  222.                 leftDirection = true;
  223.                 upDirection = false;
  224.                 downDirection = false;
  225.             }
  226.  
  227.             if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
  228.                 rightDirection = true;
  229.                 upDirection = false;
  230.                 downDirection = false;
  231.             }
  232.  
  233.             if ((key == KeyEvent.VK_UP) && (!downDirection)) {
  234.                 upDirection = true;
  235.                 rightDirection = false;
  236.                 leftDirection = false;
  237.             }
  238.  
  239.             if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
  240.                 downDirection = true;
  241.                 rightDirection = false;
  242.                 leftDirection = false;
  243.             }
  244.         }
  245.     }
  246. }
  247. //First we will define the constants used in our game.//
  248. private final int B_WIDTH = 300;
  249. private final int B_HEIGHT = 300;
  250. private final int DOT_SIZE = 10;
  251. private final int ALL_DOTS = 900;
  252. private final int RAND_POS = 29;
  253. private final int DELAY = 140;
  254. private final int x[] = new int[ALL_DOTS];
  255. private final int y[] = new int[ALL_DOTS];
  256. //These two arrays store the x and y coordinates of all joints of a snake.//
  257. private void loadImages() {
  258.  
  259.     ImageIcon iid = new ImageIcon("src/resources/dot.png");
  260.     ball = iid.getImage();
  261.  
  262.     ImageIcon iia = new ImageIcon("src/resources/apple.png");
  263.     apple = iia.getImage();
  264.  
  265.     ImageIcon iih = new ImageIcon("src/resources/head.png");
  266.     head = iih.getImage();
  267. }
  268. //In the loadImages() method we get the images for the game. The ImageIcon class is used for displaying PNG images.//
  269. private void initGame() {
  270.  
  271.     dots = 3;
  272.  
  273.     for (int z = 0; z < dots; z++) {
  274.         x[z] = 50 - z * 10;
  275.         y[z] = 50;
  276.     }
  277.  
  278.     locateApple();
  279.  
  280.     timer = new Timer(DELAY, this);
  281.     timer.start();
  282. }
  283. //In the initGame() method we create the snake, randomly locate an apple on the board, and start the timer.//
  284. private void checkApple() {
  285.  
  286.     if ((x[0] == apple_x) && (y[0] == apple_y)) {
  287.  
  288.         dots++;
  289.         locateApple();
  290.     }
  291. }
  292. //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.
  293.  
  294. 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.//
  295. for (int z = dots; z > 0; z--) {
  296.     x[z] = x[(z - 1)];
  297.     y[z] = y[(z - 1)];
  298. }
  299. //This code moves the joints up the chain.//
  300. if (leftDirection) {
  301.     x[0] -= DOT_SIZE;
  302. }
  303. //This line moves the head to the left.
  304.  
  305. In the checkCollision() method, we determine if the snake has hit itself or one of the walls.//
  306. for (int z = dots; z > 0; z--) {
  307.  
  308.     if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
  309.         inGame = false;
  310.     }
  311. }
  312. //If the snake hits one of its joints with its head the game is over.//
  313. if (y[0] >= B_HEIGHT) {
  314.     inGame = false;
  315. }
  316. //snake.java//
  317. package com.zetcode;
  318.  
  319. import java.awt.EventQueue;
  320. import javax.swing.JFrame;
  321.  
  322. public class Snake extends JFrame {
  323.  
  324.     public Snake() {
  325.        
  326.         initUI();
  327.     }
  328.    
  329.     private void initUI() {
  330.        
  331.         add(new Board());
  332.        
  333.         setResizable(false);
  334.         pack();
  335.        
  336.         setTitle("Snake");
  337.         setLocationRelativeTo(null);
  338.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  339.     }
  340.    
  341.     public static void main(String[] args) {
  342.        
  343.         EventQueue.invokeLater(() -> {
  344.             JFrame ex = new Snake();
  345.             ex.setVisible(true);
  346.         });
  347.     }
  348. }
  349. //package com.zetcode;
  350.  
  351. import java.awt.EventQueue;
  352. import javax.swing.JFrame;
  353.  
  354. public class Snake extends JFrame {
  355.  
  356.     public Snake() {
  357.        
  358.         initUI();
  359.     }
  360.    
  361.     private void initUI() {
  362.        
  363.         add(new Board());
  364.        
  365.         setResizable(false);
  366.         pack();
  367.        
  368.         setTitle("Snake");
  369.         setLocationRelativeTo(null);
  370.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  371.     }
  372.    
  373.     public static void main(String[] args) {
  374.        
  375.         EventQueue.invokeLater(() -> {
  376.             JFrame ex = new Snake();
  377.             ex.setVisible(true);
  378.         });
  379.     }
  380. }
  381. //This is the main class.//
  382. setResizable(false);
  383. pack();
  384. //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.//
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement