Валерий Алексеевич Жарков

Справочник Жаркова по проектированию и программированию искусственного интеллекта. Том 7: Программирование на Visual C# искусственного интеллекта. Издание 2


Скачать книгу

структуры Rectangle.

      Visual Basic (Declaration)

      Public Function IntersectsWith ( _

      rect As Rectangle _

      ) As Boolean

      Visual Basic (Usage)

      Dim instance As Rectangle

      Dim rect As Rectangle

      Dim returnValue As Boolean

      returnValue = instance.IntersectsWith(rect)

      C#

      public bool IntersectsWith (

      Rectangle rect

      )

      C++

      public:

      bool IntersectsWith (

      Rectangle rect

      )

      J#

      public boolean IntersectsWith (

      Rectangle rect

      )

      JScript

      public function IntersectsWith (

      rect : Rectangle

      ) : Boolean

      Этот метод IntersectsWith обнаруживает пересечение заданного нами первого прямоугольника со вторым прямоугольником, объявленного здесь как параметр (Rectangle rect).

      Если метод определит, что ни одна точка одного прямоугольника не находится внутри другого прямоугольника, то метод возвращает булево значение False.

      А если метод определит, что хотя бы одна точка одного прямоугольника находится внутри другого прямоугольника, то метод IntersectsWith возвращает булево значение True, и это значение применяется для изменения направления движения какого-либо прямоугольника на противоположное (чтобы уйти от дальнейшего пересечения), например, в таком коде:

      //We check the collision of objects:

      if (cheeseRectangle.IntersectsWith(breadRectangle))

      {

      //We change the direction of the movement to opposite:

      goingDown = !goingDown;

      //At the time of collision, we give a sound signal Beep:

      Microsoft.VisualBasic.Interaction.Beep();

      }

      5.3. Код и выполнение программы

      Теперь в проекте, который мы начали разрабатывать в предыдущей главе (и продолжаем в данной главе) объявляем два прямоугольника, а приведённый выше код в теле метода Form1_Paint заменяем на тот, который дан на следующем листинге (с подробными комментариями).

      Листинг 5.1. Метод для рисования изображения.

      //The rectangle, described around the first object:

      Rectangle cheeseRectangle;

      //The rectangle, described around the second object:

      Rectangle breadRectangle;

      private void Form1_Paint(object sender, PaintEventArgs e)

      {

      //We load into objects of class System.Drawing.Image

      //the image files of the set format, added to the project

      //by means of ResourceStream:

      cheeseImage =

      new Bitmap(myAssembly.GetManifestResourceStream(

      myName_of_project + "." + "cheese.JPG"));

      breadImage =

      new Bitmap(myAssembly.GetManifestResourceStream(

      myName_of_project + "." + "bread.JPG"));

      //We initialize the rectangles, described around objects:

      cheeseRectangle = new Rectangle(cx, cy,

      cheeseImage.Width, cheeseImage.Height);

      breadRectangle = new Rectangle(bx, by,

      breadImage.Width, breadImage.Height);

      //If it is necessary, we create the new buffer:

      if (backBuffer == null)

      {

      backBuffer = new Bitmap(this.ClientSize.Width,

      this.ClientSize.Height);

      }

      //We createobject of the Graphics class from the buffer:

      using (Graphics g = Graphics.FromImage(backBuffer))

      {

      //We clear the form:

      g.Clear(Color.White);

      //We draw the image in backBuffer:

      g.DrawImage(cheeseImage, cx, cy);

      g.DrawImage(breadImage, bx, by);

      }

      //We draw the image on Form1:

      e.Graphics.DrawImage(backBuffer, 0, 0);

      //We turn on the timer:

      timer1.Enabled = true;

      } //End of the method Form1_Paint.

      А вместо приведённого выше метода updatePositions для изменения координат записываем следующий метод, дополненный кодом для обнаружения столкновения объектов.

      Листинг 5.2. Метод для изменения координат и обнаружения столкновения объектов.

      private void updatePositions()

      {

      if (goingRight)

      {

      cx += xSpeed;

      }

      else

      {

      cx -= xSpeed;

      }

      if