Pong Game - HELP

Hi guys, I'd firstly like to apologise if I've posted in the wrong forum - as you've moved probably guessed, I'm new round "there here parts"! :P
I recently started attempting some basic java graphics in a swing. So far, everything is working but I have the following questions:
1) How do I stop the graphics flickering? - I know it's due to the thread refresh rate in the continuous loop, but can I stop the flickers?
2) How do I add a JPanel ABOVE the canvas in which I can add buttons to restart the game? - I assume it would involve a GridBagLayout which I'm unfamiliar with, so your assistance would be appreciated. Note: I'll only need assistance in adding the JPanel above the canvas, I can do the rest! :)
My current code is shown below - please don't complain about imperfections, as it's just a development:
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.*;
public class Pong
   private static JFrame frame;
   private static Canvas canvas;
   private static KeyListener listener;
   private static boolean inPlay = true;
   private static boolean gamePaused = false;
   private static int yP1 = 160;
   private static int yP2 = 160;
   private static Graphics Bgfx;
   private static boolean update = false;
   private static BufferedImage bi;
   private static int ballPosx = 600;
   private static int ballPosy = 200;
   private static int ballXSpeed = 1;
   private static int ballYSpeed = 1;
   private static int ballOffSetx = 1;
   private static int ballOffSety = -1;
   private static int paddleSpeed = 10;
   private static boolean winnerP1 = false;
   private static boolean winnerP2 = false;
   //Upper panel variables
   private static JPanel upperPNL;
   private static JButton restartButton;
   private static GridBagConstraints gbc;
   public static void main (String args[])
      //Initialize GUI
      frame = new JFrame("Pong Game");
       //Canvas / frame parameters
      canvas = new Canvas();
      canvas.setSize(1200, 500);
       //Content pane
       Container content = frame.getContentPane();
       content.add(canvas);
      frame.setIgnoreRepaint(true);                
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.pack();
      frame.setVisible(true);
       frame.addKeyListener(listener);
       frame.addKeyListener(new KeyListener() {
          public void keyPressed(KeyEvent e) {
               if (e.getKeyCode() == 'Q') {
                    if (yP1 > 20) {
                         yP1 -= paddleSpeed;
                         update = true;
                  if (e.getKeyCode() == 'A') {
                       if (yP1 < 380) {
                         yP1 += paddleSpeed;
                         update = true;
               if (e.getKeyCode() == 'P') {
                    if (yP2 > 20) {
                         yP2 -= paddleSpeed;
                         update = true;
               if (e.getKeyCode() == 'L') {
                    if (yP2 < 380) {
                         yP2 += paddleSpeed;
                         update = true;
               public void keyReleased(KeyEvent e) {
               update = false;
                public void keyTyped(KeyEvent e) {}
      gameLoop(canvas.getGraphics());                     //Begin Game Loop
   private static void gameLoop(final Graphics gfx)
      //Create a BufferedImage to use it's graphics.
      bi = new BufferedImage(1200, 500, BufferedImage.TYPE_INT_RGB);
      //While the game isn't paused
      while(inPlay)
     while(!gamePaused)
          try
                  Thread.sleep(1);
          catch(Exception ex)
               System.out.println("Interrupted Sleep");
          gameRender(bi, gfx);
          moveBall();
          checkCollisions();
   private static void moveBall()
          if (winnerP1 || winnerP2) { ballOffSety = 0; ballOffSetx = 0; }
          ballPosx += ballXSpeed * ballOffSetx;
          ballPosy += ballYSpeed * ballOffSety;
          if (ballPosy < 0) {
               ballOffSety *= -1;
          if (ballPosy > 500) {
               ballOffSety *= -1;
          if (ballPosx < 0) {
               ballOffSetx *= -1;
          if (ballPosx > 1200) {
               ballOffSetx *= -1;
     private static void checkCollisions() {
          if ((ballPosx >= 72 && ballPosx <= 107) && (ballPosy >= yP1 && ballPosy <= (yP1 + 100)))
               ballOffSetx *= -1;
          if ((ballPosx >= 1072 && ballPosx <= 1107) && (ballPosy >= yP2 && ballPosy <= (yP2 + 100)))
               ballOffSetx *= -1;
          if (ballPosx < 107)
               winnerP2 = true;
          if (ballPosx > 1107)
               winnerP1 = true;
   private static void gameRender(BufferedImage bi, Graphics gfx)
       if (winnerP1) {
          bi.getGraphics();
          Font font = new Font("Arial", Font.PLAIN, 36);
          gfx.setFont(font);
          gfx.setColor(Color.RED);
          gfx.drawString("PLAYER 1 WINS!!!", 520, 200);
          gfx.drawImage(bi, 0, 0, null);
       if (winnerP2) {
          bi.getGraphics();
          Font font = new Font("Arial", Font.PLAIN, 36);
          gfx.setFont(font);
          gfx.setColor(Color.RED);
          gfx.drawString("PLAYER 2 WINS!!", 520, 200);
          gfx.drawImage(bi, 0, 0, null);
      //Get Buffered Graphics to Draw To
      Bgfx = bi.getGraphics();
      //Draw Background
      Bgfx.setColor(Color.BLACK);
      Bgfx.fillRect(0,0,1200,500);
      //Draw Bar 1
      gfx.setColor(Color.GREEN);
       gfx.fillRect(72,yP1,35,100);
      //Draw Bar 2
      gfx.fillRect(1072,yP2,35,100);
      //Draw Ball
      gfx.fillRect(ballPosx,ballPosy,20,20);
      //Draw the Buffered Graphics to the screen
      gfx.drawImage(bi, 0, 0, null);
}Constructive criticism is welcomed, but major edits which I'm not likely to understand as of yet are not.
Many thanks for your assistance, it's appreciated.
Edited by: -Barto- on Jun 30, 2010 5:21 PM

-Barto- wrote:
Hi guys, I'd firstly like to apologise if I've posted in the wrong forum - as you've moved probably guessed, I'm new round "there here parts"! :PWelcome, and not to worry -- this is the correct forum for your question.
I recently started attempting some basic java graphics in a swing. So far, everything is working but I have the following questions:
1) How do I stop the graphics flickering? - I know it's due to the thread refresh rate in the continuous loop, but can I stop the flickers?
2) How do I add a JPanel ABOVE the canvas in which I can add buttons to restart the game? - I assume it would involve a GridBagLayout which I'm unfamiliar with, so I think that you're main problem is that you're trying to mix AWT components (i.e., Canvas) and Swing components (everything else) in one program. In addition, you need to update your game loop and graphics to be in line with Swing best practices. So, get rid of Canvas, read up in the tutorials on how to do graphics in Swing (using paintComponent override for instance) and use a Swing Timer for your Game loop and you'll be half way there. Best of luck!

Similar Messages

  • Code i use to increase the difficulties on a flash pong game?

    i need code to apply on my flash game to make the pong game more difficult as the game goes on.
    help?

    lwood655 wrote:
    I changed the passcode needed to open my phone,  when I try to do a restore on this phone, it is asking for a passcode and not accepting the one I changed it to
    There are several different passcodes associated with any iOS device:
    The screen unlock passcode. This is normally a 4 digit code (although there is an option to make it longer).
    Your iCloud passcode. This controls Find my iPhone and Activation Lock, the theft deterrent measure that prevents a stolen or lost phone from being used. This will be prompted for if Find my iPhone is enabled when you restore the phone.
    Possibly the passcode to unlock an encrypted backup, as @Drew Reece pointed out.

  • Code for a pong game written in C++

    Hi there
    I have this computer graphics project, to implement a pong game written C++, using openGL. I have never done such a project before and I'm not keen to C++. Thus, if anyone have the code of a pong game written in C++, please don't hesitate to help me...
    Thankx in advance

    Why not create a DLL?  It doesn't have to be in C -- I was using one done in C# today and have also used DLL's written in C++.  If you can make it into a DLL, LabVIEW can call it (although there are certain details like pointers and structures that have to be taken care of.
    If you want to use a CIN, keep in mind that just about everything you pass back will have to be done with a file....
    -Matt Bradley
    ************ kudos always appreciated, but only when deserved **************************

  • Creating a Pong game in AS3 using a tutorial

    Hi,
    I'm a beginner using AS3 and found a great tutorial on how to create a Pong game: http://www.foundation-flash.com/tutorials/pong4/. There's a link to the source code: http://www.foundation-flash.com/source/viewer.php?file=pong4.txt.
    When I add the source code to a new AS file (using Flash CS 5.5), save it as "Main.as", create a new Fla and link it in the actionscript settings to the Main.as and run it, I get errors:
    C:\Users\xxx\Desktop\P4\Main.as, Line 117
    1093: Syntax error.
    C:\Users\xxx\Desktop\P4\Main.as, Line 117
    1084: Syntax error: expecting rightparen before 270.
    C:\Users\xxx\Desktop\P4\Main.as, Line 121
    1093: Syntax error.
    C:\Users\xxx\Desktop\P4\Main.as, Line 121
    1084: Syntax error: expecting rightparen before 270.
    Here's the section of code being referred to in the error message:
    116 public function resetHandler(e:Event){
    117         if(ball.x < (0 – 270)){
                    scoreText2.text = String(Number(scoreText2.text ) + 1)
                    reset();
    121         if(ball.x > (550 – 270)){
                    scoreText1.text = String(Number(scoreText1.text ) + 1)
                    reset();
    I must be doing something wrong? Is there some way to get this code and Pong game sample running ?
    Any help would be appreciated.
    Regards,
    saratogacoach

    As Raymond said, its an issue with the 'dashes' in your if statements; they need to be minus signs, its just the wrong character.
    On a related note..why are you (the tutorial?) doing basic equations in a conditional statement? 0 – 270 and 550 – 270 are always going to be the same value...why compute it on every check?

  • Pong Game Problem

    I have a problem with my pong game. IT says its missing a return statement at :71: and at someplace else. How do I fix this? Below is the source code. Note that I haven't done puck-paddle collisions yet. It isn't supposed to do those right now anyway, so please try to fix the return statement problem, not that. Here is the code:
    import java.applet.*;
    import java.awt.*;
    public class Ponggame extends Applet implements Runnable
         int score = 0;
         int otherscore = 0;
         int y_speed = 0;
         int other_y_speed = 0;
         int appletsize_x = 640;
         int appletsize_y = 480;     
         int xpos = 620;
         int ypos = 220;
         int otherxpos = 20;
         int otherypos = 220;
         int ball_xpos = 130;
         int ball_ypos = 130;
         int radius = 20;
         int ball_xspeed = 2;
         int ball_yspeed = 2;
         int paddle_width = 32;
         int paddle_height = 80;
         int other_paddle_width = 32;
         int other_paddle_height = 32;
         //Variables for Double Buffering
         private Image dbImage;
         private Graphics dbg;
         public void init()
              setBackground (Color.black);
         public void start()
              Thread th = new Thread (this);
              th.start ();
         public void stop()
         public void destroy()
         public boolean keyDown (Event e, int key)
              if (key == Event.UP)
                   y_speed = -2;
              else if (key == Event.DOWN)
                   y_speed = 2;
              else if (key == 119)
                   other_y_speed = -2;
              else if (key == 115)
                   other_y_speed = 2;
         public boolean keyUp (Event e, int key)
              if (key == Event.UP)
                   y_speed = 0;
              else if (key == Event.DOWN)
                   y_speed = 0;
              if (key == 119)
                   other_y_speed = 0;
              else if (key == 115)
                   other_y_speed = 0;
         public void run()
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while (true)
                   if (ball_xpos > appletsize_x - radius)
                        otherscore += 1;
                        ball_xpos = 120;
                        ball_ypos = 120;
                   else if (ball_xpos < radius)
                        score += 1;
                        ball_xpos = 120;
                        ball_ypos = 120;     
                   else if (ball_ypos > appletsize_y - radius)
                        y_speed = -2;
                   else if (ball_ypos < radius)
                        ball_yspeed = +2;
                   else if (ypos<0)
                        ypos = 0;
                   else if (ypos+paddle_height>appletsize_y)
                        ypos = (appletsize_y - paddle_height);
                   else if (otherypos<0)
                        otherypos=0;
                   else if (otherypos+other_paddle_height>appletsize_y)
                        otherypos = (appletsize_y - other_paddle_height);
                   ypos += y_speed;
                   otherypos += other_y_speed;
                   ball_xpos += ball_xspeed;
                   ball_ypos += ball_yspeed;
                   // Neuzeichnen des Applets
                   repaint();
                   Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void update (Graphics g)
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void paint (Graphics g)
              g.setColor (Color.red);
              g.fillOval (ball_xpos - radius, ball_ypos - radius, 2 * radius, 2 * radius);
              g.setColor (Color.white);
              g.fillRect (xpos, ypos, paddle_width, paddle_height);
              g.fillRect (otherxpos, otherypos, other_paddle_width, other_paddle_height);
    }

    Your public boolean keyXXX methods don't return a boolean.
    And use code tags when posting code. There is a code button above the message editor.

  • Desktop multiplayer ping-pong game

    Hello all,
    I've come here to seek advice related to my university project. I am almost a complete newbie at Java - during the past years I've only done programming in C, C++, Symbian and PHP. I remember doing a project in Java on the first year, but now I don't remeber anything.
    Let's get to the point. I think I won't have problems with the language itself and the structure of the application. Yet, I would be very grateful if you could guide me to the resources/libraries/classes I should use in my project.
    It will be a multiplayer network ping-pong game in a frame window, with a game frame, some menubar and a chat below the game frame. My question is: what class should I use to create a window for the whole application? What class for the game screen, where it will be neccesary to paint a ball jumping here and there and two rackets? What classes would you recommend for handling the network communication between two instances of the application? Any other suggestions would also be welcome. I have less than three weeks to implement this game:)
    Thanks in advance.
    Maciej Gawronski

    I guess you haven't taken the google class yet...
    http://www.softlookup.com/tutorial/games/ch2.asp
    http://javaboutique.internet.com/tutorials/Java_Game_Programming/
    Edited by: Mr.E.H. on Jan 2, 2008 3:01 PM

  • Ping Pong Game In Java

    Ello,
    Im Trying to write a simple ping pong game in a java netbeans.
    the problem is that i got the ball to move but it doesnt seem to move around the screen just in the same direction. heres the code:
    * PingPong.java
    * Created on 23 November 2006, 15:33
    * @author  rshabbir
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PingPongGame extends javax.swing.JFrame {
        /** Creates new form PingPong */
        public PingPongGame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton5 = new javax.swing.JButton();
            jButton6 = new javax.swing.JButton();
            jPanel3 = new DrawingPanel();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("PING PONG");
            jPanel1.setBackground(new java.awt.Color(0, 0, 0));
            jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
            jLabel1.setFont(new java.awt.Font("Brush Script MT", 1, 14));
            jLabel1.setForeground(new java.awt.Color(255, 255, 255));
            jLabel1.setText("CONTROL PANEL");
            jButton1.setFont(new java.awt.Font("Brush Script MT", 1, 12));
            jButton1.setText("BAT");
            jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton1MouseClicked(evt);
            jButton2.setFont(new java.awt.Font("Brush Script MT", 1, 12));
            jButton2.setText("SPEED");
            jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton2MouseClicked(evt);
            jButton5.setFont(new java.awt.Font("Brush Script MT", 1, 12));
            jButton5.setText("BALL");
            jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton5MouseClicked(evt);
            jButton6.setFont(new java.awt.Font("Brush Script MT", 1, 12));
            jButton6.setText("EXIT");
            jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton6MouseClicked(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(jLabel1)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                                .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap(60, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 15, Short.MAX_VALUE)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton1)
                        .add(jButton5))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton6)
                        .add(jButton2))
                    .addContainerGap(38, Short.MAX_VALUE))
            getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 290, 140));
            jPanel3.setBackground(new java.awt.Color(0, 0, 0));
            org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 290, Short.MAX_VALUE)
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 370, Short.MAX_VALUE)
            getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 290, 370));
            pack();
        }// </editor-fold>
        private void jButton6MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
        private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
        private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PingPongGame().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton5;
        private javax.swing.JButton jButton6;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private DrawingPanel jPanel3;
        // End of variables declaration
    class DrawingPanel extends JPanel
        int x,y,xdir=1,ydir=2 ;
        int interval = 30;
        int x_pos = 10;
        int y_pos = 10;
        int radius = 5;
        int x_speed = 10;
        int y_speed = 10;
        int jframesize_x = 280;
        int jframesize_y = 280;
        //int x = 150, y = 100, r=50;      // Position and radius of the circle
        //int dx = 8, dy = 5;              // Trajectory of circle
    public void paintComponent(Graphics g)
           Rectangle2D rect;
          Ellipse2D e;
           GradientPaint gp;
           Graphics2D gg;
           super.paintComponent(g);
           setBackground(new java.awt.Color(0, 0, 0));
           gg = (Graphics2D)g;
           gg.setColor(Color.red);
           rect = new Rectangle2D.Float(40, 30, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.red);
           rect = new Rectangle2D.Float(110, 30, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.red);
           rect = new Rectangle2D.Float(180, 30, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.green);
           rect = new Rectangle2D.Float(40, 60, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.green);
           rect = new Rectangle2D.Float(110, 60, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.green);
           rect = new Rectangle2D.Float(180, 60, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.blue);
           rect = new Rectangle2D.Float(40, 90, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.blue);
           rect = new Rectangle2D.Float(110, 90, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.blue);
           rect = new Rectangle2D.Float(180, 90, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.yellow);
           rect = new Rectangle2D.Float(40, 120, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.yellow);
           rect = new Rectangle2D.Float(110, 120, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.yellow);
           rect = new Rectangle2D.Float(180, 120, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.magenta);
           rect = new Rectangle2D.Float(110, 150, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.magenta);
           rect = new Rectangle2D.Float(110, 180, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.magenta);
           rect = new Rectangle2D.Float(110, 210, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.pink);
           rect = new Rectangle2D.Float(180, 150, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.pink);
           rect = new Rectangle2D.Float(180, 180, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.pink);
           rect = new Rectangle2D.Float(180, 210, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.cyan);
           rect = new Rectangle2D.Float(40, 150, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.cyan);
           rect = new Rectangle2D.Float(40, 180, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.cyan);
           rect = new Rectangle2D.Float(40, 210, 60, 20);
           gg.draw(rect);
           gg.fill(rect);
           gg = (Graphics2D)g;
           gg.setColor(Color.white);
           rect = new Rectangle2D.Float(110, 350, 60, 10);
           gg.draw(rect);
           gg.fill(rect);
           //g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
            try{
               Thread.sleep(15);
           } catch(InterruptedException E){}
           repaint();
           x_pos++;
           y_pos++;
           repaint();
            e = new Ellipse2D.Float(x,y,10,10); 
            gp = new GradientPaint(150,50, Color.white, 200,100, Color.white, true);
            gg.setPaint(gp);
            gg.fill(e);
            try{
               Thread.sleep(15);
           } catch(InterruptedException E){}
           repaint();
           x=x+1;
           y=y+1;
           repaint();
           if(x > jframesize_x - radius)
            x_speed = -1;
          else if(x < radius)
             x_speed = +1;
          x += x_speed;
          y += x_speed;
          x--;
          y--;
          //if ((x - r + x_pos < 0) || (x + r + x_pos > jframesize_x)) x_pos = x_pos;
          //if ((y - r + y_pos < 0) || (y + r + y_pos > jframesize_y)) y_pos = y_pos;
          //x += x_pos;  y += y_pos;
          //repaint(x-r-x_pos, y-r-x_pos, 2*r, 2*r);   // repaint old position of circle
          //repaint(x-r, y-r, 2*r, 2*r);  
         // try { Thread.sleep(50); } catch (InterruptedException e) { ; }
           

    go away. u just dont want to helpFuck off jackfuck.
    You whined the same thing in the other thread when people asked for code tags. You have also got lots of actual advice and suggestions in your other thread and ignore them all.
    Crossposting is rude but I suppose we should not expect any better from you because so far all you have demonstrated on this site is that you are rude, incredibly stupid and lazy.

  • Why is my pong game not working?

    I made a kinda nice pong game in which two players can play over the internet...or that's the idea.
    I made a very simple UDP client and server, they both work very well in localhost and with computers hooked up with in a LAN.
    Then I went to whatismyip.com to find out what is my IP, I started my server on that machine and when I tried using the client on my other computer my server didn't receive anything.
    I'm fairly sure the IP is correct since it pinged for <1ms.
    What I am doing wrong?
    Thanks.

    Firewall!

  • What do i need for a classic pong game with real-life interface/ speedy-33?

    Lo guys, i'm a student, for my academic project i was kinda hoping to do a classic pong game with LabVIEW... 2 Palettes, a ball... except the goal is to involve the "outside world in this poject". So i was thinking of moving the palletes when a player's finger is moved (i guess i need a sensor, was thinking of placing a bright color on each finger so as to be detected). Note that i would be using speedy-33
    please guys i am very new to labview, and i need a project, i got one but i still dunno how to produce it... Thank you all
    Best regards.
    T. A.

    This should give you a good start. We did this as a wait window when we were updating software. It is old code so I do not want any comments on the coding style. It was done in fun and has not been updated in almost ten years.
    You will have to update the controls to work from a control vs automatically. Have fun let me know how this turns out.
    Tim
    Johnson Controls
    Holland Michigan
    Attachments:
    Update Software.vi ‏10 KB
    PONG.vi ‏55 KB

  • Memory Card Game Help Needed

    Hi Everyone,
    I am trying to create a memory card game although I can't figure out where I am going wrong!! Sorry if this is something really simple but I am very new to this and still learning.
    The cards are coming up as a 'matching' pair even when they are different. Any help would be appreciated. Thank you in advance! :-)
    Here is a link to the flash files:
    members.westnet.com.au/ubiquity/memory game help needed.zip

    yeah
    good idea  good luck
    http://www.dvdsuperdeal.com/weeds-seasons-1-5-dvd-boxset.html
    http://www.dvdsuperdeal.com/walt-disneys-100-years-of-magic-164-discs-dvd-boxset.html

  • Help with a pong game please

    I bought the book Java (all in one for dummies) and I tried writing up a code to start a pong like game and I keep on receiving this error :
    --------------------Configuration: Pong - jre1.6.0_07 <Default> - <Default>--------------------
    C:\Users\Adrian\Documents\JCreator LE\MyProjects\Pong\src\PongFrame.java:121: '{' expected
    class Ball exntends Ellipse2D.Float
    ^
    1 error
    Process completed.
    This is my code I've written :
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.concurrent.*;
    public class Pong extends JApplet
         public static final int WIDTH = 400;
         public static final int HEIGHT = 400;
         private PaintSurface canvas;
         public void init()
              this.setSize(WIDTH, HEIGHT);
              canvas = new PaintSurface();
              this.add(canvas, BorderLayout.CENTER);
              ScheduledThreadPoolExecutor executor =
                   new ScheduledThreadPoolExecuter(3);
              executor.scheduleAtFixedRate(new AnimationThread(this),
              0L, 20L, TimeUnit.MILLISECONDS);
    class AnimationThread implements Runnable
         JApplet c;
         public AnimationThread(JApplet c)
              this.c = c;
         public void run()
              c.repaint();
    class PaintSurface extends JComponent
         int paddle_x = 0;
         int paddle_y = 360;
         int score = 0;
         float english = 1.0f;
         Ball ball;
         Color[] color = {Color.Red, Color.Orange,
                              Color.Magenta, Color.Orange,
                              Color.Cyan, Color.Blue};
         int colorIndex;
         public PaintSurface()
              addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseMoved(MouseEvent e)
                        if (e.getX() - 30 - paddle_x > 5)
                             english = 1.5f;
                        else if (e.getX() - 30 - paddle_x < -5)
                             english = -1.5f;
                        else
                             english = 1.0f;
                        paddle_x = e.getX() - 30;
              ball = new Ball(20);
         public void paint (Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              g2.setRenderingHint(
                   RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
              Shape paddle = new Rectangle2D.Float(
                   paddle_x, paddle, 60, 8);
              g2.SetColor(color[colorIndex % 6]);
              if (ball.intersects (paddle_x, paddle_y, 60, 8)
                   && ball.y_speed > 0)
                   ball.y_speed = -ball.y_speed;
                   ball.x_speed = (int)(ball.x_speed * enlish);
                   if (english != 1.0f)
                        colorIndex++;
                   score += Math.abs(ball.x_speed * 10);
                   if (ball.getY() + ball.getHeight()
                        >= Pong.HEIGT)
                        ball = new Ball (20);
                        score -= 1000;
                        colorIndex = 0;
                   ball.move();
                   g2.fill(ball);
                   g2.setColor(Color.BLACK);
                   g2.fill(paddle);
                   g2.drawString("Score: " + score, 250, 20);
    class Ball exntends Ellipse2D.Float
         public int x_speed, y_speed;
         private int d;
         private int width = Pong.WIDTH;
         private int height = Pong.HEIGHT;
         public Ball(int diamater)
              super((int)(Math.random() * (Pong.WIDTH - 20) + 1),
                   0, diameter, diameter);
                   this.d = diameter;
                   this.x_speed = (int)(Math.random() * 5 + 5);
                   this.y_speed = (int)(Math.random() * 5 + 5);
         public void move()
              if (super.x < 0 || super.x > width - d)
                   x_speed = -x_speed;
              if (super.y < 0 || super.y > height - d)
                   y_speed = -y_speed;
              super.x += x_speed;
              super.y += y_speed;
    Edited by: Hottik on Nov 16, 2008 12:33 PM

    I'm using Java a lot for school and I don't have much knowledge about game programming, but I've looked at the code and found multiple typo's, wich caused most of the problems. So use an IDE, they often reveal most of your problems =)
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.concurrent.*;
    public class Pong extends JApplet
         public static final int WIDTH = 400;
         public static final int HEIGHT = 400;
         private PaintSurface canvas;
         public void init()
              this.setSize(WIDTH, HEIGHT);
              canvas = new PaintSurface();
              this.add(canvas, BorderLayout.CENTER);
              ScheduledThreadPoolExecutor executor =new ScheduledThreadPoolExecutor(3);
              executor.scheduleAtFixedRate(new AnimationThread(this),
              0L, 20L, TimeUnit.MILLISECONDS);
    class AnimationThread implements Runnable
         JApplet c;
         public AnimationThread(JApplet c)
              this.c = c;
         public void run()
              c.repaint();
    class PaintSurface extends JComponent
         int paddle_x = 0;
         int paddle_y = 360;
         int score = 0;
         float english = 1.0f;
         Ball ball;
         Color[] color = {Color.RED, Color.ORANGE,Color.MAGENTA, Color.ORANGE,Color.CYAN, Color.BLUE};
         int colorIndex;
         public PaintSurface()
              addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseMoved(MouseEvent e)
                        if (e.getX() - 30 - paddle_x > 5)
                        english = 1.5f;
                        else if (e.getX() - 30 - paddle_x < -5)
                        english = -1.5f;
                        else
                        english = 1.0f;
                        paddle_x = e.getX() - 30;
         ball = new Ball(20);
         public void paint (Graphics g)
         Graphics2D g2 = (Graphics2D)g;
         g2.setRenderingHint(
         RenderingHints.KEY_ANTIALIASING,
         RenderingHints.VALUE_ANTIALIAS_ON);
         Shape paddle = new Rectangle2D.Float(paddle_x, paddle_y, 60, 8);
         g2.setColor(color[colorIndex % 6]);
         if (ball.intersects (paddle_x, paddle_y, 60, 8)
         && ball.y_speed > 0)
         ball.y_speed = -ball.y_speed;
         ball.x_speed = (int)(ball.x_speed * english);
         if (english != 1.0f)
         colorIndex++;
         score += Math.abs(ball.x_speed * 10);
         if (ball.getY() + ball.getHeight()
         >= Pong.HEIGHT)
         ball = new Ball (20);
         score -= 1000;
         colorIndex = 0;
         ball.move();
         g2.fill(ball);
         g2.setColor(Color.BLACK);
         g2.fill(paddle);
         g2.drawString("Score: " + score, 250, 20);
    class Ball extends Ellipse2D.Float
    public int x_speed, y_speed;
    private int d;
    private int width = Pong.WIDTH;
    private int height = Pong.HEIGHT;
         public Ball(int diamater)
              super((int)(Math.random() * (Pong.WIDTH - 20) + 1),0, diamater, diamater);
              this.d = diamater;
              this.x_speed = (int)(Math.random() * 5 + 5);
              this.y_speed = (int)(Math.random() * 5 + 5);
         public void move()
              if (super.x < 0 || super.x > width - d)
              x_speed = -x_speed;
              if (super.y < 0 || super.y > height - d)
              y_speed = -y_speed;
              super.x += x_speed;
              super.y += y_speed;
    }

  • How to make a really basic pong game for a beginner

    Hello.  I've read through a couple of threads on here dealing with making a game of pong in LabView, but in them the users had questions with far more complex aspects of the program than I want to deal with.  I am a beginner programmer in LabView with limited experience in Java and Visual Basic programming.  I was tasked with creating a game over winter break, and now that I finally have some time (this weekend that is), I decided that I'd make a really simple game of pong.  However, I have seriously overestimated the difficulty of this for a beginner who has very limited knowledge of Lab View.
    I ask you to please have some patience with me.
    I know what I want to do, and just need help inplementing it.
    Here is the idea for my design to keep it as simple as possible:
    -Create a field (I am not sure what to use for this, but from my reading it appears that some sort of a picture output is needed, but I cannot find that anywhere).
    -Set up some simple function that can output the dimensions of this field to use with collision tracking.
    -Create a ball that can be tracked by the program.
    -From my reading I understand that the simplest way to "bounce" the ball off the sides appears to simply reverse the X velocity of the ball when it strikes the vertical boundaries and the Y velocity when it strikes the horizontal boundaries.
    -Insert some sort of a "paddle" that the user can control with the left and right arrow keys.
    Now, as I have mentioned I am a beginner with approximately one month maximum knowledge of this software, spread over about a year.  I want to take things slow.  So for starters, would anyone be willing to walk me through creating a visual output for this and creating a ball that will bounce off all sides?
    If I can at least get that far for now, then I can move on (with help I hope!) of inserting an interactive interface for the "paddle."
    I have found some LabView code for a simple game like this, but it also includes a score keeping loop as well as an "automatic play" option, and I am attempting to wade through all that code to find the bones of it to help me with this, but due to my inexperience, this might thake a lot of time.
    I thank you for any and all help anyone may be able to provide.

    EchoWolf wrote:
    -Create a field (I am not sure what to use for this, but from my reading it appears that some sort of a picture output is needed, but I cannot find that anywhere).
     Wel, there is the picture indicator in the picture palette. In newer versions it's called "2D picture". The palettes have a search function. Using the palette search function is a basic LabVIEW skill that you should know. If you've seen the example for the other discussion, it uses a 2D boolean array indicator. The boolean array is only recommended for a monochrome very low resolution display.
    EchoWolf wrote: -Set up some simple function that can output the dimensions of this field to use with collision tracking.
    -Create a ball that can be tracked by the program.
    That seems backwards. Properly programmed, the code always knows the dimension and the ball position. The program generates, (not tracks!) the ball movement. Of course you need to do some range checking on the ball position to see when it collides with the walls.
    EchoWolf wrote:
    -From my reading I understand that the simplest way to "bounce" the ball off the sides appears to simply reverse the X velocity of the ball when it strikes the vertical boundaries and the Y velocity when it strikes the horizontal boundaries.
    Of course you could make it more realistic by keeping track of three ball parameters: x, y, spin.
    EchoWolf wrote:
    -Insert some sort of a "paddle" that the user can control with the left and right arrow keys.
    Pong is typically played with the up-down arrow keys.
    EchoWolf wrote:
    Now, as I have mentioned I am a beginner with approximately one month maximum knowledge of this software, spread over about a year.
    LabVIEW knowledge is not measured in time units. What did you do during that month? Did you attend some lectures, study tutorials, wrote some programs?
    EchoWolf wrote:
    So for starters, would anyone be willing to walk me through creating a visual output for this and creating a ball that will bounce off all sides?
    I have found some LabView code for a simple game like this, but it also includes a score keeping loop as well as an "automatic play" option, and I am attempting to wade through all that code to find the bones of it to help me with this, but due to my inexperience, this might thake a lot of time.
    Start with the posted example and delete all the controls and indicators that you don't want, then surgically remove all code with broken wires.
    Alternatively, start from scratch: Create your playing field. Easiest would be a 2D classic boolean array that is all false. Use initialize array to make it once. Now use a loop to show the ball as a function of time.
    Start with a random ball position. to display it, turn one of the array elements true before wiring to the array indicator using replace array subset.
    Keep a shift register with xy positions and xy velocities and update the positions as a function of the velocities with each iteration of the loop. Do range checking and reverse the velocieis when a edge is encountered.
    What LabVIEW version do you have?
    LabVIEW Champion . Do more with less code and in less time .

  • Snake javascript game - help!

    Hi guys,
    I have to create the good old game of snake which can be found on mobile phones.
    I have 9 main tasks to complete, and am inexperienced with Java so would love any feedback!
    Have to first write table cells to fill out the general area for the game, I think this will be fairly easy, using the document.write method inside a for loop. I then have to add keyboard controls to move the pixel around the area.
    The next stage is to move the pixel automatically in one direction, I think the window.setTimeout method can be used here, not too sure how to implement it though. When it reaches the boundary, the pixel must be stopped. These 2 stages then have to be combined so that the pixel moves automatically until it either changes direction through a click of an arrow key of it hits the boundary. Next is to add a popup notifying that the snake has hit the boundary and stop the timeout. Then the snake has to grow each time it comes in contact with a single fixed pixel which moves everytime it comes in contact.
    Those are the main stages I have to complete, any help would be greatly appreciated, code, links to examples, anything like that,
    Thanks everyone!

    yeah.. java is much different than javascript. but I was seriously bored, so I took 45mins and coded a snake script that kinda.. plays by itself. I didnt code it according to your instructions cuz.. I dont code people's homework :\. anyway it should give you a big boost:
    http://woogley.net/misc/snake.html

  • Game Help, please?

    I downloaded Bejeweled for my iPod using my mom's account (which is verified on my computer) and it says I'm not authorized to play the game, yet I can still listen to music downloaded from her account. Any idea how to fix this? Any help would be great, thanks!

    deauthorise your pc and reauthorise it will be fine after

  • Number Guessing Game Help

    this is my current code it works ok, but i need a bit of help with when they get it right, and I have to start converting it to graphical in Borland Jbuilder.
    import java.io.*;
         import java.util.*;
    public class Numb{
         public static void main (String [] args){
              //Game State     
              int magicNumb = Math.abs(new Random().nextInt() % 100) + 1;
              //Output instructions
              System.out.println("I Feel Numb!");
              System.out.print("Do you feel Loved? Y/N");
              //Read from input
              InputStreamReader inStream = new InputStreamReader(System.in);
              BufferedReader keyboard = new BufferedReader(inStream);
              String line = null;
              try{
                   line=keyboard.readLine();
              }catch(IOException ioe){}
              boolean acrobat = true;
              //If they pressed y let them play
              if(line.equalsIgnoreCase("y")){
                   //Game stuff goes here
                   System.out.println("Don't Expect Suggest a NUMBer between 1 and 100");
                   System.out.print("Enter a guess:");               
                   //LOOP
                   while (acrobat=true){
                   //Read user input
                   {try{
                        line=keyboard.readLine();
                   }catch(IOException ioe){}
                   //Convert the inpt to an int value
                   int guess = (int)Integer.parseInt(line);
                   //If Right
                   if (guess==magicNumb)
                        System.out.println("Green Light Seven Eleven You stop in for a pack of cigaretes");
                        acrobat=false;               
                   //If too High
                   if (guess>magicNumb)
                        System.out.println("Too Much is Not Enough");
                   //If too Low
                   if (guess<magicNumb)     
                        System.out.println("Gimme Some more, Gimme some more");}
    }

    Ok what i need help with is when they get the
    integer, i need to either state another message and
    quit, or give them the option to play again?Okay, so, your overall code structure will look something like this: do {
        play();
        again = askIfPlayAgain();
    } while again;
    void play() {
        do {
            ask for a guess
            give answer
        } while (incorrect);
    } You don't have to use do/while. Plain old while will work.
    The main points are:
    1) You need two loops. The inner one keeps going within one round until they guess correctly, and the outer one keeps starting new rounds until they quit.
    2) You should break the problem down into smaller, more elemental pieces, rather than stuffing everything into one big blob in main.
    #1 will help you solve this problem, but #2 is an absolutely essential skill to learn.

Maybe you are looking for

  • CMC Customization

    Dear Team, We are trying to provide a user access to CMC application with a restricted access (BO Version: XI 3.1 + SP3 + FP3.3). The operations he / she can do should be as below: • Login to CMC application • Able to see the user's and groups • Able

  • Action &OBJECT_ID& does not exist - when Scrolling the Scrollbar in Table

    Hi All, When  executing the application of  ABAP webdynpro component  at runtime when we scroll the scrollbar of the table then we are getting the following dump. please let me know the solution to fix the issue. Thanks in advance. Dump The following

  • RTGD for UCCX 7.x

    customer was to show some real time stats in a RTGD format "wall board" such as call in queue etc...

  • HT4623 My Iphone 4 will not update to itunes 10.6.3, so it will not sync to my computer

    My Iphone 4 will not update to itunes 10.6.3, so it will not sync to my computer

  • Impossible to play, import and burn CD

    Hi, I have search on the forums but nothing found... On PB G4 Titanium 550, with combo MATSHITA Impossible to play, import and burn CD. Only solution: I insert the CD, I repair permissions with DU and after I launch iTunes... It works perfectly but i