Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何使用SwingWorker创建多线程游戏_Java_Multithreading_Swing_Concurrency_Swingworker - Fatal编程技术网

Java-如何使用SwingWorker创建多线程游戏

Java-如何使用SwingWorker创建多线程游戏,java,multithreading,swing,concurrency,swingworker,Java,Multithreading,Swing,Concurrency,Swingworker,我想用线程创建一个[1人vs PC]游戏 我们的电路板上有10*10两种颜色的形状,如下所示: 当玩家点击蓝色圆圈时,它们的颜色变成灰色 在另一侧,PC应将所有红色矩形变为灰色 获胜者是谁提前清除了他/她自己的所有形状 播放器的代码工作正常,但是, 我的问题在于实现游戏的PC端,正如我在本文中所读到的,我应该使用SwingWorker在GUI中实现线程。 这是我第一次使用SwingWorkers,我不知道如何才能正常工作 这是我的密码: 主类 public class BubblePopGa

我想用线程创建一个[1人vs PC]游戏

我们的电路板上有10*10两种颜色的形状,如下所示:

当玩家点击蓝色圆圈时,它们的颜色变成灰色

在另一侧,PC应将所有红色矩形变为灰色

获胜者是谁提前清除了他/她自己的所有形状


播放器的代码工作正常,但是, 我的问题在于实现游戏的PC端,正如我在本文中所读到的,我应该使用SwingWorker在GUI中实现线程。 这是我第一次使用SwingWorkers,我不知道如何才能正常工作

这是我的密码:

主类

public class BubblePopGame {

public static final Color DEFAULT_COLOR1 = Color.BLUE;
public static final Color DEFAULT_COLOR2 = Color.RED;

public BubblePopGame() {
    List<ShapeItem> shapes = new ArrayList<ShapeItem>();

    int Total = 10;
    for (int i = 1; i <= Total; i++) {
        for (int j = 1; j <= Total; j++) {
            if ((i + j) % 2 == 0) {

                shapes.add(new ShapeItem(new Ellipse2D.Double(i * 25, j * 25, 20, 20),
                        DEFAULT_COLOR1));
            } else {
                shapes.add(new ShapeItem(new Rectangle2D.Double(i * 25, j * 25, 20, 20),
                        DEFAULT_COLOR2));
            }
        }
    }

    JFrame frame = new JFrame("Bubble Pop Quest!!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ShapesPanel panel = new ShapesPanel(shapes);
    frame.add(panel);
    frame.setLocationByPlatform(true);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new BubblePopGame();
        }
    });
}
public class ShapeItem {

private Shape shape;
private Color color;

public ShapeItem(Shape shape, Color color) {
    super();
    this.shape = shape;
    this.color = color;
}

public Shape getShape() {
    return shape;
}

public void setShape(Shape shape) {
    this.shape = shape;
}

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
}
public class ShapesPanel extends JPanel {

private List<ShapeItem> shapes;
private Random rand = new Random();
private SwingWorker<Boolean, Integer> worker;

public ShapesPanel(List<ShapeItem> shapesList) {
    this.shapes = shapesList;
    worker = new SwingWorker<Boolean, Integer>() {            

        @Override
        protected Boolean doInBackground() throws Exception {
            while (true) {
                Thread.sleep(200);
                int dim = rand.nextInt(300);
                publish(dim);                
                return true;
           }
        }

        @Override
        protected void done() {
            Boolean Status;
            try {                    
                Status = get();
                System.out.println(Status);
                super.done();                    //To change body of generated methods, choose Tools | Templates.
            } catch (InterruptedException ex) {
                Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        protected void process(List<Integer> chunks) {
            int mostRecentValue = chunks.get(chunks.size()-1);
            System.out.println(mostRecentValue);
                Color color2 = Color.LIGHT_GRAY;
                ShapeItem tmpShape = shapes.get(mostRecentValue);
                if(tmpShape.getColor()==Color.RED){
                    tmpShape.setColor(color2);
                }
                repaint();                
       }

    };
    worker.execute ();

    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            Color color1 = Color.LIGHT_GRAY;
            for (ShapeItem item : shapes) {
                if (item.getColor() == Color.BLUE) {
                    if (item.getShape().contains(e.getPoint())) {
                        item.setColor(color1);
                    }
                }
            }
            repaint();
        }
    });
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g.create();

    for (ShapeItem item : shapes) {
        g2.setColor(item.getColor());
        g2.fill(item.getShape());
    }

    g2.dispose();
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

private Color getRandomColor() {
    return new Color(rand.nextFloat(), rand.nextFloat(),
            rand.nextFloat());
}
}

形状面板类

