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

Добавляем в наш проект (из отмеченной выше статьи или из Интернета) файл изображения помидора tomato.gif по стандартной схеме, а именно: в меню Project выбираем Add Existing Item, в этой панели в окне “Files of type” выбираем “All Files”, в центральном окне находим и выделяем имя файла и щёлкаем кнопку Add (или дважды щёлкаем по имени файла). В панели Solution Explorer мы увидим этот файл.

Теперь этот же файл tomato.gif встраиваем в проект в виде ресурса по разработанной выше схеме, а именно: в панели Solution Explorer выделяем появившееся там имя файла, а в панели Properties (для данного файла) в свойстве Build Action (Действие при построении) вместо заданного по умолчанию выбираем значение Embedded Resource (Встроенный ресурс).

Рис. 5.7. Помидоры – мишени. Рис. 5.8. Помидоры исчезают после попадания в них сыра.

Для программной реализации рисования и уничтожения помидоров после попадания в них сыра, в классе Form1 нашего проекта записываем следующий код.

Листинг 5.4. Переменные и методы для помидоров (tomatoes).

//We declare the object of the System.Drawing.Image class

//for product:

Image tomatoImage;

//Position and state of tomato

struct tomato

{

public Rectangle rectangle;

public bool visible;

}

// Spacing between tomatoes. Set once for the game

int tomatoSpacing = 4;

// Height, at which the tomatoes are drawn. Will change

// as the game progresses. Starts at the top.

int tomatoDrawHeight = 4;

// The number of tomatoes on the screen. Set at the start

// of the game by initialiseTomatoes.

int noOfTomatoes;

// Positions of the tomato targets.

tomato[] tomatoes;

// called once to set up all the tomatoes.

void initialiseTomatoes

{

noOfTomatoes = (this.ClientSize.Width – tomatoSpacing) /

(tomatoImage.Width + tomatoSpacing);

// create an array to hold the tomato positions

tomatoes = new tomato[noOfTomatoes];

// x coordinate of each potato

int tomatoX = tomatoSpacing / 2;

for (int i = 0; i < tomatoes.Length; i++)

{

tomatoes[i].rectangle =

new Rectangle(tomatoX, tomatoDrawHeight,

tomatoImage.Width, tomatoImage.Height);

tomatoX = tomatoX + tomatoImage.Width + tomatoSpacing;

}

}

// Called to place a row of tomatoes.

private void placeTomatoes

{

for (int i = 0; i < tomatoes.Length; i++)

{

tomatoes[i].rectangle.Y = tomatoDrawHeight;

tomatoes[i].visible = true;

}

}

Приведённый выше код в теле метода Form1_Paint заменяем на тот, который дан на следующем листинге.

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

private void Form1_Paint(object sender, PaintEventArgs e)

{

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

if (backBuffer == null)

{

backBuffer = new Bitmap(this.ClientSize.Width,

this.ClientSize.Height);

}

//We create a object 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 the backBuffer:

g.DrawImage(cheeseImage, cx, cy);

g.DrawImage(breadImage, bx, by);

for (int i = 0; i < tomatoes.Length; i++)

{

if (tomatoes[i].visible)

{

g.DrawImage(tomatoImage,

tomatoes[i].rectangle.X,

tomatoes[i].rectangle.Y);

}

}

}

//We draw the image on the Form1:

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

} //End of the method Form1_Paint.

Добавление новых объектов в игру соответственно усложняет код. В панели Properties (для Form1) на вкладке Events дважды щёлкаем по имени события Load. Появившийся шаблон метода Form1_Load после записи нашего кода принимает следующий вид.

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

private void Form1_Load(object sender, EventArgs 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);

//We load the tomato:

tomatoImage =

new Bitmap(myAssembly.GetManifestResourceStream(

myName_of_project + "." + "tomato.gif"));

//We initialize an array of tomatoes and rectangles:

initialiseTomatoes;

//We place the tomatoes in an upper part of the screen:

placeTomatoes;

//We turn on the timer:

timer1.Enabled = true;

}

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

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

private void updatePositions

{

if (goingRight)

{

cx += xSpeed;

}

else

{

cx -= xSpeed;

}

if ((cx + cheeseImage.Width) >= this.Width)

{

goingRight = false;

//At the time of collision, the Beep signal is given:

Microsoft.VisualBasic.Interaction.Beep;

}

if (cx <= 0)

{

goingRight = true;

//At the time of collision, the Beep signal is given:

Microsoft.VisualBasic.Interaction.Beep;

}

if (goingDown)

{

Перейти на страницу:

Похожие книги