daily pastebin goal
86%
SHARE
TWEET

Untitled

a guest Jun 14th, 2018 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.awt.*;
  2. import java.awt.event.KeyEvent;
  3. import java.awt.event.KeyListener;
  4.  
  5. import javax.swing.*;
  6. public class SnakeGame extends JPanel {
  7.     private int snakeY, snakeX;
  8.     private int direction=4;    //1 hoch, 2, runter, 3 links, 4 rechts
  9.     public SnakeGame() {
  10.         setFocusable(true);
  11.         addKeyListener(new Listener());
  12.     }
  13.    
  14.     public void paintComponent(Graphics g) {
  15.         super.paintComponent(g);
  16.         g.fillRect(snakeX, snakeY, 10, 10);
  17.         System.out.println(snakeY);
  18.     }
  19.    
  20.     public void moveSnake() {
  21.         if(direction==1) {
  22.             while(direction==1) {
  23.                 snakeY-=10;
  24.                 System.out.println(snakeY);
  25.                 repaint();
  26.                 speed();   
  27.             }
  28.         }
  29.         else if(direction==2) {
  30.             snakeY+=10;
  31.             repaint();
  32.             speed();
  33.         }
  34.         else if(direction==3) {
  35.             snakeX-=10;
  36.             repaint();
  37.             speed();
  38.         }
  39.         else if(direction==4) {
  40.             snakeX+=10;
  41.             repaint();
  42.             speed();
  43.         }
  44.        
  45.     }
  46.    
  47.     public void speed() {
  48.         try {
  49.             Thread.sleep(200);
  50.         }
  51.         catch (Exception e) {}
  52.     }
  53.    
  54.     public class Listener implements KeyListener {
  55.  
  56.         @Override
  57.         public void keyPressed(KeyEvent e) {
  58.                        
  59.         }
  60.  
  61.         @Override
  62.         public void keyReleased(KeyEvent e) {
  63.             if(e.getKeyCode()==KeyEvent.VK_UP){
  64.                 direction=1;
  65.                 System.out.println(direction);
  66.                 moveSnake();
  67.             }
  68.             else if(e.getKeyCode()==KeyEvent.VK_DOWN){
  69.                 direction=2;
  70.                 moveSnake();
  71.             }
  72.             else if(e.getKeyCode()==KeyEvent.VK_LEFT){
  73.                 direction=3;
  74.                 moveSnake();
  75.             }
  76.             else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
  77.                 direction=4;
  78.                 moveSnake();
  79.             }
  80.         }
  81.  
  82.         @Override
  83.         public void keyTyped(KeyEvent e) {
  84.            
  85.         }
  86.        
  87.     }
  88.    
  89.  
  90. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top