Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
220
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 22

Return True

End If

If btn20.Text = btn21.Text And btn21.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on bottom Row Call Winner(btn20.Text) Return True

End If

If btn00.Text = btn10.Text And btn10.Text = btn20.Text And _ btn20.Text <> String.Empty Then

‘Winner on first column Call Winner(btn00.Text) Return True

End If

If btn01.Text = btn11.Text And btn11.Text = btn21.Text And _ btn21.Text <> String.Empty Then

‘Winner on second column Call Winner(btn01.Text) Return True

End If

If btn02.Text = btn12.Text And btn12.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on third column Call Winner(btn02.Text) Return True

End If

If btn00.Text = btn11.Text And btn11.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on diagonal top left to bottom right Call Winner(btn00.Text)

Return True End If

If btn20.Text = btn11.Text And btn11.Text = btn02.Text And _ btn02.Text <> String.Empty Then

‘Winner on diagonal bottom left to top right Call Winner(btn20.Text)

Return True End If

‘Test for a tie, all square full Dim ctrl As Control

Dim intOpenings As Integer = 0 For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then If ctrl.Text = String.Empty Then

intOpenings = intOpenings + 1 End If

End If

716

Building Mobile Applications

Next

If intOpenings = 0 Then

Call Winner(“It’s a tie.”)

Return True

End If

Return False

End Function

End Class

6.Add this highlighted code to the Form1_Load event handler.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

CorrectEnabledState(False)

lblMessages.Text = “Click new game to begin.” End Sub

7.Add this code to the btnNewGame_Click event handler.

Private Sub btnNewGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewGame.Click

ResetGame()

End Sub

8.Run the program mode in debug mode to see how it works. You will be asked how to deploy the application. Choose Pocket PC 2003 SE Emulator and click the Deploy button shown in Figure 22-8. Be patient, because it will take some time to start the entire process.

Figure 22-8

9.When the application starts, you will see the Pocket PC emulator, and the TicTacToe program will be running. Wait for the application to start. The emulator will look like Figure 22-9. You may be prompted with an Establishing Connection dialog box. Choose Internet to continue.

717

Chapter 22

Figure 22-9

10.Click New Game and play against the computer. The computer player chooses a random play and is easy to defeat.

How It Works

This game gave you a basic understanding of smart device development. It is relatively the same as the work you completed in earlier chapters. The first thing you may have noticed is the screen size. You had limited real estate to design the user interface. The screen was the perfect size for a simple game of tic tac toe.

To start, you created the user interface. When you added the buttons and labels, it was just like building a desktop application. The controls had many of the same properties you were familiar with from previous chapters. You should have had no problem with the user interface.

Most of the work you did for the game was with code. Again, everything you learned earlier in the book applies to smart device applications. You saw the functions and subroutines created to run the game, and you should have remembered most of this logic from previous chapters. We will go through the code one routine at a time to explain what happened.

718

Building Mobile Applications

After a game ends, you needed a standard way to get the board and screen ready for a new game. This was accomplished with the ResetGame procedure. This procedure used the collection of controls on the form and iterated through each control that was a button. If the button was a part of the board, the text property was reset to an empty string. After all buttons had been reset, the message label text was set to blank and all board buttons were enabled.

‘Get the game ready to start again Sub ResetGame()

Dim ctrl As Control

‘Loop through the board controls and set them to “” For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then ctrl.Text = String.Empty

End If Next

lblMessages.Text = “” ‘Enable the board buttons CorrectEnabledState(True)

End Sub

The CorrectEnabledState subroutine had two signatures. This was an example of overloaded methods. When you called CorrectEnabledState with one Boolean argument, the procedure set the Enabled property of all buttons on the board to the value of the parameter you passed. The other method signature expected no parameters. So when it was called, that procedure tested every button on the board. If a button was blank, it was enabled. Otherwise, the button was disabled.

Private Sub CorrectEnabledState(ByVal ButtonEnabledState As Boolean)

Dim ctrl As Control

For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then

ctrl.Enabled = ButtonEnabledState

End If

Next

End Sub

Private Sub CorrectEnabledState()

Dim ctrl As Control

For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then

If ctrl.Text = String.Empty Then

ctrl.Enabled = True

Else

ctrl.Enabled = False

End If

End If

Next

End Sub

Another procedure created was ComputerPlay. This procedure made the play for the computer. At the top of the code, declarations were made for local variables. The meat of the logic started before the while loop. The Next method of the Random class generated a random number between 20 and 100. The program looped through every open square on the board, counting each one, until the lucky random number square was found and it was marked with an O.

719

Chapter 22

Sub ComputerPlay()

Dim RandomGenerator As New Random() Dim intRandom As Integer

Dim intCount As Integer = 0 Dim ctrl As Control

intRandom = RandomGenerator.Next(20, 100) While intCount < intRandom

For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then If ctrl.Text = String.Empty Then

intCount += 1

If intCount = intRandom Then ctrl.Text = “O” ctrl.Enabled = False

Exit For End If

End If

End If Next

End While End Sub

When you clicked any square, the TicTacToe_Click procedure was called. Take a look at the Handles keyword in the declaration of the subroutine. The Click event from every button on the board has been added to the comma-delimited list. So when you clicked any square, this procedure handled the event.

The first step of the procedure disabled all squares, followed by a call to Application.DoEvents. The DoEvents method allowed all waiting events in the queue to complete. This was placed here to avoid the problems associated with clicking more than one button in a turn. If you removed these two lines of code, you could quickly click three squares in a row before the computer made one pick. Next, the button that was clicked, the sender, is marked with an X. After the square is marked, the board is checked for a winner. If no winner is found, the computer makes the next move. Again, the board is checked for a winner. If no winner is found, the player is asked to select again.

Private Sub TicTacToe_Click(ByVal sender As Object, ByVal e As _ System.EventArgs) Handles btn00.Click, btn20.Click, btn10.Click, _ btn01.Click, btn21.Click, btn11.Click, btn02.Click, btn22.Click, btn12.Click

CorrectEnabledState(False)

Application.DoEvents() ‘Allows the screen to refresh CType(sender, Button).Text = “X”

If IsGameOver() Then MsgBox(“Game Over”)

Else

lblMessages.Text = “Computer selecting ...” Application.DoEvents() ‘Allows the screen to refresh ComputerPlay()

If IsGameOver() Then MsgBox(“Game Over”)

Else

lblMessages.Text = “Select your next position ...” CorrectEnabledState()

End If End If

End Sub

720

Building Mobile Applications

The Winner procedure is called when a winner is found. The outcome of the game is displayed on the message label.

Sub Winner(ByVal strWinner As String) Dim strMessage As String

If strWinner = “X” Then strMessage = “You win!!”

ElseIf strWinner = “O” Then strMessage = “Computer wins!!”

Else

strMessage = strWinner End If

lblMessages.Text = strMessage End Sub

After every move, IsGameOver is called to look for a winner. Every possible combination of squares is tested. If three squares in a row are marked by the same player, the Winner procedure is called and True is returned from the function. If no winner is found, the board is tested to see whether all squares are marked. When all squares are marked, the game is a tie.

Function IsGameOver() As Boolean

If btn00.Text = btn01.Text And btn01.Text = btn02.Text And _

btn02.Text <> String.Empty Then

‘Winner on top Row

Call Winner(btn00.Text)

Return True

End If

If btn10.Text = btn11.Text And btn11.Text = btn12.Text And _ btn12.Text <> String.Empty Then

‘Winner on middle Row Call Winner(btn10.Text) Return True

End If

If btn20.Text = btn21.Text And btn21.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on bottom Row Call Winner(btn20.Text) Return True

End If

If btn00.Text = btn10.Text And btn10.Text = btn20.Text And _ btn20.Text <> String.Empty Then

‘Winner on first column Call Winner(btn00.Text) Return True

End If

If btn01.Text = btn11.Text And btn11.Text = btn21.Text And _ btn21.Text <> String.Empty Then

‘Winner on second column Call Winner(btn01.Text) Return True

End If

721

Chapter 22

If btn02.Text = btn12.Text And btn12.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on third column Call Winner(btn02.Text) Return True

End If

If btn00.Text = btn11.Text And btn11.Text = btn22.Text And _ btn22.Text <> String.Empty Then

‘Winner on diagonal top left to bottom right Call Winner(btn00.Text)

Return True End If

If btn20.Text = btn11.Text And btn11.Text = btn02.Text And _ btn02.Text <> String.Empty Then

‘Winner on diagonal bottom left to top right Call Winner(btn20.Text)

Return True End If

‘Test for a tie, all square full Dim ctrl As Control

Dim intOpenings As Integer = 0 For Each ctrl In Me.Controls

If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then If ctrl.Text = String.Empty Then

intOpenings = intOpenings + 1 End If

End If Next

If intOpenings = 0 Then

Call Winner(“It’s a tie.”) Return True

End If Return False

End Function

The remaining code is part of the handlers for the form’s Load event and the New Game button Click event. On form load, the overloaded method CorrectEnabledState is called and all buttons are disabled. When you click the New Game button, ResetGame is called to set up the board to start a new game.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

CorrectEnabledState(False)

lblMessages.Text = “Click new game to begin.” End Sub

Private Sub btnNewGame_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles btnNewGame.Click

ResetGame() End Sub

722

Building Mobile Applications

Summar y

Visual Studio 2005 and the Compact Framework make developing mobile applications very similar to desktop application development. This small learning curve for .NET developers is one of the reasons more PDAs are shipping with a Windows operating system than with any other competitor. The trend has been growing, and companies are starting to value the developer with mobile application skills.

Take advantage of your knowledge and leverage it to start developing mobile applications.

In this chapter, you learned the basics of mobile development. You saw what is similar and what is different between the full version of the .NET Framework and the Compact Framework. You were shown examples of the missing pieces that explain how the CF has been shrunk by over 80 percent. Finally, you built your first application, tic-tac-toe.

To summarize, you should know how to:

Find differences between the full .NET framework and the Compact Framework

Use ActiveSync to connect to smart devices

Create mobile applications

Use the built in emulator to test mobile applications

Exercise

The computer player is a random picker. Give the computer player some brains. Add at least one function named ComputerPlayToWin to the application. When the computer moves, call ComputerPlayToWin and check for a spot on the board that will create a win for the computer. If it exists, the computer should play that move rather than a random move. You can add other procedures if needed.

723

A

Where To Now?

Now that you have come to the end of this book, you should have a relatively good idea of how to write code using Visual Basic 2005. The topics and example code covered in this book have been designed to provide you with a firm foundation, but it is just the beginning of your journey. In fact, this book is just one of the many steps you are going to take on your road to becoming a full fledged Visual Basic 2005 programmer. Although you have come a long way, there is still a lot farther to go, and you will certainly have many more questions on the way.

The problem now is, where do you get these questions answered, and, of course, “What next?”

This appendix offers you some advice on what your possible next step(s) could be. As you can imagine, a number of different routes are open to any one person. The path you choose will probably depend on what your goal is or what you are being asked to do by your employer. Some of you will want to continue at a more general level with some knowledge about all aspects of Visual Basic 2005, while others may want to drill down into more specific areas.

Well, it is extremely important not to take a long break before carrying on with Visual Basic 2005. If you do so, you will find that you will quickly forget what you have learned. The trick is to practice. You can do this in a number of ways.

Continue with the examples from this book. Try to add more features and more code to it. Try to merge and blend different samples together.

You may have an idea for a new program. Go on and write it.

Try to get a firm understanding of the terminology.

Read as many articles as you can. Even if you do not understand them at first, bits and pieces will come together.

Make sure you communicate your knowledge. If you know other programmers, get talking and ask questions.

Consult our online and offline resources for more information.

The rest of this appendix lists available resources, both online and offline, to help you decide where to go next.