boxglue

Game.java

May 7th, 2021
671
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package testGame;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Dimension;
  5. import java.awt.Graphics;
  6. import java.awt.Graphics2D;
  7. import java.awt.RenderingHints;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.awt.event.KeyEvent;
  11. import java.awt.event.KeyListener;
  12. import javax.swing.JFrame;
  13. import javax.swing.JPanel;
  14. import javax.swing.Timer;
  15.  
  16. //Remove PUBLIC from everything except where it is really needed.
  17.  
  18. /* Trying to fix the lagging:
  19.  * The best way is to draw to a buffered image and then put that on the screen.
  20.  * You're then in total control of how fast the redraw happens
  21.  *
  22.  * What I'm doing here is reducing the speed of the ball.
  23.  * The ball speed is how many pixels it jumps each time it moves. The larger this is, the more jerky the movement.
  24.  * So if the speed is slower, then the move timer has to be faster (smaller milliseconds) to compensate.
  25.  * I think it's working a bit better, but I'm not sure.
  26.  */
  27.  
  28.  
  29. public class Game extends JFrame implements KeyListener {
  30.  
  31.     final static int SCREEN_WIDTH = 800;
  32.     final static int SCREEN_HEIGHT = 500;
  33.     Paddle player1, player2;
  34.     Ball ball = new Ball();
  35.     DrawPanel drawPanel;
  36.  
  37.     //I'm going to use a Timer instead of a thread because timers are simpler.
  38.     //However, I think that a thread can be adjusted easier to varying frame rate. I'd have to look into this.
  39.     private Timer moveTimer, repaintTimer;
  40.  
  41.  
  42.     Game() {
  43.         //PROBLEM: this sets the size of the JFRAME NOT the JPANEL.  
  44.         //All of the moving happens on the JPANEL so you need to use those coordinates.
  45.         //This is probably why your paddle goes off the bottom of the screen
  46.         //setSize(SCREEN_WIDTH, SCREEN_HEIGHT);//  See DrawPanel constructor  **
  47.  
  48.         /** 1. Set up game objects **/
  49.         //create the players for the left and right sides of the screen
  50.         player1 = new Paddle('L');
  51.         player2 = new Paddle('R');
  52.  
  53.         /** 2. Set up Jpanel **/
  54.         drawPanel = new DrawPanel();
  55.         add(drawPanel);
  56.         this.pack(); //needed for setting JPAnel size
  57.  
  58.         /** 3. Set up JFrame **/
  59.         //This has to be after the DrawPanel is created so that it is positioned correctly
  60.         //because we're setting the JPanel size precisely.
  61.         addKeyListener(this);
  62.         setResizable(false);
  63.         setLocationRelativeTo(null);
  64.         /* Always On Top --- interesting. I think that it would be better to do something to freeze
  65.           the game if the window stops being on top */
  66.         //setAlwaysOnTop(true);
  67.         //setLayout(null);  // I don't think that this is needed
  68.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  69.  
  70.         setVisible(true);
  71.  
  72.         //all timer stuff (start after window is shown)
  73.         moveTimer = new Timer(5, new TimerAL());
  74.         moveTimer.setInitialDelay(500);
  75.  
  76.         repaintTimer = new Timer(1,
  77.                 new ActionListener() {
  78.             public void actionPerformed(ActionEvent e)  {
  79.                 drawPanel.repaint();
  80.                 //drawPanel.paintImmediately(0,0,SCREEN_WIDTH, SCREEN_HEIGHT);
  81.             }
  82.         }
  83.                 );
  84.         repaintTimer.start();
  85.         moveTimer.start();
  86.         //moveTimer.setInitialDelay(0); //if we don't do this, then restarting the timer is delayed
  87.  
  88.     }
  89.  
  90.     // I'm making this an inner class. It's much easier to work with.
  91.     // You only have one JPanel so it's not a problem to put it here.
  92.     // We'll leave the keylistener on the JFrame since if you add it to a JPanel you have to repeatedly get the focus back
  93.     class DrawPanel extends JPanel {
  94.  
  95.         DrawPanel() {
  96.             this.setBackground(Color.BLACK);
  97.             //Set the size of the JPANEL (see note above **)
  98.             this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
  99.  
  100.             //This should never be here. Set it up in the main part of the program, where my Timers are being setup.
  101.             //Updater updater = new Updater(player1, this, ball);
  102.  
  103.             //I have no idea why this is here or needed.
  104.             //setBounds(0, 0, Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT);
  105.         }
  106.  
  107.         @Override
  108.         protected void paintComponent(Graphics g) {
  109.             super.paintComponent(g);
  110.             //drawBackground(g);  Delete this line. See below
  111.  
  112.             //make the lines smoother using AntiAliasing
  113.             Graphics2D g2 = (Graphics2D) g;
  114.             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  115.  
  116.             player1.draw(g);
  117.             player2.draw(g);
  118.             ball.draw(g);
  119.         }
  120.  
  121.         /* This is NOT needed.  Set the background colour to Black and then super.paintcomponent
  122.          * does this.  Why are you calling super.paintComponent() if not to draw the background?
  123.          */
  124.         //      void drawBackground(Graphics g) {
  125.         //          g.setColor(Color.black);
  126.         //          g.fillRect(0, 0, Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT);
  127.         //      }
  128.     }
  129.  
  130.     /**********************************************
  131.      * Event Listener Methods                     *
  132.      **********************************************/
  133.  
  134.     //You'll need to add keys for player2
  135.     @Override
  136.     public void keyTyped(KeyEvent e) {}
  137.  
  138.     @Override
  139.     public void keyPressed(KeyEvent e) {
  140.         if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP) {
  141.             player1.upAccel = true;
  142.         }
  143.         //ElSEIF is not needed. Only use it when you absolutely have to.
  144.         if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN) {
  145.             player1.downAccel = true;
  146.         }
  147.     }
  148.  
  149.     @Override
  150.     public void keyReleased(KeyEvent e) {
  151.         if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP) {
  152.             player1.upAccel = false;
  153.         }
  154.         if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN) {
  155.             player1.downAccel = false;
  156.         }
  157.     }
  158.  
  159.     /* I'm making a separate inner class for this because other things might also use an ActionListener
  160.      * for example, if you add a Pause button on the screen
  161.      */
  162.     private class TimerAL implements ActionListener {
  163.         @Override
  164.         public void actionPerformed(ActionEvent e) {
  165.  
  166.             player1.move();
  167.             player2.move();
  168.             ball.move();
  169.             ball.checkPlayerCollision(player1);
  170.             //ball.checkPlayerCollision(player2);
  171.  
  172.             //This has been moved to repaintTimer
  173.             //drawPanel.repaint();         
  174.         }
  175.  
  176.     }
  177.     //=========================================================//
  178.     public static void main(String[] args) {
  179.         //Game game = new Game();
  180.         //Make the game thread safe. This way all of the threads and timers will work together
  181.         javax.swing.SwingUtilities.invokeLater(new Runnable() {
  182.             @Override
  183.             public void run() {
  184.                 new Game();
  185.             }
  186.         });
  187.     }
  188. }
  189.  
  190.  
  191.  
  192.  
RAW Paste Data