Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package gra;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.awt.event.MouseEvent;
- import java.awt.event.MouseMotionListener;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.Timer;
- @SuppressWarnings("serial")
- public class PongGame extends JPanel implements ActionListener, MouseMotionListener, KeyListener{
- public PongGame() {
- }
- private static Color kolorPilka = Color.ORANGE;
- private static Color kolorTlo = Color.DARK_GRAY;
- private static Color kolorPaleta = Color.RED;
- private boolean start = false;
- private int paletaX = 100;
- private int paletaY = 350;
- private int pilkaX = 0;
- private int pilkaY = 0;
- private int ballYSpeed = 5;
- private int ballXSpeed = 10;
- static PongGame game = new PongGame();
- static Timer timer = new Timer(100, game);
- protected void paintComponent(Graphics g){
- super.paintComponent(g);
- //tlo
- g.setColor(kolorTlo);
- g.fillRect(0, 0, 600, 400);
- //pilka
- g.setColor(kolorPilka);
- g.fillOval(pilkaX, pilkaY, 15, 15);
- //paletka
- g.setColor(kolorPaleta);
- g.fillRect(paletaX, paletaY, 150, 15);
- }
- public static void main(String args[]){
- JFrame jf = new JFrame();
- jf.setTitle("PongGame");
- jf.setSize(600, 400);
- jf.setVisible(true);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- jf.setResizable(false);
- jf.getContentPane().add(game);
- jf.addMouseMotionListener(game);
- jf.addKeyListener(game);
- jf.getContentPane().addKeyListener(new KeyAdapter() {
- @Override
- public void keyTyped(KeyEvent e) {
- }
- });
- }
- //NIE UZYWANE
- public void mouseDragged(MouseEvent e) {}
- public void actionPerformed(ActionEvent e) {
- pilkaX += ballXSpeed;
- pilkaY += ballYSpeed;
- if(pilkaX >= paletaX && pilkaX <= paletaX + 150 && pilkaY >= 400-60){
- ballYSpeed = -7;
- }
- if(pilkaY <= 0){
- ballYSpeed = 7;
- }
- if(pilkaX >= 600-20){
- ballXSpeed = -5;
- }
- if(pilkaX <= 0){
- ballXSpeed = 5;
- }
- if(pilkaY > 400-60){
- System.out.println("FAILED");
- timer.stop();
- //okno
- JFrame error = new JFrame("Przegrales!");
- error.setTitle("PRZEGRALES!");
- error.setVisible(true);
- error.setSize(300, 200);
- error.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- repaint();
- }
- public void mouseMoved(MouseEvent e) {
- paletaX = e.getX()-75;
- repaint();
- }
- public void keyPressed(KeyEvent e) {
- System.out.println(e.getKeyChar());
- if(e.getKeyChar()==KeyEvent.VK_ENTER){
- if(!start){
- start = true;
- timer.start();
- }
- }
- }
- public void keyReleased(KeyEvent arg0) {}
- public void keyTyped(KeyEvent arg0) {}
- }
Advertisement
Add Comment
Please, Sign In to add comment