-4

我想做的是从构成等边三角形的三个点开始。我的代码应该随机选择三个点中的两个,计算一个中点 (m),然后绘制它。然后从它生成的中点 m 开始,代码将随机选择三个原始点中的另一个并计算一个新的中点 (m2)。最后一步应重复 10,000 次。我刚开始使用 Java,我真的迷路了。我最大的问题是不知道怎么随机取点,也不知道怎么从取两个原点的中点到取旧中点和一个原点的中点. 这是我到目前为止的代码(请随时指出我在代码中犯的任何错误!):

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Dimension;

public class Game
{
    static final int HEIGHT = 500;
    static final int WIDTH = 500;

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("The Game");
        Board board = new Board(WIDTH, HEIGHT);
        Point p1 = new Point(0,0);
        Point p2 = new Point(500, 0);
        Point p3 = new Point(0, 250);

        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(board);

        board.addPoint(p1);
        board.addPoint(p2);
        board.addPoint(p3);

        frame.pack();
        frame.setVisible(true);

    }
}

class Board extends JPanel
{
    public Board(int h, int w)
    {
        setPreferredSize(new Dimension(w, h));
    }

    public void addPoint(Point p)
    {

        points.add(p);
    }


    public void paint(Graphics g)
    {
        super.paint(g);

        int i = 0;

        while (i < 10000)
            {
                board.add();
                i++;
            }

    }
}

class Point
{
    int x;
    int y;

    public Point(int x, int y)
    {
        x = this.x;
        y = this.y;
    }

    private static Point midPoint(Point p1, Point p2)
        {
            return new Point((p1.x + p2.x)/2, (p1.y + p2.y)/2);
        }

    public double getX()
    { 
        return x;
    }   

    public double getY()
    { 
        return y;
    }

}
4

2 回答 2

1

拆分问题。首先,使用您的算法生成 100000 个点并将它们添加到列表中。

如果您有 3 个点的列表,并且您想随机选择两个,那么Collections.shuffle()列表并首先选择两个。

在paint方法中,简单地迭代列表并绘制点。无需重建列表。

(是的,你可以在paint方法中做所有事情并节省一些内存,但我认为你稍微整理一下你的想法对你有好处:-)

编辑:

顺便说一句,您示例中的三角形不是等边的。

于 2013-05-16T17:00:15.183 回答
0

要选择三个点之一,首先选择一个从 0 到 1 的随机数(使用Math.random())。如果数字小于 1/3 取第一点,如果在 1/3 和 2/3 之间取第二点,否则取第三点。例子:

 double r = Math.random();

 if ( r < 1.0/3) {
      // Chose first point
 } else if (r < 2.0/3) {
      // Choose second point
 } else {
      // Choose third point 
 }
于 2013-05-16T16:49:16.410 回答