PongMitDatenbank/src/package1/Game.java

134 lines
3.1 KiB
Java

package package1;
import java.awt.Color;
import java.awt.Font;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Game {
int timer1 = 0;
int timer2 = 0;
long lastT;
int lives = 3;
public void delay(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Game() throws SQLException {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
Player player = new Player(38, 40);
Wall Walls[] = new Wall[3];
Lives Lives[] = new Lives[3];
Ball ball = new Ball();
int score = 0;
JLabel scoreLabel = new JLabel();
Font f = new Font("TimesRoman", Font.BOLD, 25);
for (int i = 0; i < 3; i++) {
Walls[i] = new Wall(i);
Lives[i] = new Lives();
panel.add(Walls[i]);
panel.add(Lives[i]);
}
panel.add(player);
frame.addKeyListener(player);
scoreLabel.setText(Integer.toString(score));
scoreLabel.setForeground(new Color(255, 255, 255));
scoreLabel.setFont(f);
panel.add(scoreLabel);
panel.add(ball);
frame.setContentPane(panel);
frame.setSize(600, 700);
frame.setVisible(true);
frame.setTitle("Pong by Lenz and Tilman");
frame.setLocation(300, 10);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
panel.setBackground(Color.BLACK);
scoreLabel.setBounds(540, 300, 100, 100);
ball.setBounds(ball.getPosi('x', 0), ball.getPosi('y', 0), 10, 10);
panel.add(ball);
Lives[0].setBounds(25, 630, 18, 15);
Lives[1].setBounds(43, 630, 18, 15);
Lives[2].setBounds(62, 630, 18, 15);
for (int i = 0; i < 3; i++) {
Walls[i].setBounds(Walls[i].getPosi('x'), Walls[i].getPosi('y'), Walls[i].getSize('x'),
Walls[i].getSize('y'));
}
long dt;
player.setBounds(player.getPosi('x', 0), player.getPosi('y', 0), 10, 100);
//delay(3000);
lastT = System.nanoTime();
while (lives > 0) {
dt = System.nanoTime() - lastT;
lastT = System.nanoTime();
player.setBounds(player.getPosi('x', dt), player.getPosi('y', dt), 10, 100);
player.sonic();
ball.setBounds(ball.getPosi('x', dt), ball.getPosi('y', dt), 10, 10);
if (player.getPosi('x', 0) <= ball.getPosi('x', 0) + 10 && player.getPosi('y', 0) <= ball.getPosi('y', 0)
&& player.getPosi('y', 0) >= ball.getPosi('y', 0) - 100) {
ball.changeDir('x');
ball.setPosi('x', 560);
score++;
scoreLabel.setText(Integer.toString(score));
} else if (ball.getPosi('x', 0) < 20) {
ball.changeDir('x');
ball.setPosi('x', 20);
} else if (ball.getPosi('y', 0) > 640 || ball.getPosi('y', 0) < 20) {
ball.changeDir('y');
} else if (ball.getPosi('x', 0) > 570) {
Lives[lives - 1].setBounds(0, 0, 0, 0);
lives--;
if (lives == 0) {
frame.setVisible(false);
} else {
ball.setPosi('x', 300);
ball.setPosi('y', 350);
ball.setBounds(ball.getPosi('x', 0), ball.getPosi('y', 0), 10, 10);
delay(1000);
lastT = System.nanoTime();
}
}
ball.sonic();
delay(15);
}
frame.dispose();
@SuppressWarnings("unused")
GUI Gui = new GUI(score);
}
}