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

Листинг 20.14. Метод, вызываемый через Interval времени.

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

ByVal e As System.EventArgs) Handles Timer1.Tick

' Add another row to the grid and update the screen.

matrix.AddRow()

matrix.Draw(Me.PictureBox1.CreateGraphics(), _

Me.PictureBox1.BackColor)

End Sub

Чтобы в верхней части формы (на синей полоске для свойства Text) после начала игры шел отсчёт времени (Time), ниже формы дважды щёлкаем по значку для второго таймера Timer2 (или в панели Properties для этого компонента на вкладке Events дважды щёлкаем по имени события Tick). Появляется шаблон метода, который после записи нашего кода принимает следующий вид.

Листинг 20.15. Метод, вызываемый через Interval времени.

'Счётчик секунд, который обнуляем в начале каждой игры

'в методе StartNewGame:

Dim secondCounter As Integer

'Время окончания игры:

Dim EndGameTime As Integer = 60

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

ByVal e As System.EventArgs) Handles Timer2.Tick

secondCounter = secondCounter + 1

Me.Text = "Time : " & secondCounter.ToString()

'Мелодия окончания игры:

If secondCounter = EndGameTime Then

My.Computer.Audio.Play( _

"..\..\Resources\win.wav", _

AudioPlayMode.Background)

End If

End Sub

Схема записи и вывода справочной информации, например, с правилами игры после выбора команды Contents (для элемента управления MenuStrip) и после выбора других команд уже приводилась в наших предыдущих работах.

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

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

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

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

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

Imports System.Drawing.Drawing2D

''' <summary>

''' This class represents one of the balls in the game grid.

''' </summary>

''' <remarks></remarks>

Public Class Block

Public Const BlockSize As Integer = 25

Private colorValue As Color

Private deletionValue As Boolean = False

Private Shared rand As New Random

Public Property Color() As Color

Get

Return colorValue

End Get

Set(ByVal Value As Color)

colorValue = Value

End Set

End Property

Public Property MarkedForDeletion() As Boolean

Get

Return deletionValue

End Get

Set(ByVal Value As Boolean)

deletionValue = Value

End Set

End Property

Public Sub New(ByVal newColor As Color)

colorValue = newColor

End Sub

Public Sub New(ByVal colors() As Color)

Dim ncolors As Integer = colors.Length

Dim pickedColor As Integer

pickedColor = rand.Next(0, ncolors)

colorValue = colors(pickedColor)

End Sub

Public Sub Draw(ByVal graphics As Graphics, ByVal point As Point)

Dim brush As System.Drawing.Drawing2D.LinearGradientBrush = _

CreateTheBrush(point)

DrawTheCircle(graphics, brush, point)

End Sub

Private Sub DrawTheCircle(ByVal graphics As Graphics, _

ByVal brush As LinearGradientBrush, ByVal location As Point)

Dim topleft As Point = location

Dim bottomright As Point = New Point(location.X + _

BlockSize, location.Y + BlockSize)

Dim transTopLeft As Point = PointTranslator.TranslateToBL( _

topleft)

Dim transBottomRight As Point = _

PointTranslator.TranslateToBL(bottomright)

Dim transwidth As Integer = transBottomRight.X – transTopLeft.X

Dim transheight As Integer = _

transBottomRight.Y – transTopLeft.Y

graphics.FillEllipse(brush, New Rectangle(transTopLeft, _

New Size(transwidth, transheight)))

End Sub

Private Function CreateTheBrush(ByVal location As Point) As _

LinearGradientBrush

Dim transLocation As Point = _

PointTranslator.TranslateToBL(location)

Dim brushpt1 As Point = transLocation

Dim brushpt2 As New Point(transLocation.X + Block.BlockSize _

+ 4, transLocation.Y – BlockSize – 4)

Dim brush As New LinearGradientBrush(brushpt1, _

brushpt2, Me.Color, System.Drawing.Color.White)

Return brush

End Function

End Class

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

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

''' <summary>

''' This class represents the grid of blocks. It handles most of

''' the game play.

''' </summary>

''' <remarks></remarks>

Public Class Grid

' The grids is 12 columns and 15 rows of Block objects.

Dim matrix(11, 14) As Block

''' <summary>

''' Creates a few rows of blocks to start the game.

''' Game starts with Red, Blue, and Green blocks.

''' </summary>

''' <param name="nrows">Number of rows of blocks to create

''' to start the game.</param>

''' <remarks></remarks>

Public Sub New(ByVal nrows As Integer)

If nrows > matrix.GetLength(0) Then

Throw New Exception("Must start with " & _

matrix.GetLength(0) & " or fewer rows.")

End If

Dim row As Integer

Dim column As Integer

For row = 0 To nrows – 1

For column = 0 To matrix.GetLength(1) – 1

matrix(row, column) = New Block( _

New Color() {Color.Red, Color.Blue, Color.Green})

Next

Next

For row = nrows To matrix.GetLength(0) – 1

For column = 0 To matrix.GetLength(1) – 1

matrix(row, column) = Nothing

Next

Next

End Sub

''' <summary>

''' A new row may be added at any time. New rows have Gray

''' blocks in addition

''' to Red, Blue, and Green. This makes the game more difficult.

''' </summary>

''' <remarks></remarks>

Public Sub AddRow()

Dim column As Integer

' Add a new block to each column.

For column = 0 To matrix.GetLength(1) – 1

Dim newBlock As New Block(New Color() _

{Color.Red, Color.Blue, Color.Green, Color.Gray})

' Add the new block at the botttom of the column,

' and push the rest of the

' blocks up one column.

For row As Integer = matrix.GetLength(0) – 1 To 1 Step -1

matrix(row, column) = matrix(row – 1, column)

Next

matrix(0, column) = newBlock

Next

End Sub

''' <summary>

''' Draw the grid of blocks

''' </summary>

''' <param name="graphics"></param>

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