public class BubblePopGame {

public static final Color DEFAULT_COLOR1 = Color.BLUE;
public static final Color DEFAULT_COLOR2 = Color.RED;

public BubblePopGame() {
    List<ShapeItem> shapes = new ArrayList<ShapeItem>();

    int Total = 10;
    for (int i = 1; i <= Total; i++) {
        for (int j = 1; j <= Total; j++) {
            if ((i + j) % 2 == 0) {

                shapes.add(new ShapeItem(new Ellipse2D.Double(i * 25, j * 25, 20, 20),
                        DEFAULT_COLOR1));
            } else {
                shapes.add(new ShapeItem(new Rectangle2D.Double(i * 25, j * 25, 20, 20),
                        DEFAULT_COLOR2));
            }
        }
    }

    JFrame frame = new JFrame("Bubble Pop Quest!!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ShapesPanel panel = new ShapesPanel(shapes);
    frame.add(panel);
    frame.setLocationByPlatform(true);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new BubblePopGame();
        }
    });
}
public class ShapeItem {

private Shape shape;
private Color color;

public ShapeItem(Shape shape, Color color) {
    super();
    this.shape = shape;
    this.color = color;
}

public Shape getShape() {
    return shape;
}

public void setShape(Shape shape) {
    this.shape = shape;
}

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
}
public class ShapesPanel extends JPanel {

private List<ShapeItem> shapes;
private Random rand = new Random();
private SwingWorker<Boolean, Integer> worker;

public ShapesPanel(List<ShapeItem> shapesList) {
    this.shapes = shapesList;
    worker = new SwingWorker<Boolean, Integer>() {            

        @Override
        protected Boolean doInBackground() throws Exception {
            while (true) {
                Thread.sleep(200);
                int dim = rand.nextInt(300);
                publish(dim);                
                return true;
           }
        }

        @Override
        protected void done() {
            Boolean Status;
            try {                    
                Status = get();
                System.out.println(Status);
                super.done();                    //To change body of generated methods, choose Tools | Templates.
            } catch (InterruptedException ex) {
                Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        protected void process(List<Integer> chunks) {
            int mostRecentValue = chunks.get(chunks.size()-1);
            System.out.println(mostRecentValue);
                Color color2 = Color.LIGHT_GRAY;
                ShapeItem tmpShape = shapes.get(mostRecentValue);
                if(tmpShape.getColor()==Color.RED){
                    tmpShape.setColor(color2);
                }
                repaint();                
       }

    };
    worker.execute ();

    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            Color color1 = Color.LIGHT_GRAY;
            for (ShapeItem item : shapes) {
                if (item.getColor() == Color.BLUE) {
                    if (item.getShape().contains(e.getPoint())) {
                        item.setColor(color1);
                    }
                }
            }
            repaint();
        }
    });
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g.create();

    for (ShapeItem item : shapes) {
        g2.setColor(item.getColor());
        g2.fill(item.getShape());
    }

    g2.dispose();
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

private Color getRandomColor() {
    return new Color(rand.nextFloat(), rand.nextFloat(),
            rand.nextFloat());
}
公共类ShapePanel扩展了JPanel{
私有列表形状;
private Random rand=new Random();
私人荡秋千工人;
公共形状面板(列表形状列表){
this.shapes=shapesList;
worker=新SwingWorker(){
@凌驾
受保护的布尔值doInBackground()引发异常{
while(true){
睡眠(200);
int dim=兰特nextInt(300);
出版(dim);
返回true;
}
}
@凌驾
受保护的void done(){
布尔状态;
试试{
Status=get();
系统输出打印项次(状态);
super.done();//若要更改生成的方法体,请选择工具|模板。
}捕获(中断异常例外){
Logger.getLogger(shapePanel.class.getName()).log(Level.SEVERE,null,ex);
}捕获(ExecutionException ex){
Logger.getLogger(shapePanel.class.getName()).log(Level.SEVERE,null,ex);
}
}
@凌驾
受保护的无效进程(列表块){
int mostRecentValue=chunks.get(chunks.size()-1);
系统输出打印项次(mostRecentValue);
Color color2=颜色。浅灰色;
ShapeItem tmpShape=shapes.get(mostRecentValue);
if(tmpShape.getColor()==Color.RED){
tmpShape.setColor(color2);
}
重新油漆();
}
};
worker.execute();
addMouseListener(新的MouseAdapter(){
@凌驾
公共无效mouseClicked(MouseEvent e){
Color color1=颜色。浅灰色;
用于(形状项:形状){
if(item.getColor()==Color.BLUE){
如果(item.getShape()包含(e.getPoint())){
项目。设置颜色(颜色1);
}
}
}
重新油漆();
}
});
}
@凌驾
受保护组件(图形g){
超级组件(g);
Graphics2D g2=(Graphics2D)g.create();
用于(形状项:形状){
g2.setColor(item.getColor());
g2.填充(item.getShape());
}
g2.dispose();
}
@凌驾
公共维度getPreferredSize(){
返回新维度(300300);
}
私有颜色getRandomColor(){
返回新颜色(rand.nextFloat(),rand.nextFloat(),
rand.nextFloat());
}

}

如果我正确理解了您的代码,您正在制作一个游戏,人类玩家必须尽可能快地单击其所有形状,而PC也随机单击形状。第一个清除所有形状的人获胜

如果这是正确的,您可能需要将您的
SwingWorker
调整为

  • 循环直到游戏结束。当前,由于
    return
    语句,循环在第一次到达循环结束时退出
  • 因为您并没有对
    SwingWorker
    的布尔返回值执行任何操作,所以您最好让它返回void
  • 无需在
    done
    方法中调用
    get
    。调用该方法时,
    SwingWorker
    已完成。你似乎只对中间结果感兴趣
  • 过程
    方法中,您可能希望循环所有值。请注意,
    过程
    方法不会在每次发布内容时调用。当EDT(事件调度线程)可用时,您发布的值将被分组并批量传递给
    进程
    方法

所以。。。问题出在哪里?工人工作不正常。正如您在屏幕截图中所看到的,没有一个矩形变为灰色…您的doInBackground()在第一次循环迭代后结束。非常感谢@Robin,您的回答为我澄清了Swing Workers,问题有望得到解决:)@Mahdi Rashidi get返回异常或结果,请谨慎使用