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

Жарков Валерий

Шрифт:

За каждый сбитый помидор мы можем начислить игроку любое количество очков, например, 10 очков в строке:

scoreValue = scoreValue + 10;

Новые очки сразу же выводятся на экран, информируя игрока.

Рис. 5.9. Получили 20 очков за 2 сбитых помидора. Рис. 5.10. Получили 50 очков.

Приступим к программной реализации методики подсчёта очков в игре в нашем базовом учебном проекте.

Сначала мы должны опустить ряд помидоров пониже, чтобы освободить место вверху для записи очков, поэтому вместо 4 записываем ординату, равную, например, 20:

int tomatoDrawHeight = 20;

В любом месте класса Form1 добавляем новые переменные для счётчика очков.

Листинг 5.8. Новые переменные.

// Font for score messages.

Font messageFont = null;

// Rectangle for score display.

Rectangle messageRectangle;

// Height of the score panel.

int scoreHeight = 20;

// Brush used to draw the messages.

SolidBrush messageBrush;

// The string, which is drawn as the user message.

string messageString = "Score : 0";

// Score in a game.

int scoreValue = 0;

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

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

private void Form1_Paint(object sender, PaintEventArgs e)

{

//If the buffer empty, we create the new buffer:

if (backBuffer == null)

{

backBuffer = new Bitmap(this.ClientSize.Width,

this.ClientSize.Height);

}

//We create a object of class Graphics from the buffer:

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

{

//We clear the form:

g.Clear(Color.White);

//We draw the images of objects 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 write the player's points:

g.DrawString(messageString, messageFont, messageBrush,

messageRectangle);

}

//We draw the image on the Form1:

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

} //End of the method Form1_Paint.

Приведённый выше код в теле метода Form1_Load (для загрузки файлов изображений игровых объектов) заменяем на тот, который дан на следующем листинге.

Листинг 5.10. Метод для загрузки файлов изображений.

private void Form1_Load(object sender, EventArgs e)

{

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

//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 image file of a new object:

tomatoImage =

new Bitmap(myAssembly.GetManifestResourceStream(

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

//We initialize an array of new objects and rectangles,

//described around these objects:

initialiseTomatoes;

//We place new objects in an upper part of the screen:

placeTomatoes;

//We create and initialize a font for record of points:

messageFont = new Font(FontFamily.GenericSansSerif, 10,

FontStyle.Regular);

//We reserve a rectangle on the screen

//for record of points:

messageRectangle = new Rectangle(0, 0,

this.ClientSize.Width, scoreHeight);

//We set the color of a brush for record of points:

  • Читать дальше
  • 1
  • ...
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Ебукер (ebooker) – онлайн-библиотека на русском языке. Книги доступны онлайн, без утомительной регистрации. Огромный выбор и удобный дизайн, позволяющий читать без проблем. Добавляйте сайт в закладки! Все произведения загружаются пользователями: если считаете, что ваши авторские права нарушены – используйте форму обратной связи.

Полезные ссылки

  • Моя полка

Контакты

  • chitat.ebooker@gmail.com

Подпишитесь на рассылку: