如何在窗格上的随机位置放置形状?

时间:2016-04-16 19:53:45

标签: java

我正在制作一个最终项目并制作一个游戏,其中有一个点会随机移动一个窗口,当点击它时,用户得分会增加。我想知道如何每半秒左右随机移动一个点。这是我到目前为止的所有代码,谢谢!

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


public class CatchTheDot extends Application{

//create ball for game
public static Circle dot;

//create pane to run game
public static Pane window;

//create score counter
int score = 0;

//creat random
Random r = new Random((21)+1);

@Override
public void start(Stage primaryStage) throws Exception {

    window.getChildren().addAll(dot);

    // create scene and place on pane
    Scene s = new Scene(window, 800, 800);
    primaryStage.setTitle("Catch The Dot");
    primaryStage.setScene(s);
    primaryStage.show();

    //move dot
    Timer timer = new Timer();
    timer.schedule(new TimerTask() 
        {
        @Override
        public void run(){
        window.getChildren().remove(dot);
        int randX = 1 + (int)(Math.random()*800);
        int randY = 1 + (int)(Math.random()*800);
        window.add(dot, randX, randY);
        }
        }, 0, 5000);        


    // create listener
    ActionEvent mouseClicked(ActionEvent event)
    {
        if(event.getSource()==dot)
        {
            score = score + 10;
            if(score == 50)
            {
                popUp(primaryStage);
            }
        }
    }
}

public void popUp(final Stage primaryStage)
{
    primaryStage.setTitle("You won!");
    final Popup popup = new Popup();
    popup.setX(300);
    popup.setY(200);
    Text t = new Text("You won! Nice job!");
    Text tt = new Text("Play again?");
    Button yes = new Button("yes");
    Button no = new Button("no");
    popup.getContent().addAll(t, tt, yes, no);
    yes.setOnAction(e -> Yes());
    no.setOnAction(e -> No());
}

public void Yes()
{
    restartGame();
}
public void No()
{
    System.exit(0);
}
public void restartGame()
{
    score = 0;

}
public static void main(String[] args)
{
    launch(args);
}

}

1 个答案:

答案 0 :(得分:-1)

我建议使用Random而不是使用Math.random()。

DEPENDS_${PN} = "python-cython \
                  python-pyserial"

其余的看起来没问题。