Литмир - Электронная Библиотека
Содержание  
A
A

'–

If (m_playfieldManager Is Nothing) Then Exit Sub

'–

'Give all the characters a chance to move

'–

m_playfieldManager.MoveCharactersOnPlayfield()

'–

'Render the playfield and all of the objects onto the form

'–

m_myFormsGraphics.DrawImage(m_playfieldManager. _

RenderPlayField(), GAME_SCREEN_DX, GAME_SCREEN_DY)

End Sub

В панели Properties, для формы Form1, на вкладке Events дважды щёлкаем по имени события MouseDown. Появившийся шаблон после записи нашего кода принимает следующий вид.

Листинг 22.9. Метод-обработчик события.

Private Sub Form1_MouseDown(ByVal sender As System.Object, _

ByVal e As System.Windows.Forms.MouseEventArgs) _

Handles MyBase.MouseDown

'Make sure there is a game we are playing

If Not (m_playfieldManager Is Nothing) Then

If e.Button = MouseButtons.Right Then

m_playfieldManager.HankTheWonderCaveman. _

MakeHankJump()

Else

'–

'Figure out where on the game playfield we clicked

'–

Dim x_GAME As Integer

Dim y_GAME As Integer

x_GAME = e.X – GAME_SCREEN_DX

y_GAME = e.Y – GAME_SCREEN_DY

'Let Hank figure out what to do

m_playfieldManager.HankTheWonderCaveman. _

setHanksDestination(x_GAME, y_GAME)

End If

End If

End Sub

Мы закончили написание программы в главный класс Form1 (для формы Form1 с пользовательским интерфейсом игры).

Теперь в наш проект добавляем новые файлы (для программирования соответствующих игровых действий). Добавить в проект файл можно по двум вариантам.

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

По второму варианту, в панели Solution Explorer выполняем правый щелчок по имени проекта и в контекстном меню выбираем Add, New Item, в панели Add New Item выделяем шаблон Code File, в окне Name записываем имя BorisTheMenacingBird.vb и щёлкаем кнопку Add. В проект (и в панель Solution Explorer) добавляется этот файл, открывается пустое окно редактирования кода, в которое записываем код со следующего листинга.

Листинг 22.10. Новый файл.

'–

'This class represents one of the characters in the game,

' "BorisTheMenacingBird"

'

'It contains logic for the rendering and movement of the character

'–

Public Class BorisTheMenacingBird

Inherits DrawablePlayfieldMultiFrameBitmap

Private m_yVelocityBoris As Integer      'How fast are _

'we traveling vertically?

Private m_xVelocityBoris As Integer      'How fast are we

'traveling vertically?

Const MAX_DY_BORIS_FLYING = 4

Private m_y_accelerationBorris As Integer

Private m_world_I_Inhabit As PlayFieldManager

Private m_myModeOfMovement As ModeOfMovement

Public Enum ModeOfMovement As Integer

 Flying = 1

End Enum

'When did we last update a flipped image

Private m_lastTickCountWhenImageFlipped As Integer

Const DTIME_TO_FLAP_WINGS = 400      'Every 600 ms we should

'flap our wings

'–

'These are the current image states for Hank

'–

Private Enum BorisImagesIndexes

 flyLeft1 = 1

 flyLeft2 = 2

End Enum

'–

'[in] X,Y : Position to start Hank at

'[in] worldHankInhabits : Playfield in which Hank lives

'–

Sub New(ByVal x As Integer, ByVal y As Integer, _

ByVal world_I_Inhabit As PlayFieldManager)

 '–

 'Get the bitmaps for our character

 '–

 Dim col As Collection

 col = g_FlyingBirdPictureCollection()

 m_world_I_Inhabit = world_I_Inhabit

 ChangeMyMovementState(ModeOfMovement.Flying)

 'Start him off as falling.

 'Initialize our base class with these…

 MyBase.Initialize_DrawableMultiPlayfiedBitmapObject( _

x, y, col, True)

 'Set the image index

 Me.CurrentFrameIndex = BorisImagesIndexes.flyLeft1

 'Set Boris' speed

 m_xVelocityBoris = -4

 m_y_accelerationBorris = 1

 '–

 'Set the collision rectangle for Hank

 '–

 Const BORIS_COLLISION_STARTX = 11

 Const BORIS_COLLISION_DX = 31

 Const BORIS_COLLISION_STARTY = 6

 Const BORIS_COLLISION_DY = 7

 Me.CollisionRectangle = New Rectangle( _

BORIS_COLLISION_STARTX, BORIS_COLLISION_STARTY, _

BORIS_COLLISION_DX, BORIS_COLLISION_DY)

End Sub

'–

'This function should be called to bring about any change

'of state

'It sets/resets any other variables we need to when we deal

'with state transitions

'–

Private Sub ChangeMyMovementState(ByVal newState As _

ModeOfMovement)

 m_myModeOfMovement = newState

End Sub

'–

'MOVE Boris

'

'This function is called to move the character on the screen

Конец ознакомительного фрагмента.

Текст предоставлен ООО «ЛитРес».

Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.

Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.

21
{"b":"813074","o":1}