Java连锁反应游戏

时间:2013-04-08 13:43:11

标签: java swing drawing2d

我是Java 2d图形的初学者,而stackoverflow的新手如果做错了就原谅我。我正在尝试做一个涉及连锁反应的迷你游戏。例如,我想在具有单独线程的JPanel上放置10个球弹跳。当我点击JPanel上的一个球时,我希望它能够扩展,并且每一个击中它的球也会扩展。我已经设法在一个Java文件中执行此操作,但我不能使它在单独的文件中工作。任何输入都表示赞赏。谢谢。

这是我的单个文件BounceBall.java

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.util.*;

public class BounceBall extends JFrame {

    private ShapePanel drawPanel;
    private Vector<NewBall> Balls;
    private JTextField message;

    // set up interface
    public BounceBall() {
        super("MultiThreading");
        drawPanel = new ShapePanel(400, 345);
        message = new JTextField();
        message.setEditable(false);

        Balls = new Vector<NewBall>();
        add(drawPanel, BorderLayout.NORTH);
        add(message, BorderLayout.SOUTH);

        setSize(400, 400);
        setVisible(true);
        createBalls();
    } // end Ex20 constructor

    public void createBalls() {
        for (int i = 1; i <= 20; i++) {
            NewBall nextBall = new NewBall();
            Balls.addElement(nextBall);
            nextBall.start();
            message.setText("Number of Balls: " + Balls.size());
        }
    }

    public static void main(String args[]) {

        BounceBall application = new BounceBall();

        application.addWindowListener(
            new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // Class NewBall is used to create a ball and move its position
    // A thread overrides the run method to define how the ball behaves
    // Each ball is one instance of this class
    private class NewBall extends Thread {

        private Ellipse2D.Double thisBall;
        private boolean ballStarted, growBall, growEnd;
        private int size = 30, speed = 70;             // characteristics
        private int deltax, deltay;          // of the ball
        Random r = new Random();
        int red = r.nextInt(255), green = r.nextInt(255), blue = r.nextInt(255);

        public NewBall() {
            // Create new ball with random size, speed, start point,
            // and direction.  "Speed" is actually the amount of sleep
            // between moves.
            ballStarted = true;
            // size = 10 + (int)(Math.random() * 60);
            // speed = 10 + (int)(Math.random() * 100);
            int startx = (int) (Math.random() * 300);
            int starty = (int) (Math.random() * 300);
            deltax = -10 + (int) (Math.random() * 21);
            deltay = -10 + (int) (Math.random() * 21);
            if ((deltax == 0) && (deltay == 0)) {
                deltax = 1;
            }
            thisBall = new Ellipse2D.Double(startx, starty, size, size);
        }

        public void draw(Graphics2D g2d) {
            if (thisBall != null) {
                g2d.setColor(new Color(red, green, blue, 80));
                g2d.fill(thisBall);
            }
        }

        public void grow() {
            growBall = true;
        }

        void removeBall() {
            for (int i = 0; i < Balls.size(); i++) {
                Balls.remove(i);
            }

            repaint();
        }

        public double getPositionX() {
            return thisBall.getX();
        }

        public double getPositionY() {
            return thisBall.getY();
        }

        public int radius() {
            return size * 2;
        }

        public void run() {
            while (ballStarted && !growBall) // Keeps ball moving
            {
                try {
                    // To free up processor time
                    Thread.sleep(speed);

                } catch (InterruptedException e) {
                    System.out.println("Woke up prematurely");
                }

                // calculate new position and move ball
                int oldx = (int) thisBall.getX();
                int oldy = (int) thisBall.getY();
                int newx = oldx + deltax;
                if (newx + size > drawPanel.getWidth() || newx < 0) {
                    deltax = -deltax;
                }
                int newy = oldy + deltay;
                if (newy + size > drawPanel.getHeight() || newy < 0) {
                    deltay = -deltay;
                }
                thisBall.setFrame(newx, newy, size, size);

                while (growBall && size < 80) {
                    try {
                        // To free up processor time
                        Thread.sleep(speed);

                    } catch (InterruptedException e) {
                        System.out.println("Woke up prematurely");
                    }
                    size++;
                    thisBall.setFrame(newx, newy, size, size);

                    for (int i = 0; i < Balls.size(); i++) {
                        if (thisBall.contains(Balls.get(i).thisBall.x, Balls.get(i).thisBall.y)) {
                            Balls.get(i).grow();
                        }
                    }
                }
                drawPanel.repaint();
            }
        }
    } // end NewBall

    // Define a class to be a panel on which the balls are drawn
    private class ShapePanel extends JPanel {

        private int prefwid, prefht;

        public ShapePanel(int pwid, int pht) {
            prefwid = pwid;
            prefht = pht;


            // add ball when mouse is clicked
            addMouseListener(
                new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    stopBall(e);

                }
            });
        }

        public void stopBall(MouseEvent e) {
            for (int i = 0; i < Balls.size(); i++) {
                if (Balls.get(i).thisBall.contains(e.getPoint())) {
                    Balls.get(i).grow();
                }
            }
        }

        public Dimension getPreferredSize() {
            return new Dimension(prefwid, prefht);
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            for (int i = 0; i < Balls.size(); i++) {
                (Balls.elementAt(i)).draw(g2d);
            }
        }
    } // end ShapePanel inner class
} // end BounceBall

这是我尝试做的3个类:Ball.java

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.util.Random;


public class Ball extends Thread {
    public Ellipse2D.Double thisBall;
    public int size=30,xPoz,yPoz;
    Random r=new Random();
    int red=r.nextInt(255),green=r.nextInt(255),blue=r.nextInt(255);
    int deltax,deltay;
    public boolean ballStarted;

    public Ball()
    {xPoz=(int)Math.random();
     yPoz=(int)Math.random();
     ballStarted = true;
     deltax=-10+(int)(Math.random()*21);
     deltay=-10+(int)(Math.random()*21);
     if ((deltax == 0) && (deltay == 0)) { deltax = 1; }
     thisBall=new Ellipse2D.Double(xPoz,yPoz,size,size);
     super.start();
    }

    public void draw(Graphics2D g2d){
    if(thisBall!=null)
    {g2d.setColor(new Color(red,green,blue,80));
     g2d.fill(thisBall);
    }  
    }

    public int PozX(){return xPoz;}
    public int PozY(){return yPoz;}
    public int radius(){return size*2;}

    public void grow(){
    size++;
    thisBall.setFrame(xPoz,yPoz,size,size);
    }

    public void move(){
        int oldx=xPoz;
        int oldy=yPoz;

        int newx=oldx+deltax;
        int newy=oldy+deltay;

        if(newx+size>800 || newx<0)
            deltax=-deltax;
        if(newy+size>600 || newy<0)
            deltay=-deltay;

        thisBall.setFrame(newx,newy,size,size);
    }

    public void run(){
        try {

               Thread.sleep(100);

            }
            catch (InterruptedException e)
            {  System.out.println("Thread Halted");}
        while(ballStarted)
        {move();}

    }

}

ShapePanel.java:

public class ShapePanel extends JPanel{
    private int prefwid, prefht,nrBalls;
    public Vector<Ball> Balls=new Vector<Ball>();;

      public ShapePanel (int pwid, int pht)
      {
         prefwid = pwid;
         prefht = pht;



         addMouseListener(

        new MouseAdapter()  {
           public void mousePressed(MouseEvent e)
                   { 


                   }
                }
          );
      }

    public void createBalls(){
    for(int i=1;i<=nrBalls;i++)
    { Ball movingBall=new Ball();
      Balls.addElement(movingBall);
      //movingBall.start();

    }

    }  


      public Dimension getPreferredSize()
      {
         return new Dimension(prefwid, prefht);
      }

      public void setNrBalls(int n){this.nrBalls=n;}

      public void paintComponent (Graphics g)  
      {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Ball ball : Balls) {
                ball.draw(g2d);
            }
            g2d.dispose();
      }
   } 

和BallBlaster.java:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class BallBlaster extends JFrame
{
   private ShapePanel drawPanel;

   private JTextField message;

   // set up interface
   public BallBlaster()  
   {
      super("MultiThreading");
      drawPanel = new ShapePanel(800, 600);
      message = new JTextField("Number of balls : ");
      message.setEditable(false);


      add(drawPanel, BorderLayout.NORTH);
      add(message, BorderLayout.SOUTH);

      setSize(800, 600);
      setVisible(true);

      drawPanel.setNrBalls(20);
      drawPanel.repaint();
   } 


   public static void main(String args[])  {

      BoomShine application = new BoomShine();

      application.addWindowListener(
         new WindowAdapter()
         {
            public void windowClosing(WindowEvent e)  
            {
               System.exit(0);
            }
         }
      );
   }

} 

2 个答案:

答案 0 :(得分:1)

将内部类转换为公共类时,应将对象引用移动到适当的类。例如,Balls数组应该转到ShapePanel,Ball类应该引用ShapePanel。创建和删除球的方法应该移动到ShapePanel。这样你就可以给每个班级一个单一的责任,ShapePanel可以用球,球移动等等......

答案 1 :(得分:-1)

连锁反应游戏(多人游戏) - C程序使用递归

董事会详情

       -> Default board size is 8*8 Matrix.
       -> Number of User Minimum 2 user and Maximum 10 user.
       -> Displaying separate User ball_Count is(eg. The First User(1) balls are displayed in ((User_ID * 10) + ball_Count) ).
        (Eg). UserId – 1
              Position Of the Board ith and jth value 0,0
              the ball value is displayed as 11
              again clik(enter same position of first user ) it value is displayed as 12

球数显示逻辑 - &gt; ((User_ID * 10)+ Ball_Count)

**样本输出:**

Enter the number of player : 2

        0    1   2   3   4   5   6   7 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 0 |     0   0   0   0   0   0   0   0 
   |
 1 |     0   0   0   0   0   0   0   0 
   |
 2 |     0   0   0   0   0   0   0   0 
   |
 3 |     0   0   0   0   0   0   0   0 
   |
 4 |     0   0   0   0   0   0   0   0 
   |
 5 |     0   0   0   0   0   0   0   0 
   | 
 6 |     0   0   0   0   0   0   0   0 
   |
 7 |     0   0   0   0   0   0   0   0 
   |

Now Player 1 term....... 
Enter ith and jth Position..... : 0 0

         0   1   2   3   4   5   6   7 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 0 |     11      0   0   0   0   0   0   0 
   |
 1 |     0   0   0   0   0   0   0   0 
   |
 2 |     0   0   0   0   0   0   0   0 
   |
 3 |     0   0   0   0   0   0   0   0 
   |
 4 |     0   0   0   0   0   0   0   0 
   |
 5 |     0   0   0   0   0   0   0   0 
   |
 6 |     0   0   0   0   0   0   0   0 
   |
 7 |     0   0   0   0   0   0   0   0 
   |

Now Player 2 term....... 
Enter ith and jth Position..... : 0 1

         0    1  2   3   4   5   6   7 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 0 |     11  21  0   0   0   0   0   0 
   |
 1 |     0   0   0   0   0   0   0   0 
   |
 2 |     0   0   0   0   0   0   0   0 
   |
 3 |     0   0   0   0   0   0   0   0 
   |
 4 |     0   0   0   0   0   0   0   0 
   |
 5 |     0   0   0   0   0   0   0   0 
   |
 6 |     0   0   0   0   0   0   0   0 
   |
 7 |     0   0   0   0   0   0   0   0 
   |

Now Player 1 term....... 
Enter ith and jth Position..... : 0 0


<--------The player 1 is win ---------->



         0  1    2   3   4   5   6   7 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 0 |     0   12  0   0   0   0   0   0 
   |
 1 |     11  0   0   0   0   0   0   0 
   |
 2 |     0   0   0   0   0   0   0   0 
   |
 3 |     0   0   0   0   0   0   0   0 
    |
 4 |     0   0   0   0   0   0   0   0 
   |
 5 |     0   0   0   0   0   0   0   0 
   |
 6 |     0   0   0   0   0   0   0   0 
   |
 7 |     0   0   0   0   0   0   0   0 
   |


Program : 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int bord[8][8];
int eluminetUser[11]={0,1,1,1,1,1,1,1,1,1,1};
int eluminetUserCount;
int no_player;
int printBord(){
    printf("\n\n\t 0 \t 1 \t 2 \t 3 \t 4 \t 5 \t 6 \t 7 ");
    printf("\n\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    for(int i = 0; i<8;i++){
        printf(" %d |",i);
        for(int j = 0;j<8;j++){
            printf("\t %d ",bord[i][j]);
        }
        printf("\n |\n");
    }
    return 0;
}

int checkBord(){
    static int userCount;
    int result = 0,count = 0,eCount = 0;
    userCount++;
    if(no_player > userCount)
        return 0;
    bzero(eluminetUser,40);
    for(int i = 0; i<8;i++)
        for(int j = 0;j<8;j++)
            if(bord[i][j] != 0 )     
                eluminetUser[bord[i][j]/10] = 1;



    for(int i = 1 ; i <= no_player ; i++ )
        if(eluminetUser[i])
            eCount++;
    if(eCount>1)
        return 0; 
    return 1;
}

int playBord(int ith, int jth, int current_player, int type){
    int count = 0; 


    if((ith<0) || (jth<0) || (ith>7) || (jth>7))
        return 8;
    if(type){//user saide clike
        bord[ith][jth] = !bord[ith][jth] ? (current_player*10)+1 : bord[ith][jth]+1 ;
    }
    else{ //system saide spreading the bal
        bord[ith][jth] = (current_player *10) + (bord[ith][jth]%10) + 1;
    }

    count = bord[ith][jth]%10;


    if((ith == 0) && (jth == 0) && (count == 2)){
        bord[ith][jth] = 0;
        playBord(ith+1, jth, current_player, 0);
        playBord(ith, jth+1, current_player, 0);
    }else if((ith == 0) && (jth == 7) && (count == 2)){
        bord[ith][jth] = 0;
        playBord(ith+1, jth, current_player, 0);
        playBord(ith, jth-1, current_player, 0);
    }else if((ith == 7) && (jth == 7) && (count == 2)){
        bord[ith][jth] = 0;
        playBord(ith-1, jth, current_player, 0);
        playBord(ith, jth-1, current_player, 0);
    }else if((ith == 7) && (jth == 0) && (count == 2)){
        bord[ith][jth] = 0;
        playBord(ith-1, jth, current_player, 0);
        playBord(ith, jth+1, current_player, 0);
    }else if((ith == 0) && (count == 3)){
        bord[ith][jth] = 0;
        playBord(ith ,jth-1, current_player, 0);
        playBord(ith+1, jth, current_player, 0);
        playBord(ith, jth+1, current_player, 0);

    }else if((ith == 7) && (count == 3)){
        bord[ith][jth] = 0;
        playBord(ith,jth-1,current_player,0);
        playBord(ith-1,jth,current_player,0);
        playBord(ith,jth+1,current_player,0);
    }else if((jth == 7) && (count == 3)){
        bord[ith][jth] = 0;
        playBord(ith-1,jth,current_player,0);
        playBord(ith,jth-1,current_player,0);
        playBord(ith+1,jth,current_player,0);
    }
    else if((jth == 0) && (count == 3)){
        bord[ith][jth] = 0;
        playBord(ith-1,jth,current_player,0);
        playBord(ith,jth+1,current_player,0);
        playBord(ith+1,jth,current_player,0);
    }else if(count == 4){
        bord[ith][jth] = 0;
        playBord(ith-1,jth,current_player,0);
        playBord(ith,jth-1,current_player,0);
        playBord(ith,jth+1,current_player,0);
        playBord(ith+1,jth,current_player,0);
    }

    /*if(checkBord()){

        return 1;
    }*/


return 0;
}

int main(){
    int current_player = 1,ith,jth,count = 0;
    printf("Enter the number of player : ");
    scanf("%d",&no_player);
    if(no_player<2){
        printf("\npls select 2 or more user....\n\n");
        return 0;
    }
    while(1){
        printBord(); 
        if(current_player == (no_player+1)){
            current_player = 1;
        }
        if(eluminetUser[current_player]){// if the user is exist going to get location (eg.) User 1 and 3 is exist and User 2 is out so the current_player is comes to 2 User but that user is not exist so skip the User 2 position.
            printf("\nNow Player %d term....... ",current_player);
            printf("\nEnter ith and jth Position..... : ");
            scanf("%d%d",&ith,&jth);
            if((bord[ith][jth] == 0 ) || (bord[ith][jth] / 10 ) == current_player){

                if( playBord(ith,jth,current_player,1) == 8)
                {
                    printf("\n\n Position is invalid ......\n\n");
                    count--;
                    current_player--;
                } 
                if(checkBord()&& ( count >= no_player))
                {
                    printf("\n\n\n<--------The player %d is win ---------->\n\n",current_player);
                    break;
                }

            }
            else{
                printf("\n\n%d,%d Position not your's pls choose correct position\n\n",ith,jth);
            }
        } 
            current_player++;
            count++;
        }
        printBord();

return 0;
}