[java] Snake Game - lickin_lollipops

Viewer

copydownloadembedprintName: Snake Game - lickin_lollipops
  1.  
  2. import java.awt.*;
  3. import java.awt.event.KeyEvent;
  4. import java.awt.event.KeyListener;
  5. import java.util.ArrayList;
  6. import java.util.concurrent.TimeUnit;
  7. import java.util.Random;
  8.  
  9. import javax.swing.*;
  10.  
  11. @SuppressWarnings("serial")
  12. public class Snake extends JPanel {
  13.        
  14.        
  15.         private static int updateRate = 200; //in milliseconds, = 0.25 (250) seconds of sleep
  16.        
  17.         //snake
  18.         private static final int RADIUS = 7;
  19.         private ArrayList<Integer> snakeBodyX = new ArrayList<Integer>();
  20.         private ArrayList<Integer> snakeBodyY = new ArrayList<Integer>();
  21.        
  22.         private ArrayList<Integer> oldSnakeBodyX = new ArrayList<Integer>();
  23.         private ArrayList<Integer> oldSnakeBodyY = new ArrayList<Integer>();
  24.        
  25.         private int speed = RADIUS * 2;
  26.         private int speedX = 0;
  27.         private int speedY = 0;
  28.        
  29.         //fruit
  30.         private static final int FRUIT_RADIUS = RADIUS;
  31.         private Random fruitCoordinates = new Random();
  32.         private int fruitX[] = new int[2]; //{fruit 1, fruit 2}
  33.         private int fruitY[] = new int[2]; //{fruit 1, fruit 2}
  34.        
  35.         private boolean firstRun = true;
  36.         private boolean end = false;
  37.        
  38.        
  39.         JTextArea inputText; //for arrow key movement
  40.         int arrowKeyPressed; //1 = up, 2 = down, 3 = left, 4 = right
  41.        
  42.         //BOX SIZE
  43.         //(0,0) is in the top left corner, goes positive as it goes right and down
  44.         private static final int BOX_WIDTH = (RADIUS * 2) * 32;
  45.         private static final int BOX_HEIGHT = (RADIUS * 2) * 32;
  46.        
  47.        
  48.         //high score
  49.         private int fruitEaten = 0;
  50.        
  51.         public Snake() {
  52.                 setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
  53.                 inputText = new JTextArea();
  54.                 add(inputText, BorderLayout.NORTH);
  55.                
  56.                 //Original SNAKE SIZE
  57.                 snakeBodyX.add((BOX_WIDTH / 2));
  58.                 snakeBodyY.add(BOX_HEIGHT / 2);
  59.                
  60.  
  61.                
  62.                 Thread gameThread = new Thread() {
  63.                         public void run() {                         
  64.                                 while (true) {                                       
  65.                                        
  66.                                         //program ends
  67.                                         if(end) {
  68.                                                 repaint();
  69.                                                 break;
  70.                                         } //program ends when the snake hits the wall
  71.                                           else if(snakeBodyX.get(0) >= (BOX_WIDTH - (RADIUS * 2)) || (snakeBodyX.get(0) <= 0)) { //head hits the right side or left side (in that order)
  72.                                                 end = true;
  73.                                                 repaint();
  74.                                                 break;
  75.                                         } else if(snakeBodyY.get(0) >= (BOX_HEIGHT - (RADIUS * 2)) || (snakeBodyY.get(0) <= 0)) { //head hits the bottom or top (in that order)
  76.                                                 end = true;
  77.                                                 repaint();
  78.                                                 break;
  79.                                         }
  80.                                        
  81.                                        
  82.                                        
  83.                                         //SNAKE STUFF
  84.                                        
  85.                                         //arrow key movement                                 
  86.                                         inputText.addKeyListener(new KeyListener() {
  87.                                                 public void keyPressed(KeyEvent e) {
  88.                                                         int i = e.getKeyCode();
  89.                                                        
  90.                                                         switch(i) {
  91.                                                                 case KeyEvent.VK_UP:
  92.                                                                         if(snakeBodyX.size() > 1 && arrowKeyPressed == 2) {
  93.                                                                                 break;
  94.                                                                         }
  95.                                                                         arrowKeyPressed = 1;
  96.                                                                         break;
  97.                                                                 case KeyEvent.VK_DOWN:
  98.                                                                         if(snakeBodyX.size() > 1 && arrowKeyPressed == 1) {
  99.                                                                                 break;
  100.                                                                         }
  101.                                                                         arrowKeyPressed = 2;
  102.                                                                         break;
  103.                                                                 case KeyEvent.VK_LEFT:
  104.                                                                         if(snakeBodyX.size() > 1 && arrowKeyPressed == 4) {
  105.                                                                                 break;
  106.                                                                         }
  107.                                                                         arrowKeyPressed = 3;
  108.                                                                         break;
  109.                                                                 case KeyEvent.VK_RIGHT:
  110.                                                                         if(snakeBodyX.size() > 1 && arrowKeyPressed == 3) {
  111.                                                                                 break;
  112.                                                                         }
  113.                                                                         arrowKeyPressed = 4;
  114.                                                                         break;
  115.                                                         }
  116.                                                        
  117.                                                 }
  118.                                                 @Override
  119.                                                 public void keyReleased(KeyEvent e) {
  120.                                                        
  121.                                                 }
  122.                                                 @Override
  123.                                                 public void keyTyped(KeyEvent e) {
  124.  
  125.                                                 }
  126.                                         });
  127.                                        
  128.                                        
  129.                                        
  130.                                         //change speed based on arrow keys pressed
  131.                                         switch(arrowKeyPressed) {
  132.                                                 case 1: //up
  133.                                                         speedX = 0; //resets speed in the X direction
  134.                                                         speedY = 0 - speed;
  135.                                                         break;
  136.                                                 case 2: //down
  137.                                                         speedX = 0; //resets speed in the X direction
  138.                                                         speedY = speed;
  139.                                                         break;
  140.                                                 case 3: //left
  141.                                                         speedY = 0; //resets speed in the Y direction
  142.                                                         speedX = 0 - speed;
  143.                                                         break;
  144.                                                 case 4: //right
  145.                                                         speedY = 0; //resets speed in the Y direction
  146.                                                         speedX = speed;
  147.                                                         break;
  148.                                         }
  149.                                        
  150.                                        
  151.                                         oldSnakeBodyX.clear(); // empty the arraylist
  152.                                         oldSnakeBodyY.clear(); //empty the arraylist
  153.                                        
  154.                                         //copy current snake body onto old snake body
  155.                                         for(int pixel = 0; pixel < snakeBodyX.size(); pixel++) {
  156.                                                 oldSnakeBodyX.add(snakeBodyX.get(pixel).intValue()); //get the int value of the Integers so that they refer to different objects
  157.                                                 oldSnakeBodyY.add(snakeBodyY.get(pixel).intValue());
  158.                                         }
  159.  
  160.                                        
  161.                                         //move the snake             
  162.                                         snakeBodyX.add(0, snakeBodyX.get(0) + speedX); //inserts a new head value in the arraylist
  163.                                         snakeBodyX.remove(snakeBodyX.size() - 1); //deletes the last head value
  164.                                        
  165.                                         snakeBodyY.add(0, snakeBodyY.get(0) + speedY); //inserts a new head value in the arraylist
  166.                                         snakeBodyY.remove(snakeBodyY.size() - 1); //deletes the last head value
  167.                                        
  168.                                                                        
  169.                                        
  170.                                         //if head hits other part of snake
  171.                                                 //have to type cast the objects in the arraylist as ints because even if two objects have the same value, they are not ==
  172.                                         if(speedX != 0 || speedY != 0) {
  173.                                                 for(int bodyLocation = 0; bodyLocation < snakeBodyX.size(); bodyLocation++) {
  174.                                                         if(((int)snakeBodyX.get(0) == (int)oldSnakeBodyX.get(bodyLocation)) && ((int)snakeBodyY.get(0) == (int)oldSnakeBodyY.get(bodyLocation))) {
  175.                                                                 end = true;
  176.                                                         }
  177.                                                 }
  178.                                         }
  179.                                        
  180.                                        
  181.                                         //FRUIT STUFF
  182.                                        
  183.                                         //spawn the first fruits
  184.                                         if(firstRun) {
  185.                                                
  186.                                                 fruitX[0] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2)); //EXPLANATION: The Box Height divided by 30 is 32. I want the random number to go from 1 to 30 and then multiply it by 30
  187.                                                 fruitY[0] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2)); //to make sure that the head will be able to be in that location. If the random number went up to 32
  188.                                                                                                                                                                                 //then the fruit would go off the board, since the top left corner of the fruit is its coordinates. 
  189.                                                                                                                                                                                  //I also do not want the fruit on the edge because it's basically impossible to get the fruits on the edge
  190.                                                
  191.                                                 do {
  192.                                                         fruitX[1] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  193.                                                         fruitY[1] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  194.                                                 } while((fruitX[0] == fruitX[1]) && (fruitY[0] == fruitY[1]));
  195.                                                
  196.                                                 firstRun = false;
  197.                                         }
  198.                                        
  199.                                        
  200.                                         //if fruit is eaten
  201.                                         if((snakeBodyX.get(0) == fruitX[0] && snakeBodyY.get(0) == fruitY[0]) || (snakeBodyX.get(0) == fruitX[1] && snakeBodyY.get(0) == fruitY[1])) { //(if the head is at the same coordinates as fruit 1) OR (if the head is at the same coordinates as fruit 2)
  202.                                                
  203.                                                 //expand snake
  204.                                                 snakeBodyX.add(snakeBodyX.get(snakeBodyX.size() - 1));
  205.                                                 snakeBodyY.add(snakeBodyY.get(snakeBodyY.size() - 1));
  206.                                                
  207.                                                 //increase score
  208.                                                 fruitEaten++;
  209.                                                
  210.                                                 //increase speed
  211.                                                 if(fruitEaten % 5 == 0) {
  212.                                                         updateRate -= 15;
  213.                                                 }
  214.                                                
  215.                                                 //replace that fruit
  216.                                                 //fruit 1
  217.                                                 if((snakeBodyX.get(0) == fruitX[0] && snakeBodyY.get(0) == fruitY[0])) { //if fruit 1 is eaten
  218.                                                         do {
  219.                                                                 fruitX[0] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  220.                                                                 fruitY[0] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  221.                                                         } while((fruitX[0] == fruitX[1] && fruitY[0] == fruitY[1])); //replaces if the new fruit is at the same location as the other one
  222.                                                 }
  223.                                                
  224.                                                 //fruit 2
  225.                                                 if((snakeBodyX.get(0) == fruitX[1] && snakeBodyY.get(0) == fruitY[1])) { //if fruit 2 is eaten
  226.                                                         do {
  227.                                                                 fruitX[1] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  228.                                                                 fruitY[1] = ((fruitCoordinates.nextInt(30) + 1) * (RADIUS * 2));
  229.                                                         } while((fruitX[0] == fruitX[1] && fruitY[0] == fruitY[1])); //replaces if the new fruit is at the same location as the other one
  230.                                                 }
  231.                                         }
  232.                                        
  233.                                        
  234.                                         //redraw
  235.                                         repaint();
  236.                                        
  237.  
  238.                                         //update
  239.                                         try {
  240.                                     TimeUnit.MILLISECONDS.sleep(updateRate);
  241.                             } catch (InterruptedException ex) { }
  242.                                        
  243.                                 }
  244.                    }
  245.                 };
  246.                
  247.                 gameThread.start();
  248.         }
  249.        
  250.         public void paintComponent(Graphics g) {
  251.                 super.paintComponent(g);
  252.  
  253.                 g.setColor(Color.WHITE);
  254.                 g.fillRect(00, BOX_WIDTH, BOX_HEIGHT);
  255.                
  256.                 //make border
  257.                 g.setColor(Color.RED);
  258.                 g.drawRect(00, BOX_WIDTH, BOX_HEIGHT);
  259.                
  260.                 //draw fruit
  261.                 g.setColor(Color.BLUE);
  262.                 for(int i = 0; i < 2; i++) {
  263.                         g.fillOval(fruitX[i], fruitY[i](FRUIT_RADIUS * 2)(FRUIT_RADIUS * 2));
  264.                 }
  265.                
  266.                 //draw snake with a green body
  267.                 g.setColor(Color.GREEN);
  268.                 for(int pixel = snakeBodyX.size() - 1; pixel >= 0; pixel--) {
  269.                         if(pixel == 0) {
  270.                                 g.setColor(Color.RED); //changes the head of the snake to red
  271.                         }
  272.                         g.fillRect(snakeBodyX.get(pixel), snakeBodyY.get(pixel)(RADIUS * 2)(RADIUS * 2));
  273.                 }
  274.                
  275.                
  276.                 //display score
  277.                 g.setColor(Color.BLACK);
  278.                 g.setFont(new Font("Consolas"Font.PLAIN12));
  279.                 String score = "Score: " + fruitEaten;
  280.                 g.drawString(score, 520);
  281.                
  282.                
  283.                 //when head hits wall
  284.                 if(end == true) {
  285.                         //pause
  286.                         try {
  287.                     TimeUnit.MILLISECONDS.sleep(updateRate * 2);
  288.             } catch (InterruptedException ex) { }
  289.                        
  290.                         //reset screen
  291.                         g.setColor(Color.WHITE);
  292.                         g.fillRect(00, BOX_WIDTH, BOX_HEIGHT);
  293.                        
  294.                        
  295.                         //displays "GAME OVER"
  296.                         g.setColor(Color.RED); //font color
  297.                     g.setFont(new Font("Consolas"Font.PLAIN(RADIUS * 11))); //font size
  298.                     final String GAME_OVER = "GAME OVER";
  299.                     g.drawString(GAME_OVER, 30(BOX_HEIGHT / 2));
  300.  
  301.                 }
  302.         }
  303.  
  304.        
  305.         public static void main(String[] args) {
  306.                 javax.swing.SwingUtilities.invokeLater(new Runnable() {
  307.                         public void run() {
  308.                                 JFrame frame = new JFrame();
  309.                                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  310.                                 frame.setContentPane(new Snake());
  311.                                 frame.pack();
  312.                                 frame.setVisible(true);
  313.                         }
  314.                 });
  315.         }
  316.        
  317. }

Editor

You can edit this paste and save as new:


File Description
  • Snake Game - lickin_lollipops
  • Paste Code
  • 09 Dec-2019
  • 9.71 Kb
You can Share it: