Читать книгу «Справочник Жаркова по проектированию и программированию искусственного интеллекта. Том 6: Программирование на Visual Basic искусственного интеллекта. Продолжение 2» онлайн полностью📖 — Валерия Алексеевича Жаркова — MyBook.
image

''' 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>

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

''' <remarks></remarks>

Public Sub Draw(ByVal graphics As Graphics, _

ByVal backColor As Color)

graphics.Clear(backColor)

Dim row As Integer

Dim column As Integer

Dim theBlock As Block

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

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

theBlock = matrix(row, column)

If Not theBlock Is Nothing Then

Dim pointA As New Point( _

column * Block.BlockSize, _

row * Block.BlockSize)

matrix(row, column).Draw(graphics, pointA)

End If

Next

Next

End Sub

''' <summary>

''' This method responds to a click event in the UI.

''' </summary>

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

''' <returns>The number of blocks removed from the grid.</returns>

''' <remarks></remarks>

Public Function Click(ByVal point As Point) As Integer

' Figure out row and column.

Dim total As Integer

Dim transPt As Point = PointTranslator.TranslateToTL(point)

Dim selectedRow As Integer = transPt.Y \ Block.BlockSize

Dim selectedColumn As Integer = transPt.X \ Block.BlockSize

Dim selectedBlock As Block = matrix(selectedRow, _

selectedColumn)

If Not selectedBlock Is Nothing Then

selectedBlock.MarkedForDeletion = True

' Determine if any of the neighboring blocks are

' the same color.

FindSameColorNeighbors(selectedRow, selectedColumn)

' Determine how many blocks would be eliminated.

total = Me.CalculateScore()

If total > 1 Then

Me.CollapseBlocks()

Else

Me.ClearMarkedForDeletion()

End If

End If

Return total

End Function

Private Sub ClearMarkedForDeletion()

Dim row As Integer

Dim column As Integer

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

' If column is completely empty, then move everthing

' down one.

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

If Not matrix(row, column) Is Nothing Then

matrix(row, column).MarkedForDeletion = False

End If

Next

Next

End Sub

''' <summary>

''' Find out how many blocks will be eliminated.

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

Private Function CalculateScore() As Integer

Dim row As Integer

Dim column As Integer

Dim total As Integer = 0

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

' If column is completely empty, then move everthing

' down one.

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

If Not matrix(row, column) Is Nothing Then

If matrix(row, column).MarkedForDeletion Then

total += 1

End If

End If

Next

Next

Return total

End Function

''' <summary>

''' After the blocks are removed from the columns, there may be

''' columns that are empty. Move columns from right to left to

''' fill in the empty columns.

''' </summary>

''' <remarks></remarks>

Public Sub CollapseColumns()

Dim row As Integer

Dim column As Integer

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

' If column is completely empty, then all the columns

' over one.

Dim noBlocks As Boolean = True

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

If Not matrix(row, column) Is Nothing Then

noBlocks = False

End If

Next

If noBlocks Then

Dim newcol As Integer

For newcol = column To matrix.GetLength(1) – 2

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

matrix(row, newcol) = matrix(row, newcol + 1)

Next

Next

newcol = matrix.GetLength(1) – 1

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

matrix(row, newcol) = Nothing

Next

End If

Next

End Sub

''' <summary>

''' Remove all the blocks from the grid.

''' </summary>

''' <remarks></remarks>

Public Sub CollapseBlocks()

Dim theBlock As Block

Dim column As Integer

Dim row As Integer

Dim aRow As Integer

' First remove the blocks from each column.

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

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

theBlock = matrix(row, column)

If (Not theBlock Is Nothing) Then

If theBlock.MarkedForDeletion Then

For aRow = row To matrix.GetLength(0) – 2

matrix(aRow, column) = _

matrix(aRow + 1, column)

Next

matrix(matrix.GetLength(0) – 1, _

column) = Nothing

End If

End If

Next

Next

' Reset the MarkedForDeletion flags.

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

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

theBlock = matrix(row, column)

If Not theBlock Is Nothing Then

theBlock.MarkedForDeletion = False

End If

Next

Next

' Remove any columns that are now empty.

CollapseColumns()

End Sub

''' <summary>

''' Provides access into the grid.

''' </summary>

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

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

''' <value></value>

''' <remarks></remarks>

Default Public Property Item(ByVal row As Integer, _

ByVal column As Integer) As Block

Get

Return matrix(row, column)

End Get

Set(ByVal Value As Block)

matrix(row, column) = Value

End Set

End Property

Private blocksToExamine As ArrayList

''' <summary>

''' Set MarkedForDeletion to True for each neighboring block

''' of the same color.

''' </summary>

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

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

''' <remarks></remarks>

Private Sub FindSameColorNeighbors(ByVal row As Integer, _

ByVal column As Integer)

Dim color As Color = matrix(row, column).Color

blocksToExamine = New ArrayList

blocksToExamine.Add(New Point(row, column))

matrix(row, column).MarkedForDeletion = True

' Each time you find a neighbor, mark it for deletion, and

' add it to the list of blocks to look for neighbors.

' After you

' examine it, remove it from the list. Keep doing this

' until there are no more blocks to look at.

While blocksToExamine.Count > 0

FindNeighbors()

End While

End Sub

''' <summary>

''' Look to the blocks on each side.

''' </summary>

''' <remarks></remarks>

Private Sub FindNeighbors()

' Take the first block out of the arraylist and examine it.

Dim location As Point = CType(blocksToExamine(0), Point)

Dim currentBlock As Block = matrix(location.X, location.Y)

Dim row As Integer = location.X

Dim column As Integer = location.Y

blocksToExamine.RemoveAt(0)

Dim nextRow As Integer

Dim nextCol As Integer

Dim selected As Block

' look up

If row < matrix.GetLength(0) – 1 Then

nextRow = row + 1

selected = matrix(nextRow, column)

ExamineNeighbor(selected, nextRow, column, _

currentBlock.Color)

End If

' look down

If row > 0 Then

nextRow = row – 1

selected = matrix(nextRow, column)

ExamineNeighbor(selected, nextRow, column, _

currentBlock.Color)

End If

' look left

If column > 0 Then

nextCol = column – 1

selected = matrix(row, nextCol)

ExamineNeighbor(selected, row, nextCol, _

currentBlock.Color)

End If

' look right

If column < matrix.GetLength(1) – 1 Then

nextCol = column + 1

selected = matrix(row, nextCol)

ExamineNeighbor(selected, row, nextCol, _

currentBlock.Color)

End If

End Sub

''' <summary>

''' If the neighbor is the same color, add it to the blocks

''' to examine.

''' </summary>

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

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

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

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

''' <remarks></remarks>

Private Sub ExamineNeighbor(ByVal selected As Block, _

ByVal row As Integer, ByVal column As Integer, _

ByVal color As Color)

If Not selected Is Nothing Then

If selected.Color.Equals(color) Then

If Not selected.MarkedForDeletion Then

selected.MarkedForDeletion = True

blocksToExamine.Add(New Point(row, column))

End If

End If

End If

End Sub

End Class

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

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

''' <summary>

''' Represents one high score.

''' </summary>

''' <remarks></remarks>

Public Class HighScore

Implements IComparable

Public nameValue As String

Public scoreValue As Integer

Public Property Name() As String

Get

Return nameValue

End Get

Set(ByVal Value As String)

nameValue = Value

End Set

End Property

Public Property Score() As Integer

Get

Return scoreValue

End Get

Set(ByVal Value As Integer)

scoreValue = Value

End Set

End Property

Public Overrides Function ToString() As String

Return Name & ":" & Score

End Function

Public Sub New(ByVal saved As String)

Name = saved.Split(":".ToCharArray)(0)

Score = CInt(saved.Split(":".ToCharArray)(1))

End Sub

Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo

Dim other As HighScore

other = CType(obj, HighScore)

Return Me.Score – other.Score

End Function

End Class

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

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

Imports Microsoft.Win32

''' <summary>

''' Reads and writes the top three high scores to the registry.

''' </summary>

''' <remarks></remarks>

Public Class HighScores

''' <summary>

''' Read scores from the registry.

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function GetHighScores() As HighScore()

Dim tops(2) As HighScore

Dim scoreKey As RegistryKey = Registry.CurrentUser. _

CreateSubKey("Software\VBSamples\Collapse\HighScores")

For index As Integer = 0 To 2

Dim key As String = "place" & index.ToString

Dim score As New HighScore(CStr(scoreKey.GetValue(key)))

tops(index) = score

Next

scoreKey.Close()

Return tops

End Function

''' <summary>

''' Update and write the high scores.

''' </summary>

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

''' <remarks></remarks>

Public Shared Sub UpdateScores(ByVal score As Integer)

Dim tops(3) As HighScore

Dim scoreKey As RegistryKey = Registry.CurrentUser. _

CreateSubKey("Software\VBSamples\Collapse\HighScores")

tops(0) = New HighScore(scoreKey.GetValue("Place0").ToString)

tops(1) = New HighScore(scoreKey.GetValue("Place1").ToString)

tops(2) = New HighScore(scoreKey.GetValue("Place2").ToString)

If score > tops(2).Score Then

Dim name As String = InputBox("New high score of " & _

score & " for:")

tops(3) = New HighScore(" :0")

tops(3).Name = name

tops(3).Score = score

Array.Sort(tops)

Array.Reverse(tops)

scoreKey.SetValue("Place0", tops(0).ToString)

scoreKey.SetValue("Place1", tops(1).ToString)

scoreKey.SetValue("Place2", tops(2).ToString)

End If

scoreKey.Close()

End Sub

''' <summary>

''' Set up the entries for new scores.

''' </summary>

''' <remarks></remarks>

Shared Sub SetUpHighScores()

Dim scoreKey As RegistryKey = Registry.CurrentUser. _

CreateSubKey("Software\VBSamples\Collapse\HighScores")

If scoreKey.GetValue("Place1") Is Nothing Then

scoreKey.SetValue("Place0", " :0")

scoreKey.SetValue("Place1", " :0")

scoreKey.SetValue("Place2", " :0")

End If

scoreKey.Close()

End Sub

''' <summary>

''' Reset scores.

''' </summary>

''' <remarks></remarks>

Shared Sub ResetScores()

Dim scoreKey As RegistryKey = Registry.CurrentUser. _

CreateSubKey("Software\VBSamples\Collapse\HighScores")

scoreKey.SetValue("Place0", " :0")

scoreKey.SetValue("Place1", " :0")

scoreKey.SetValue("Place2", " :0")

scoreKey.Close()

End Sub

End Class

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

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

''' <summary>

''' Form coordinates have the top, left as (0,0). For the game grid,

''' it is easier to have the bottom left of the grid as (0,0). This

''' translates the points.

''' </summary>

''' <remarks></remarks>

Public Class PointTranslator

Private Shared graphicsValue As Graphics

Private Shared height As Integer

Public Shared Property Graphics() As Graphics

Get

Return graphicsValue

End Get

Set(ByVal Value As Graphics)

graphicsValue = Value

height = CInt(graphicsValue.VisibleClipBounds.Height())

End Set

End Property

' Translates an (X,Y) point from the top left to

' an (X, Y) point from the bottom left.

Public Shared Function TranslateToBL(ByVal topleft As Point) _

As Point

Dim newPoint As Point

newPoint.X = topleft.X

newPoint.Y = height – topleft.Y

Return newPoint

End Function

Public Shared Function TranslateToTL(ByVal bottomleft As Point) _

As Point

Dim newPoint As Point

newPoint.X = bottomleft.X

newPoint.Y = height – bottomleft.Y

Return newPoint

End Function

End Class

После этих добавлений ( Block.vb, Grid.vb, HighScore.vb, HighScores.vb, PointTranslator.vb) в панели Solution Explorer должны быть файлы, показанные выше. Дважды щёлкая по имени файла, любой файл можно открыть, изучить и редактировать.

Теперь в наш проект добавляем переменные и методы, связанные с формой Form2 для вывода результатов игры.

Открываем файл Form2.vb (например, по схеме: File, Open, File) и в классе Form2 нашего проекта записываем следующее свойство.

Листинг 20.21. Свойство.

Public Property SoundOn() As Boolean

Get

Return Me.isSoundOn.Checked

End Get

Set(ByVal Value As Boolean)

Me.isSoundOn.Checked = Value

End Set

End Property

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

Листинг 20.22. Метод для загрузки результатов игры.

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

ByVal e As System.EventArgs) Handles MyBase.Load

Me.DataGridView1.DataSource = HighScores.GetHighScores()

End Sub

На форме Form2 дважды щёлкаем по кнопке Button. Появляется шаблон метода (для очистки таблицы результатов), который после записи нашего кода принимает следующий вид.

Листинг 20.23. Метод-обработчик щелчка кнопки.

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

ByVal e As System.EventArgs) Handles Button1.Click

HighScores.ResetScores()

Me.DataGridView1.DataSource = HighScores.GetHighScores()

End Sub

В случае необходимости, методика добавления в проект звукового сигнала Beep (по-русски: Бип) описана ранее.

1
...
...
9