122 lines
2.1 KiB
Java
122 lines
2.1 KiB
Java
import java.awt.event.KeyEvent;
|
|
import java.awt.event.KeyListener;
|
|
import java.util.Random;
|
|
|
|
import javax.swing.JFrame;
|
|
|
|
public class Ball extends JFrame implements KeyListener {
|
|
|
|
private static final long serialVersionUID = -629144081400642128L;
|
|
|
|
private float speed = 0.0000003f;
|
|
|
|
private double xPos = 300;
|
|
private double yPos = 300;
|
|
public int xSize = 100;
|
|
public int ySize = 100;
|
|
|
|
public boolean leftUp;
|
|
public boolean leftDown;
|
|
|
|
public boolean rightUp;
|
|
public boolean rightDown;
|
|
|
|
public boolean ballUp;
|
|
public boolean ballDown;
|
|
public boolean ballRight;
|
|
public boolean ballLeft;
|
|
|
|
Random rand;
|
|
|
|
public Ball() {
|
|
|
|
this.addKeyListener(this);
|
|
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
|
this.setVisible(true);
|
|
this.setResizable(false);
|
|
|
|
Random rand = new Random();
|
|
|
|
if (rand.nextBoolean()) {
|
|
ballRight = true;
|
|
} else {
|
|
ballLeft = true;
|
|
}
|
|
|
|
if (rand.nextBoolean()) {
|
|
ballUp = true;
|
|
} else {
|
|
ballDown = true;
|
|
}
|
|
|
|
}
|
|
|
|
public void keyTyped(KeyEvent e) {
|
|
|
|
}
|
|
|
|
public void keyPressed(KeyEvent e) {
|
|
if (e.getKeyCode() == 87) {
|
|
leftUp = true;
|
|
leftDown = false;
|
|
} else if (e.getKeyCode() == 83) {
|
|
leftDown = true;
|
|
leftUp = false;
|
|
}
|
|
if (e.getKeyCode() == 38) {
|
|
rightUp = true;
|
|
rightDown = false;
|
|
} else if (e.getKeyCode() == 40) {
|
|
rightDown = true;
|
|
rightUp = false;
|
|
}
|
|
delay(10);
|
|
}
|
|
|
|
public void keyReleased(KeyEvent e) {
|
|
|
|
if (e.getKeyCode() == 87) {
|
|
leftUp = false;
|
|
} else if (e.getKeyCode() == 83) {
|
|
leftDown = false;
|
|
}
|
|
|
|
if (e.getKeyCode() == 38) {
|
|
rightUp = false;
|
|
} else if (e.getKeyCode() == 40) {
|
|
rightDown = false;
|
|
}
|
|
|
|
}
|
|
|
|
public int getPos(char coordinate, long dt) {
|
|
|
|
if (coordinate == 'x') {
|
|
if (ballLeft) {
|
|
xPos -= speed * dt;
|
|
} else if (ballRight) {
|
|
xPos += speed * dt;
|
|
}
|
|
return (int) xPos;
|
|
} else if (coordinate == 'y') {
|
|
if (ballUp) {
|
|
yPos -= speed * dt;
|
|
} else if (ballDown) {
|
|
yPos += speed * dt;
|
|
}
|
|
return (int) yPos;
|
|
} else
|
|
return 0;
|
|
}
|
|
|
|
public void delay(int time) {
|
|
|
|
try {
|
|
Thread.sleep(time);
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
}
|