Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

Нужно создать массив помидоров для размещения на экране, как показано в листинге 11.25.

Листинг 11.25

///

/// Расстояние между помидорами.

/// Устанавливаем один раз для игры

///

private int tomatoSpacing = 4;


///

/// Высота, на которой рисуется помидор

/// Высота может меняться в процессе игры

/// Начинаем с верхней части экрана

///

private int tomatoDrawHeight = 4;


///

/// Количество помидоров на экране.

/// Устанавливается при старте игры

/// методом initialiseTomatoes.

///

private int noOfTomatoes;


///

/// Позиции всех помидоров на экране

///

private tomato[] tomatoes;

При усложнении игры помидоры должны отображаться все ниже и ниже, заставляя пользователя действовать интуитивно. Переменная tomatoDrawHeight будет отвечать за эту задачу. Для инициализации местоположения помидоров нужно создать функцию initialiseTomatos, которая использует размеры помидоров и экрана. Ее код приведен в листинге 11.26.

Листинг 11.26

///

/// Вызывается один раз для установки всех помидоров

///

private void initialiseTomatoes() {

 noOfTomatoes =

  (this.ClientSize.Width - tomatoSpacing) /

  (tomatoImage.Width + tomatoSpacing);

 // создаем массив, содержащий позиции помидоров

 tomatoes = new tomato[noOfTomatoes];

 // Координата x каждого помидора

 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;

 }

}

Вызов этого метода следует разместить в конструкторе формы. Метод подсчитывает количество помидоров, создает массив структур и задает прямоугольники, определяющие позицию каждого помидора на экране. Теперь их надо разместить на форме в один ряд. Код, отвечающий за эти действия, приведен в листинг 11.27.

Листинг 11.27

///

/// Вызывается для создания ряда помидоров.

///

private void placeTomatoes() {

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

  tomatoes[i].rectangle.Y = tomatoDrawHeight;

  tomatoes[i].visible = true;

 }

}

Этот метод вызывается один раз при старте игры, а после этого он запускается после уничтожения очередного ряда томатов. Метод обновляет высоту с новым значением и делает изображения томатов видимыми. Вызов данного метода также размещается в конструкторе формы.

Итак, сейчас позиции всех томатов определены. Нужно вывести их изображения помидоров на экран. Код, приведенный в листинге 11.28, встраивается в обработчик события Form1_Paint.

Листинг 11.28

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

 if (tomatoes[i].visible) {

  g.DrawImage(tomatoImage, tomatoes[i].rectangle.X, tomatoes[i].rectangle.Y);

 }

}

Каждый раз, когда страница перерисовывается, этот код перерисовывает все видимые томаты. Естественно, для отображения всех томатов используется одно и то же изображение.

Чтобы сделать игру реалистичнее, нужно переместить начальную высоту батона чуть ниже, чтобы игрок мог сразу играть в игру с более подходящей позиции. Этот код приведен в листинге 11.29.

Листинг 11.29

breadRectangle = new Rectanglе(

 (this.ClientSize.Width - breadImage.Width) / 2,

 this.ClientSize.Height — breadImage.Height,

 breadImage.Width, breadImage.Height);

Теперь игра выглядит так, как показано на рис. 11.7

Рис. 11.7. Внешний вид игры

Уничтожение томатов

К сожалению, в данный момент при столкновении сыра с помидорами ничего не происходит. Ситуацию надо исправить при помощи кода, добавленного в метод updatePosition, который приведен в листинге 11.30.

Листинг 11.30

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

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

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных