Question

Java Program

The goal of this assignment is to develop an event-based game. You are going to develop a Pong Game.

The game board is a rectangle with a ball bouncing around. On the right wall, you will have a rectangular paddle (1/3 of the wall height). The paddle moves with up and down arrows. Next to the game board, there will be a score board. It will show the count of goals, and count of hits to the paddle. In the beginning of the game, the paddle will be on the center of the right wall.

pongGame.png

You can develop a two-player game, and it will count for extra 2 points bonus.

You can arrange the color and the style of the board/paddle/ball/Score Board as you prefer.

package javaapplication93;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Graphics;

import java.util.Random;

import java.util.Timer;

import java.util.TimerTask;

import javax.swing.JFrame;

import javax.swing.JPanel;

class Point{

public float mX;

public float mY;

  

public Point(float x, float y){

mX = x;

mY = y;

}

}

enum WallType{

top, bottom, left, right, none;

};

class Ball{

  

public Point mPos;

public Point mDir;

public int mLife;

  

public Ball(float y){

  

mPos = new Point(0.f, y);

mDir = new Point(1.f, 1.f);

mLife = 0;

}

  

public void move(){

  

mPos.mX += mDir.mX;

mPos.mY += mDir.mY;

mLife++;

}

  

public WallType hit(){

  

if (mPos.mX <= 2){

   return (WallType.left);

}

else if (mPos.mY <= 2){

return (WallType.top);

}

else if (mPos.mX >= 263){

return (WallType.right);

}

else if (mPos.mY >= 241){

return (WallType.bottom);

}

  

return (WallType.none);

}

  

public void rotate(WallType wallType){

switch (wallType){

case bottom:

mDir.mY *= -1;

break;

case top:

mDir.mY *= -1;

break;

case left:

mDir.mX *= -1;

break;

case right:

mDir.mX *= -1;

break;

}

}

}

/**

*

* @author neslisah

*/

public class PongGame extends JPanel {

Ball mBall;

  

public PongGame(){

super();

  

Random rand = new Random();

float y = rand.nextInt(200);

  

mBall = new Ball(y);

}

  

@Override

protected void paintComponent(Graphics g) {

super.paintComponents(g); //To change body of generated methods, choose Tools | Templates.

  

g.setColor(Color.red);

g.fillRect(0, 0, 270, 5);

  

g.setColor(Color.red);

g.fillRect(0, 0, 5, 270);

  

g.setColor(Color.red);

g.fillRect(0, 243, 270, 5);

  

g.setColor(Color.red);

g.fillRect(265, 0, 5, 250);

  

g.setColor(Color.blue);

g.fillOval((int)mBall.mPos.mX, (int)mBall.mPos.mY, 4, 4);

  

}

  

/**

   * @param args the command line arguments

   */

public static void main(String[] args) {

// TODO code application logic here

  

JFrame myFrame = new JFrame("My Pong Game");

myFrame.setLayout(new BorderLayout());

myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  

PongGame pong = new PongGame();

myFrame.add(pong, BorderLayout.CENTER);

  

TimerTask moveBall = new TimerTask() {

@Override

public void run() {

pong.mBall.move();

  

if (pong.mBall.mLife > 5){

WallType hit = pong.mBall.hit();

if (hit != WallType.none){

pong.mBall.rotate(hit);

System.out.println(hit);

pong.mBall.mLife = 0;

}

}

  

pong.repaint();

}

};

  

Timer timer = new Timer();

timer.scheduleAtFixedRate(moveBall, 0, 5);

  

myFrame.setSize(270, 270);

myFrame.setVisible(true);

}

  

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANS:-

Given that,

  

The goal of this assignment is to develop an event-based game. You are going to develop a Pong Game.The game board is a rectangle with a ball bouncing around. On the right wall, you will have a rectangular paddle (1/3 of the wall height). The paddle moves with up and down arrows. Next to the game board, there will be a score board. It will show the count of goals, and count of hits to the paddle. In the beginning of the game, the paddle will be on the center of the right wall.

the following code will provide u a ping pong game....

description

* Project Name:   ping pong java code-sticker ball
environment :  Java
* IDE:   NetBeans
* Description: , its a stand alone application, i added some features like cheering sound at the start of the game, beside the other described features in this topic:
it has two classes

ball and sound

package stickerball_game;

import java.awt.Color;

import java.awt.Component;

import java.awt.Graphics;

import java.awt.Image;

import javax.swing.ImageIcon;

public class Ball {

/** Creates a new instance of Ball */

private Sound mysound;

private int Reduis;

public int x;

public int y;

public int vx;

public int vy;

private int BALL_TOP;

private int BALL_LEFT;

private int BALL_RIGHT;

private int BALL_DOWN;

private int PLAYER_TOP;

private int PLAYER_DOWN;

private int PLAYER_RIGHT;

private int COMP_TOP;

private int COMP_DOWN;

private int COMP_LEFT;

private int max_vx=5;

private int max_vy=5;

public Component myBase;

private Color BallColor;

private Image myImg;

public Ball(int r, int x,int y,int vx,int vy,Color BallColor,Component newBase) {

Reduis=r;

this.x=x;

this.y=y;

this.vx=vx;

this.vy=vy;

myBase=newBase;

myImg=new ImageIcon("images/Ball.gif").getImage();

this.BallColor=BallColor;

}

public void move() {

if (vx > max_vx) vx = max_vx;

else if (vx < -max_vx) vx = -max_vx;

else if (vy > max_vy) vy = max_vy;

else if (vy < -max_vy) vy = -max_vy;

// else if (vx == 0 && !isStoped) vx = 1;

x += vx;

y += vy;

}

public int wheresBall() {

if (vy > 0) {

if (y > 280) {

vy = -vy;

return 0;

}

} else if (vy < 0) {

if (y < 40) {

vy = -vy;

return 0;

}

}

if(x<20)

return 1;

else if(x>375)

return 2;

return 0;

}

public void PCollision(Player PlayerStick) {

BALL_TOP = y - Reduis;

BALL_DOWN = y + Reduis;

BALL_LEFT = x - Reduis;

BALL_RIGHT = x + Reduis;

PLAYER_TOP = PlayerStick.y;

PLAYER_DOWN = PlayerStick.y + PlayerStick.sizey;

if ((BALL_TOP >= PLAYER_TOP - 10) && (BALL_DOWN <= PLAYER_DOWN + 10)) {

if (BALL_LEFT <= 30 ) {

mysound = new Sound("Sound/hit.wav");

vx = - vx;

if (PlayerStick.vy < 0) {

vy --;

} else if (PlayerStick.vy > 0) {

vy += PlayerStick.vy;

}

}

}

}

public void CCollision(Computer CompStick) {

BALL_TOP = y - Reduis;

BALL_DOWN = y + Reduis;

BALL_LEFT = x - Reduis;

BALL_RIGHT = x + Reduis;

COMP_TOP = CompStick.y;

COMP_DOWN= CompStick.y + CompStick.sizey;

if ((BALL_TOP >= COMP_TOP - 10) && (BALL_DOWN <= COMP_DOWN + 10)) {

if (BALL_RIGHT >= 370 ) {

mysound = new Sound("Sound/hit.wav");

vx = - vx;

if (CompStick.vy < 0) {

vy --;

} else if (CompStick.vy > 0) {

vy += CompStick.vy;

}

}

}

}

public void DrawBall(Graphics g) {

g.setColor(BallColor);

g.drawImage(myImg,x - Reduis, y - Reduis,myBase);

}

}

==========================================================================

package stickerball_game;

import java.io.File;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.LineUnavailableException;

import javax.sound.sampled.SourceDataLine;

import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

     

    AudioFormat audioFormat;

    AudioInputStream audioInputStream;

    SourceDataLine sourceDataLine;

    String X;

     

//end main

    /** Creates a new instance of Sound */

    public Sound(String Wavname) {

        new PlayThread().start();

        X=Wavname;

    }

    class PlayThread extends Thread{

        byte tempBuffer[] = new byte[10000];

         

        public void run(){

            File soundFile =new File(X);

            

                try {

                    audioInputStream = AudioSystem.

                            getAudioInputStream(soundFile);

                    audioFormat = audioInputStream.getFormat();

                     

                     

                    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,audioFormat);

                     

                    sourceDataLine =(SourceDataLine)AudioSystem.getLine(dataLineInfo);

                    sourceDataLine.open(audioFormat);

                } catch (LineUnavailableException ex) {

                    ex.printStackTrace();

                } catch (UnsupportedAudioFileException ex) {

                    ex.printStackTrace();

                } catch (IOException ex) {

                    ex.printStackTrace();

                }

                sourceDataLine.start();

                try{

                    int cnt;

                    while((cnt = audioInputStream.read(

                            tempBuffer,0,tempBuffer.length)) != -1) {

                        if(cnt > 0){

                            sourceDataLine.write(tempBuffer, 0, cnt);

                        }

                    }

                    sourceDataLine.flush();

                    sourceDataLine.close();

                    Thread.sleep(2000);

                }catch (Exception e) {

                    e.printStackTrace();

                    System.exit(0);

                }

         

        }

         

    }//end inner class PlayThread

//======================//

     

}//end outer class AudioPlayer02.j

Add a comment
Know the answer?
Add Answer to:
Java Program The goal of this assignment is to develop an event-based game. You are going...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Introduction to Java Programming Question: I’m doing a java game which user clicks on two different...

    Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically looking for codes that could make my memory match game more difficult or more interesting.(a timer, difficulty level, color, etc.) GUI must be included in the code. Here is what I got so far: package Card; import javax.swing.JButton; public class Card extends JButton{    private int id;   ...

  • Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent()...

    Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent() method to check when the ball has hit the edge of the window. When the ball reaches an edge, you will need to reverse the corresponding delta direction and position the ball back in bounds. Make sure that your solution still works when you resize the window. Your bounds checking should not depend on a specific window size This is the java code that...

  • Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically look...

    Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically looking for codes that could make my memory match game more difficult or more interesting.(a timer, difficulty level, color, etc.) GUI must be included in the code. Here is what I got so far: package Card; import javax.swing.JButton; public class Card extends JButton{    private int id;    private boolean...

  • In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show...

    In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...

  • please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import...

    please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; enum Dir{L, U, R, D}; class Food { public static int FOODSTYLE = 1; private int m = r.nextInt(Yard.WIDTH / Yard.B_WIDTH); private int n = r.nextInt(Yard.HEIGHT / Yard.B_WIDTH - 30/Yard.B_WIDTH) + 30/Yard.B_WIDTH;// 竖格 public static Random r = new Random(); public int getM() { return m; } public void setM(int m)...

  • This is a Clock program in Java. Can you fix my Java program error, and add function to display c...

    This is a Clock program in Java. Can you fix my Java program error, and add function to display current time currently? import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.util.Date; import javax.swing.JPanel; import javax.swing.WindowConstants; public class Clock extends javax.swing.JFrame {    public int hour;    public int min;    public int sec;    ClockDial cd;    public Clock() {        setSize(510, 530);        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        cd = new ClockDial(this);        getContentPane().add(cd);        Date curr = new Date();        String time = curr.toString();        hour = Integer.parseInt(time.substring(11, 13));        min = Integer.parseInt(time.substring(14, 16));        sec...

  • ***This is a JAVA question*** ------------------------------------------------------------------------------------------------ import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*;...

    ***This is a JAVA question*** ------------------------------------------------------------------------------------------------ import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class DrawingPanel implements ActionListener { public static final int DELAY = 50; // delay between repaints in millis private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save"; private static String TARGET_IMAGE_FILE_NAME = null; private static final boolean PRETTY = true; // true to anti-alias private static boolean DUMP_IMAGE = true; // true to write DrawingPanel to file private int width, height; // dimensions...

  • Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(),...

    Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(), then implement them, so far in my version i tentatively made them, but I don't know ho to implement them so i posted the original code before i made my version of the three methods listed above. Need help fast, this is ridiculous. Implement just one requirement at a time. For example, try implementing the case where after the user clicks 2 squares, both...

  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • This is java. Goal is to create a pacman type game. I have most of the...

    This is java. Goal is to create a pacman type game. I have most of the code done just need to add in ghosts score dots etc. Attached is the assignment, and after the assignment is my current code. import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Maze extends JFrame implements KeyListener { private static final String[] FILE = {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT