从随机位置获取坐标并使用它们

时间:2015-03-12 21:04:34

标签: java android button random set

我的代码应该是这样的:

你看到一个暗按钮(可点击,[start_time])和一个灰色按钮(不可点击,[buttongame1])。 buttongame1预测,start_time接下来会在哪里移动。 当你单击start_time时,start_time移动到buttongame1的x和y。 与此同时,buttongame1将其位置随机设置为新的。 现在,当您单击start_time时,start_time将移动到buttongame1的新x和y。 同时,buttongame1将其位置随机设置为新的,依此类推。

我试过这个,但问题是,我无法获得或使用x& y来自buttongame1

public void onClick(View v) {

    int x0;
    int y0;
    int x1;
    int y1;
    int x2;
    int y2;
    int x3;
    int y3;
    int x4;
    int y4;
    int x5;
    int y5;
    int x6;
    int y6;
    textview1 = (TextView) findViewById(R.id.over);


    Random r = new Random();
    RelativeLayout decorView = (RelativeLayout) buttongame1.getParent();

    int screenWidth = decorView.getWidth();
    int screenHeight = decorView.getHeight();

    i++;

    if(v == gameover){
        i--;
        btncounter.setText("GAME OVER");
        start_time.setVisibility(View.GONE);
        textview1.setVisibility(View.VISIBLE);
        Animation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(50); //You can manage the time of the blink with this parameter
        anim.setStartOffset(20);
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(Animation.INFINITE);
        textview1.startAnimation(anim);
        Toast.makeText(this, "GAME OVER", Toast.LENGTH_SHORT).show();

        finish();
    }

    if (i == 0 ) {
        btncounter.setText("0");
        buttongame1.setX(r.nextInt(screenHeight - buttongame1.getWidth()));
        buttongame1.setY(r.nextInt(screenHeight - buttongame1.getHeight()));
        int x0 = (int) buttongame1.getX();
        int y0 = (int) buttongame1.getY();
    }

    if (i == 1 ) {
        btncounter.setText("1");
        startTime = System.currentTimeMillis();
        buttongame1.setX(r.nextInt(screenHeight - buttongame1.getWidth()));
        buttongame1.setY(r.nextInt(screenHeight - buttongame1.getHeight()));
        int x1 = (int) buttongame1.getX();
        int y1 = (int) buttongame1.getY();
        start_time.setX((x1));
        start_time.setY(y1);

// ... and so on

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,只需在更改之前从buttongame1获取X和Y.

     if (i == 1 ) {
            btncounter.setText("1");
             startTime = System.currentTimeMillis();
            int x1 = (int) buttongame1.getX();
            int y1 = (int) buttongame1.getY();
             buttongame1.setX(r.nextInt(screenHeight - buttongame1.getWidth()));
             buttongame1.setY(r.nextInt(screenHeight - buttongame1.getHeight()));

            start_time.setX((x1));
            start_time.setY(y1);
   }

此代码也是:

   if (i == 0 ) {
            btncounter.setText("0");
            int x0 = (int) buttongame1.getX();
            int y0 = (int) buttongame1.getY();
             buttongame1.setX(r.nextInt(screenHeight - buttongame1.getWidth()));
             buttongame1.setY(r.nextInt(screenHeight - buttongame1.getHeight()));

   }