Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.applet.Applet;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.Rectangle;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.util.ArrayList;
- public class Snake extends Applet implements KeyListener {
- long timeS = System.currentTimeMillis();
- private Rectangle rect;
- private ArrayList<Integer> keysDown;
- private boolean isUp;
- private boolean isDown;
- private boolean isLeft;
- private boolean isRight;
- public void init(){
- this.addKeyListener(this);
- keysDown = new ArrayList<Integer>();
- rect = new Rectangle(15, 15, 15, 15);
- }
- public void paint(Graphics g)
- {
- setSize(500, 500);
- Graphics2D g2 = (Graphics2D)g;
- g2.fill(rect);
- }
- public void timer(){
- long timeS = System.currentTimeMillis();
- while(true)
- {
- if(System.currentTimeMillis()>=timeS + 1000 * 1); //Change this value to however many seconds interval you want.
- {
- move();
- timeS = System.currentTimeMillis();
- }
- }
- }
- public void move() {
- if (this.isUp==true){
- rect.setLocation(rect.x, rect.y + 10);
- }
- if (this.isDown==true){
- rect.setLocation(rect.x, rect.y - 10);
- }
- if (this.isLeft==true){
- rect.setLocation(rect.x - 10, rect.y);
- }
- if (this.isRight==true){
- rect.setLocation(rect.x -10, rect.y);
- }
- }
- @Override
- public void keyTyped(KeyEvent e) {
- if (!keysDown.contains(e.getKeyCode()))
- keysDown.add(new Integer(e.getKeyCode()));
- moveRect();
- /*
- if (e.getKeyCode() == KeyEvent.VK_UP && this.isDown != true)
- {
- this.isUp = true;
- this.isDown = false;
- this.isLeft = false;
- this.isRight = false;
- }
- if (e.getKeyCode() == KeyEvent.VK_DOWN && this.isUp != true)
- {
- this.isUp = false;
- this.isDown = true;
- this.isLeft = false;
- this.isRight = false;
- }
- if (e.getKeyCode() == KeyEvent.VK_LEFT && this.isRight != true)
- {
- this.isUp = false;
- this.isDown = false;
- this.isLeft = true;
- this.isRight = false;
- }
- if (e.getKeyCode() == KeyEvent.VK_RIGHT && this.isLeft != true)
- {
- this.isUp = false;
- this.isDown = false;
- this.isLeft = false;
- this.isRight = true;
- }*/
- }
- @Override
- public void keyPressed(KeyEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void keyReleased(KeyEvent e) {
- keysDown.remove(new Integer(e.getKeyCode()));
- }
- public void moveRect()
- {
- int x = rect.x;
- int y = rect.y;
- if (keysDown.contains(KeyEvent.VK_UP))
- y -= 15;
- if (keysDown.contains(KeyEvent.VK_DOWN))
- y += 15;
- if (keysDown.contains(KeyEvent.VK_LEFT))
- x -= 15;
- if (keysDown.contains(KeyEvent.VK_RIGHT))
- x += 15;
- rect.setLocation(x,y);
- repaint();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment