Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Game.java
- Ball ball = new Ball(this);
- Ball1 ball1 = new Ball1(this);
- Racket racket = new Racket(this);
- public Game() {
- initComponents();
- new Thread(new Runnable(){
- @Override
- public void run() {
- while(true){
- move();
- table.repaint();
- try {
- Thread.sleep(10);
- } catch (InterruptedException ex) {
- }
- }
- }
- }).start();
- table.setFocusable(true);
- }
- void move(){
- ball.move();
- ball1.move();
- racket.move();
- ------
- table = new javax.swing.JPanel(){
- public void paint(Graphics g){
- super.paint(g);
- ball.paint(g);
- ball1.paint(g);
- racket.paint(g);
- }
- };
- -------
- private void tableKeyPressed(java.awt.event.KeyEvent evt) {
- racket.keyPressed(evt);
- }
- private void tableKeyReleased(java.awt.event.KeyEvent evt) {
- racket.keyReleased(evt);
- }
- // Racket.java
- package exmay21;
- import java.awt.Graphics;
- import java.awt.event.KeyEvent;
- public class Racket {
- Game game;
- int x = 0;
- int xMove = 0;
- Racket(Game game){
- this.game = game;
- }
- void paint(Graphics g){
- g.fillRect(x, game.getHeight()-50, 60, 10);
- }
- void move(){
- if(x+xMove > 0 && x+xMove < game.getWidth()-60)
- x=x+xMove;
- }
- void keyPressed(KeyEvent e){
- if(e.getKeyCode() == KeyEvent.VK_RIGHT)
- xMove = 1;
- if(e.getKeyCode() == KeyEvent.VK_LEFT)
- xMove = -1;
- }
- void keyReleased(KeyEvent e){
- xMove=0;
- }
- }
- // Ball.java
- package tableTennis;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Rectangle;
- import javax.swing.JOptionPane;
- public class Ball {
- Tennis tennis;
- int x=0;
- int y=0;
- int xMove = 1;
- int yMove = 1;
- int sizeBall = 30;
- Color changeColor = Color.black;
- boolean visible;
- Ball(Tennis tennis){
- this.tennis=tennis;
- visible = true;
- }
- public void paint(Graphics g){
- g.setColor(changeColor);
- g.fillOval(x, y, 30, 30);
- }
- public boolean isVisible() {
- return visible;
- }
- public void setVisible(Boolean visible) {
- this.visible = visible;
- }
- void move(){
- if (x + xMove == 0) {
- changeColor = Color.black;
- xMove = 1;
- }
- if (x + xMove == tennis.getWidth() - 20) {
- changeColor = Color.black;
- xMove = -1;
- }
- if (y + yMove == 0) {
- yMove = 1;
- changeColor = Color.black;
- }
- if (y + yMove == tennis.getHeight() - 60) {
- yMove = -1;
- changeColor = Color.black;
- }
- if(collision()){
- System.out.println("Hit");
- //tennis.gameOver();
- sizeBall++;
- //setVisible(false);
- changeColor = Color.red;
- }
- x = x+xMove;
- y = y+yMove;
- }
- void remove(){
- x=-20;
- y=-20;
- }
- Rectangle getPosition(){
- return new Rectangle(x, y, 30, 30);
- }
- boolean collision(){
- return tennis.ball1.getPosition().intersects(getPosition());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment