0

私は課題に取り組んでいますが、1 つの要件で行き詰っています。私はできる限り誠意を持って努力してきましたが、謙虚にあなたの専門知識を求めるしかありません。私の課題では、Java で単純なゲームを作成する必要があります。このゲームでは、画像がランダムに表示され、ランダムに再表示されます。ユーザーは画像をクリックすることになっており、ユーザーが画像をクリックすると、クリック数が画面に出力されます。私の主な質問は、ランダムな期間、ランダムな位置に画像を表示/再表示させるにはどうすればよいですか? 期間をランダムにするには、タイマーで何らかの方法で設定しますか? 私はそれを試しましたが、うまくいきませんでした。ランダムな位置については、コーディングを開始する方法さえわかりません。誰かが私を正しい方向に向けることができますか? actionPerformed メソッドでそれを行いますか?

とにかく、これまでのところ私のコードです。コンパイルされますが、動きと速度はスムーズで一定です。滑らかな一定の速度で「滑空」するのではなく、画像をランダムに表示/再表示する必要があります。

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;

public class CreatureClass extends JPanel
{

   private final int WIDTH = 400, HEIGHT = 300;
   private final int DELAY=20, IMAGE_SIZE = 60;

   Random r = new Random();
   private ImageIcon image;
   private Timer timer;
   private int x, y, moveX, moveY;
   private int catchCount=0;

   //-----------------------------------------------------------------
   //  Sets up the panel, including the timer for the animation.
   //-----------------------------------------------------------------
   public CreatureClass()
   {
      timer = new Timer(DELAY, new CreatureListener());//how to make duration random here?

      addMouseListener (new MouseClickedListener());

      image = new ImageIcon ("UMadBro.gif");

      x = 0; //starting coordinates of image
      y = 40;

      moveX = moveY = 3;//image is shifted 3 pixels every time image is updated. I  
                        // tried setting these to a random number, but it makes the 
                        // image "stuck" in one position. 

      setPreferredSize (new Dimension(WIDTH, HEIGHT));
      setBackground (Color.yellow);
      timer.start();
   }

   //-----------------------------------------------------------------
   //  Draws the image in the current location.
   //-----------------------------------------------------------------
   public void paintComponent (Graphics page)
   {
      super.paintComponent (page);
      image.paintIcon (this, page, x, y);
      page.drawString("Number of clicks: " + catchCount, 10, 15);

   }
   //*****************************************************************
   // Detects when mouse clicked=image postition
   //*****************************************************************
   public boolean pointInMe(int posX, int posY)
   {
      if(x == posX && y == posY)
      {
         catchCount++;
         return true;
      }
      return false;
      }
   public int getCatchCount()
   {
      return catchCount;
   }

   private class MouseClickedListener extends MouseAdapter
   {

      public void mouseClicked (MouseEvent event)
      {
         pointInMe(event.getX(), event.getY());

      }
   }

   //*****************************************************************
   //  Represents the action listener for the timer.
   //*****************************************************************
   private class CreatureListener implements ActionListener
   {
      //--------------------------------------------------------------
      //  Updates the position of the image and possibly the direction
      //  of movement whenever the timer fires an action event.
      //  (I don't know how to make the image appear and reappear
      //   randomly for random durations)
      //--------------------------------------------------------------

      public void actionPerformed (ActionEvent event)
      {

         x += moveX;
         y += moveY;

         if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
            moveX = moveX * -1;

         if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
            moveY = moveY * -1;

        repaint();

      }
    }
 }
4

3 に答える 3

0

...滑らかな一定速度で「滑空」する代わりに。

CreatureListener はアニメーションを担当します。これを新しい ActionListener クラス、RandomCreatureListener に置き換えましょう。

timer = new Timer(DELAY, new RandomCreatureListener());

「r」フィールド (ランダム) は未使用のようです。RandomCreatureListener で適用する必要があることがヒントになります。例えば

x = r.nextInt(WIDTH - IMAGE_SIZE);
y = r.nextInt(WIDTH - IMAGE_SIZE);

目的のランダムなポップアップが表示されますが、速度は非常に高速です。速度を落とす必要があります。

これは課題なので、あなたに任せます。

于 2013-10-11T05:58:17.773 に答える
0

rという名前の java.util.Random のインスタンスを定義したように見え、その他の必要な機能はすべて実装されています。それでは、コードを変更してみませんactionPerformed

x = r.nextInt(WIDTH-IMAGE_SIZE);
y = r.nextInt(HEIGHT-IMAGE_SIZE);

これはあなたの要件に合うはずです。

(コメントでこの簡単な提案を直接行うには、私の評判が不十分で申し訳ありません。:(

于 2013-10-11T05:55:30.717 に答える
0

これは本当に良いスタートです。

私がすることは、使い捨ての(繰り返しのない) Swing を作成することですTimer。これは、ランダムな遅延 (たとえば 1 ~ 5 秒) で開始されます。

それが時を刻むとき、あなたは現在の状態を判断します。クリーチャーが表示されている場合は、メインを停止する必要がありますtimer(表示されていない間は位置を更新してもほとんど意味がないため)、ビューを停止し、新しいランダム値でrepaint非表示/表示をリセットする必要があります。Timer

クリーチャーが見えない場合は、新しい x/y 座標と移動方向を計算し、メインを再起動して、新しいランダム値でtimer非表示/表示をリセットする必要があります。Timer

paintComponentメソッドでは、単純なフラグをチェックしてvisibleクリーチャーの現在の状態を判断し、クリーチャーをペイントする必要があるかどうかを判断します。

例えば...

(注:outTimerjavax.swing.Timervisiblebooleanrndですjava.util.Random)

outTimer = new Timer(1000 + (int)(Math.random() * 4000), new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Are we currently visible or not
        if (!visible) {
            // Calculate the x/y position
            x = (int) (Math.random() * (WIDTH - IMAGE_SIZE));
            y = (int) (Math.random() * (HEIGHT - IMAGE_SIZE));

            // Calculate a random speed
            int xSpeed = (int) (Math.random() * 4) + 1;
            int ySpeed = (int) (Math.random() * 4) + 1;

            // Calculate the direction based on the speed
            moveX = rnd.nextBoolean() ? xSpeed : -xSpeed;
            moveY = rnd.nextBoolean() ? ySpeed : -ySpeed;
            // Restart the main timer
            timer.start();
        } else {
            // Stop the main timer
            timer.stop();
        }
        // Flip the visible flag
        visible = !visible;
        repaint();
        // Calculate a new random time
        outTimer.setDelay(1000 + (int)(Math.random() * 4000));
        outTimer.start();
    }
});
// We don't want the timer to repeat
outTimer.setRepeats(false);
outTimer.start();

timerまた、メインの初期遅延を0,に設定することをお勧めしますtimer.setInitialDelay(0);。これにより、最初の起動時にすぐに起動できます

于 2013-10-11T05:56:43.047 に答える