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.
Similar Messages
-
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 GawronskiI 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 -
Part II - Playing Ping-Pong ... now with KaLin?
Just call me flummoxed ...
I went to my "profile page for the forum" by clicking on my name. (So far so good)
I looked "at the top of the middle column," (Puzzled, I search for KaLin's promised support.)
THERE IS NOTHING REMOTELY RESEMBLING "an area titled "My Private Support Cases," nor any selection that leads to "My Private Support Cases."
THERE IS NO LINK to "the private board where you and the agent may exchange information."
And thus, it seems like the ping-pong game continues ...
I used to wonder why nobody responded to their original posts with updates. It appears that moderators prevent this from happening.
Eager for assistance, I remain yours sincerely,
marlowrogPlease check your Private Message Inbox. It should look like this -->>
If a forum member gives an answer you like, give them the Kudos they deserve. If a member gives you the answer to your question, mark the answer that solved your issue as the accepted solution. -
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. -
Can I Write a * Game in Java?
I have noticed loads of topics lately along the lines of "Can I write a quake style shooter in java" or "could I write a mmporg in Java" and similar for almost every style of game. I'd just like to make a quick point on this:
Java is a programming language. At the stage it has reached now it can do anything any other programming language can do. It's strengths and weaknesses may be different from those of C, C++, Visual Basic, Lisp or whatever other languages people use regularly, but when it gets right down to it Java isn't the problem. If you can design it effectively then you can implement it in any complete language. It may not be easy but it is possible. The answer to this question is invariably yes.
These forums are far more useful for asking practical questions rather than asking conceptual ones. A better question might be "how would I best start to design a * to be implemented in Java?"Yeah thats a good point. I think that Java has been so popular for so long that it can pretty well do anything as long as the designer designs it properly.
I've made a http web server, and just yesterday I made a pong style game. Java works for almost anything. Take a cruse through the Java Programming forum. People there are using Java to sort money things and everything. -
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! -
Trying to make a Ping Pong Ball generate in random location
Hey guys and Gals,
im trying to make a pingpong ball, well 2 of them spawn in random locations so that it makes the game a little harder as of right now the ping pong balls spawn right next to each other and untill score 5-6 there right next to each otherI disagree with Caillen. If somebody is trying to learn a programming language writing a game is an excellent way of learning. In the constructor to the form (or form load function ) you can change the X,Y location of the ball(s). You also want
to make sure the two balls don't overlap. To make the programming simpler I would start the two balls at the same Y coordinate (or X).
See code below. I used a little clever programming to prevent the two ball from overlapping. The code assumes the left side of the panel x = 0. If it is not zero then add the X of the left side of the panel to the results.
int widthPanel = 10;
int diameterBall = 2;
Random rand = new Random();
int ball1X = rand.Next(diameterBall / 2, widthPanel - (diameterBall / 2));
//now get a random number that is space not taken up by ball one
int ran2 = rand(0, widthPanel - diameterBall);
int ball1Left = ballX - (diameterBall / 2);
int ball2X = 0;
if(rand2 <= ball1X)
ball2X = rand2;
else
int ball1Right = ballX + (diameterBall / 2);
ran2 -= ball1Left;
ball2X = ball1Right + ran2;
jdweng -
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!
-
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 PMI'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;
} -
Motion Tracking Ping pong ball
I'm superimposing a ping pong ball into live footage of a match but with the actions acting the hitting.
What do people think is the best way to do this?
I was thinking maybe its best to put the 'ball' under a null, motion track the null and animate the ball underneath for scaling and position.
Maybe motion tracking isn't an option and I should just animate the ball movements?
Has anyone done this or may have any possible suggestions?
Thanks!
SGMake your life easy, hand-animate it. Pingpong is a fast game, resulting in lots of motionblurred elements and it will be a nightmare to track. You'll waste a lot of time on fixing a poor track that you could have spent refining your animation to begin with....
Mylenium -
i want to create a ping-pong online game as applet and i have a few problems:
the game contains 4 classes:
user pedal
computer pedal
ball
boardgame
do i have to use 4 applet(1 applet to every class)?
or to use one applet that contains 4 panels?
did every class contain the paint metode?The way i will do it is: 1 Applet, 4 classes that extends Component each have a paint method.
Noah -
Want help in developing my first game in java!!
I want to develop a tetris game in java..can any one help me on this..basically i m new to java programming, i want to know abt the graphical part ..how to make that.. i will code the rest..I want to make an application rather than an applet..
look at the Java2D demo that comes with the JDK
it has lots of source code and just about everything you'll need to do in Tetris (technology wise) is in there, except the game logic.
when you're ready to move into 3D and heavier apps, try this book:
Practical Java Game Programming
http://www.amazon.com/exec/obidos/tg/detail/-/1584503262/102-3570681-1096110?v=glance -
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. -
Making Games in Java!!!
hey i want to make a game in java but i want to get a lot more ideas about what the game should be like and what it should do. I want to actually work with someone else to make the game and then we can sell it or something like that. So if anyone is interested just make a reply OR e-mail me at [email protected] thanks.
hey i want to make a game in java but i want to get a
lot more ideas about what the game should be like and
what it should do. I want to actually work with
someone else to make the game and then we can sell it
or something like that. So if anyone is interested
just make a reply OR e-mail me at [email protected]
thanks.This post is an email harvester's dream. -
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
Maybe you are looking for
-
JFrame (menubar) problem
Hi, I have a JFrame with few JPanels on it ( those in turn have JButtons etc). JFrame has the ussual menubar ( set using setJMenuBar) . Menubar is not accessiable using <TAB> . All other items are. Any ideas? Thank you in advence for any help.
-
How to create a table format in Scripts
I need atabe format to display items in invoice created using scripts
-
Connecting to an oracle database questions
<p>Our current solution to connecting to our oracle database uses the following code:</p><p> ReportClientDocument clientDoc = new ReportClientDocument;</p><p> java.sql.ResultSet rs = fetchResultSet(driverName, connectStr, userName, password, <
-
Unity 7 Backup Subscriber Server - Live Reply not working
Hi we have two Unity 7 servers, one Primary and 2nd Backup Subscriber Server. Live Reply is not working when the Unity Primary Server fall onto the Backup Server. Do anyone have an idea or an solution form me? On both Servers: Unity Version: 7.0(2.0)
-
In the Sales Order item line have lines charge, How to insert the charge ? Is it set in the Item Master or Price List ,please let me know ? thanks