- •Microsoft C# Programming for the Absolute Beginner
- •Table of Contents
- •Microsoft C# Programming for the Absolute Beginner
- •Introduction
- •Overview
- •Chapter 1: Basic Input and Output: A Mini Adventure
- •Project: The Mini Adventure
- •Reviewing Basic C# Concepts
- •Namespaces
- •Classes
- •Methods
- •Statements
- •The Console Object
- •.NET Documentation
- •Getting into the Visual Studio .Net Environment
- •Examining the Default Code
- •Creating a Custom Namespace
- •Adding Summary Comments
- •Creating the Class
- •Moving from Code to a Program
- •Compiling Your Program
- •Looking for Bugs
- •Getting Input from the User
- •Creating a String Variable
- •Getting a Value with the Console.ReadLine() Method
- •Incorporating a Variable in Output
- •Combining String Values
- •Combining Strings with Concatenation
- •Adding a Tab Character
- •Using the Newline Sequence
- •Displaying a Backslash
- •Displaying Quotation Marks
- •Launching the Mini Adventure
- •Planning the Story
- •Creating the Variables
- •Getting Values from the User
- •Writing the Output
- •Finishing the Program
- •Summary
- •Chapter 2: Branching and Operators: The Math Game
- •The Math Game
- •Using Numeric Variables
- •The Simple Math Game
- •Numeric Variable Types
- •Integer Variables
- •Long Integers
- •Data Type Problems
- •Math Operators
- •Converting Variables
- •Explicit Casting
- •The Convert Object
- •Creating a Branch in Program Logic
- •The Hi Bill Game
- •Condition Testing
- •The If Statement
- •The Else Clause
- •Multiple Conditions
- •Working with The Switch Statement
- •The Switch Demo Program
- •Examining How Switch Statements Work
- •Creating a Random Number
- •Introducing the Die Roller
- •Exploring the Random Object
- •Creating a Random Double with the .NextDouble() Method
- •Getting the Values of Dice
- •Creating the Math Game
- •Designing the Game
- •Creating the Variables
- •Managing Addition
- •Managing Subtraction
- •Managing Multiplication and Division
- •Checking the Answers
- •Waiting for the Carriage Return
- •Summary
- •Chapter 3: Loops and Strings: The Pig Latin Program
- •Project: The Pig Latin Program
- •Investigating The String Object
- •The String Mangler Program
- •A Closer Look at Strings
- •Using the Object Browser
- •Experimenting with String Methods
- •Performing Common String Manipulations
- •Using a For Loop
- •Examining The Bean Counter Program
- •Creating a Sentry Variable
- •Checking for an Upper Limit
- •Incrementing the Variable
- •Examining the Behavior of the For Loop
- •The Fancy Beans Program
- •Skipping Numbers
- •Counting Backwards
- •Using a Foreach Loop to Break Up a Sentence
- •Using a While Loop
- •The Magic Word Program
- •Writing an Effective While Loop
- •Planning Your Program with the STAIR Process
- •S: State the Problem
- •T: Tool Identification
- •A: Algorithm
- •I: Implementation
- •R: Refinement
- •Applying STAIR to the Pig Latin Program
- •Stating the Problem
- •Identifying the Tools
- •Creating the Algorithm
- •Implementing and Refining
- •Writing the Pig Latin Program
- •Setting Up the Variables
- •Creating the Outside Loop
- •Dividing the Phrase into Words
- •Extracting the First Character
- •Checking for a Vowel
- •Adding Debugging Code
- •Closing Up the code
- •Summary
- •Introducing the Critter Program
- •Creating Methods to Reuse Code
- •The Song Program
- •Building the Main() Method
- •Creating a Simple Method
- •Adding a Parameter
- •Returning a Value
- •Creating a Menu
- •Creating a Main Loop
- •Creating the Sentry Variable
- •Calling a Method
- •Working with the Results
- •Writing the showMenu() Method
- •Getting Input from the User
- •Handling Exceptions
- •Returning a Value
- •Creating a New Object with the CritterName Program
- •Creating the Basic Critter
- •Using Scope Modifiers
- •Using a Public Instance Variable
- •Creating an Instance of the Critter
- •Adding a Method
- •Creating the talk() Method for the CritterTalk Program
- •Changing the Menu to Use the talk() Method
- •Creating a Property in the CritterProp Program
- •Examining the Critter Prop Program
- •Creating the Critter with a Name Property
- •Using Properties as Filters
- •Making the Critter More Lifelike
- •Adding More Private Variables
- •Adding the Age() Method
- •Adding the Eat() Method
- •Adding the Play() Method
- •Modifying the Talk() Method
- •Making Changes in the Main Class
- •Summary
- •Introducing the Snowball Fight
- •Inheritance and Encapsulation
- •Creating a Constructor
- •Adding a Constructor to the Critter Class
- •Creating the CritViewer Class
- •Reviewing the Static Keyword
- •Calling a Constructor from the Main() Method
- •Working with Multiple Files
- •Overloading Constructors
- •Viewing the Improved Critter Class
- •Adding Polymorphism to Your Objects
- •Modifying the Critter Viewer in CritOver to Demonstrate Overloaded Constructors
- •Using Inheritance to Make New Classes
- •Creating a Class to View the Clone
- •Creating the Critter Class
- •Improving an Existing Class
- •Introducing the Glitter Critter
- •Adding Methods to a New Class
- •Changing the Critter Viewer Again
- •Creating the Snowball Fight
- •Building the Fighter
- •Building the Robot Fighter
- •Creating the Main Menu Class
- •Summary
- •Overview
- •Introducing the Visual Critter
- •Thinking Like a GUI Programmer
- •Creating a Graphical User Interface (GUI)
- •Examining the Code of a Windows Program
- •Adding New Namespaces
- •Creating the Form Object
- •Creating a Destructor
- •Creating the Components
- •Setting Component Properties
- •Setting Up the Form
- •Writing the Main() Method
- •Creating an Interactive Program
- •Responding to a Simple Event
- •Creating and Adding the Components
- •Adding an Event to the Program
- •Creating an Event Handler
- •Allowing for Multiple Selections
- •Choosing a Font with Selection Controls
- •Creating the User Interface
- •Examining Selection Tools
- •Creating Instance Variables in the Font Chooser
- •Writing the AssignFont() Method
- •Writing the Event Handlers
- •Working with Images and Scroll Bars
- •Setting Up the Picture Box
- •Adding a Scroll Bar
- •Revisiting the Visual Critter
- •Designing the Program
- •Determining the Necessary Tools
- •Designing the Form
- •Writing the Code
- •Summary
- •Chapter 7: Timers and Animation: The Lunar Lander
- •Introducing the Lunar Lander
- •Reading Values from the Keyboard
- •Introducing the Key Reader Program
- •Setting Up the Key Reader Program
- •Coding the KeyPress Event
- •Coding the KeyDown Event
- •Determining Which Key Was Pressed
- •Animating Images
- •Introducing the ImageList Control
- •Setting Up an Image List
- •Looking at the Image Collection
- •Displaying an Image from the Image List
- •Using a Timer to Automate Animation
- •Introducing the Timer Control
- •Configuring the Timer
- •Adding Motion
- •Checking for Keyboard Input
- •Working with the Location Property
- •Detecting Collisions between Objects
- •Coding the Crasher Program
- •Getting Values for newX and newY
- •Bouncing the Ball off the Sides
- •Checking for Collisions
- •Extracting a Rectangle from a Component
- •Getting More from the MessageBox Object
- •Introducing the MsgDemo Program
- •Retrieving Values from the MessageBox
- •Coding the Lunar Lander
- •The Visual Design
- •The Constructor
- •The timer1_Tick() Method
- •The moveShip() Method
- •The checkLanding() Method
- •The theForm_KeyDown() Method
- •The showStats() Method
- •The killShip() Method
- •The initGame() Method
- •Summary
- •Chapter 8: Arrays: The Soccer Game
- •The Soccer Game
- •Introducing Arrays
- •Exploring the Counter Program
- •Creating an Array of Strings
- •Referring to Elements in an Array
- •Working with Arrays
- •Using the Array Demo Program to Explore Arrays
- •Building the Languages Array
- •Sorting the Array
- •Designing the Soccer Game
- •Solving a Subset of the Problem
- •Adding Percentages for the Other Players
- •Setting Up the Shot Demo Program
- •Setting Up the List Boxes
- •Using a Custom Event Handler
- •Writing the changeStatus() Method
- •Kicking the Ball
- •Designing Programs by Hand
- •Examining the Form by Hand Program
- •Adding Components in the Constructor
- •Responding to the Button Event
- •Building the Soccer Program
- •Setting Up the Variables
- •Examining the Constructor
- •Setting Up the Players
- •Setting Up the Opponents
- •Setting Up the Goalies
- •Responding to Player Clicks
- •Handling Good Shots
- •Handling Bad Shots
- •Setting a New Current Player
- •Handling the Passage of Time
- •Updating the Score
- •Summary
- •Chapter 9: File Handling: The Adventure Kit
- •Introducing the Adventure Kit
- •Viewing the Main Screen
- •Loading an Adventure
- •Playing an Adventure
- •Creating an Adventure
- •Reading and Writing Text Files
- •Exploring the File IO Program
- •Importing the IO Namespace
- •Writing to a Stream
- •Reading from a Stream
- •Creating Menus
- •Exploring the Menu Demo Program
- •Adding a MainMenu Object
- •Adding a Submenu
- •Setting Up the Properties of Menu Items
- •Writing Event Code for Menus
- •Using Dialog Boxes to Enhance Your Programs
- •Exploring the Dialog Demo Program
- •Adding Standard Dialogs to Your Form
- •Using the File Dialog Controls
- •Responding to File Dialog Events
- •Using the Font Dialog Control
- •Using the Color Dialog Control
- •Storing Entire Objects with Serialization
- •Exploring the Serialization Demo Program
- •Creating the Contact Class
- •Referencing the Serializable Namespace
- •Storing a Class
- •Retrieving a Class
- •Returning to the Adventure Kit Program
- •Examining the Room Class
- •Creating the Dungeon Class
- •Writing the Game Class
- •Writing the Editor Class
- •Writing the MainForm Class
- •Summary
- •Chapter 10: Chapter Basic XML: The Quiz Maker
- •Introducing the Quiz Maker Game
- •Taking a Quiz
- •Creating and Editing Quizzes
- •Investigating XML
- •Defining XML
- •Creating an XML Document in .NET
- •Creating an XML Schema for Your Language
- •Investigating the .NET View of XML
- •Exploring the XmlNode Class
- •Exploring the XmlDocument Class
- •Reading an Existing XML Document
- •Creating the XML Viewer Program
- •Writing New Values to an XML Document
- •Building the Document Structure
- •Adding an Element to the Document
- •Displaying the XML Code
- •Examining the Quizzer Program
- •Building the Main Form
- •Writing the Quiz Form
- •Writing the Editor Form
- •Summary
- •Overview
- •Introducing the SpyMaster Program
- •Creating a Simple Database
- •Accessing the Data Server
- •Accessing the Data in a Program
- •Using Queries to Modify Data Results
- •Limiting Data with the SELECT Statement
- •Using an Existing Database
- •Adding the Capability to Display Queries
- •Creating a Visual Query Builder
- •Working with Relational Databases
- •Improving Your Data with Normalization
- •Using a Join to Connect Two Tables
- •Creating a View
- •Referring to a View in a Program
- •Incorporating the Agent Specialty Attribute
- •Working with Other Databases
- •Creating a New Connection
- •Converting a Data Set to XML
- •Reading from XML to a Data Source
- •Creating the SpyMaster Database
- •Building the Main Form
- •Editing the Assignments
- •Editing the Specialties
- •Viewing the Agents
- •Editing the Agent Data
- •Summary
- •List of Figures
- •List of Tables
- •List of Sidebars
If either fighter’s strength drops to 0 or below, the other fighter wins. In either case, I set keepGoing to false so that the program would exit the next time through the Main loop.
In the Real World
Sometimes you describe something in English that turns out to be very difficult to convert into programming terms. In the snowball fight, saying “Check whether somebody has won the game” in your algorithm is easy, but the actual condition is much more difficult to write because winning is not really defined in this game. Instead, a player wins only if the opponent loses. Sometimes you must modify your algorithm so that it still retains its meaning. Seeing whether anybody has won is difficult, but finding out whether somebody has lost is easy, and the meaning is the same.
Displaying the Menu
The code for displaying the main menu is straightforward. The main menu consists of two parts: the scoreboard describing various statistics and the list of choices facing the human player. Both are accomplished through a set of Console.WriteLine() statements, as shown in the following code:
public int displayMenu(){ int choice;
Console.WriteLine("Stats:"); Console.WriteLine(" distance: \t{0}", range);
Console.WriteLine(" snowballs: \t{0}", player.snowballs); Console.WriteLine(" {0}: \t{1}", player.name, player.strength); Console.WriteLine(" {0}: \t{1}", opponent.name, opponent.strength); Console.WriteLine();
Console.WriteLine("0. Quit"); Console.WriteLine("1. Make a snowball"); Console.WriteLine("2. Move closer"); Console.WriteLine("3. Run away"); Console.WriteLine("4. Throw"); Console.WriteLine();
Console.Write("Indicate your choice: "); choice = Convert.ToInt32(Console.ReadLine()); Console.WriteLine();
Console.WriteLine(); return choice;
} // end dispayMenu
I needed to change the string value that comes from a Console.ReadLine() call to the integer value that displayMenu has to send out.
Summary
This chapter has led you through some of the most important ideas in modern computer programming. You have learned how to customize the creation of your classes through constructors. You have learned how to overload constructors by adding multiple constructors with different parameter sets. You have used inheritance to create new types of classes that inherit characteristics of existing classes. You have learned how polymorphism can be used to customize methods for new classes. All these new skills together give you the ability to create powerful new objects and manipulate them in interesting ways.
125
Challenges
∙Create your own new forms of the Critter class, inherited from the original critter.
∙Add a trick method to your critter so that it can do various types of tricks. Perhaps the happier a critter is, the better trick it can perform.
∙Make a two−player version of the snowball fight. You won’t need the RoboFighter class, but you will need two copies of the Fighter class. You’ll need to modify the main menu code a little, but two player games (at least, on the same computer) are easier to write than artificial intelligence.
∙Improve the performance of the robot fighter. Perhaps have it throw snowballs only when it is closer than five units away, or have it always run away after being hit so it can build more snowballs.
∙Make a tournament. Allow the user to choose human and computer players. Then build a tournament that pairs various fighters together, ultimately choosing a champion. Hint: You can reuse the existing program almost in its entirety. The main difference will be adding another program outside of it to control the tournament. Each individual snowball fight will invoke the Snowball Fight program.
126
Chapter 6: Creating a Windows Program: The Visual
Critter
Overview
The first programs in this book are much like the programs in the early high−level languages, such as COBOL and FORTRAN. These programs work primarily on the command line and begin with straight−line logic. As you have progressed in your own programming, you have used more complex logical structures, such as loops and branching statements, and you have played around with more complex data structures, such as variables. The history of programming follows the same progression. In the past two chapters, you looked at object−oriented programming, which represents the current thinking in program design, but your programs still do not seem very modern because they are written on the ugly and unfriendly console. In the next few chapters, you will look at how C# is used in Windows programming. The programs you will write feature the capabilities of the Windows operating system, with all the graphical features you have come to expect from such a system.
Now you will explore how to build a program with a Windows interface. In this chapter you will
∙Learn the basic concepts of a graphical user interface (GUI).
∙Use the IDE to build an interface.
∙Navigate the System.Drawing and System.Windows namespaces.
∙Add the most common GUI elements (text boxes, labels, images, scroll bars, and multiple selection elements) to your forms.
∙Write event−handling code.
∙Use event−driven programming.
Introducing the Visual Critter
As the final exercise for this chapter, you will build a critter program that has a graphical interface. This program will look and feel more like the programs you encounter on the Windows operating system. As usual, an image or two of the program is more helpful than just a description. Figure 6.1 demonstrates the Visual Critter in its default state.
127
Figure 6.1: This critter has a picture and some Windows−style controls.
You can see from Figure 6.1 that the newest version of the critter has much more visual appeal than the older versions. Modern users have become used to the convenience of a graphical interface, with all the various components such as text boxes, scroll bars, and command buttons. This version of the Visual Critter features several standard graphical controls.
Before diving into how all these controls work, you should play around with the program and see what it does. This is a highly interactive program, so you should open it from the CD−ROM and look at it live. I’ll show you a few of the highlights now in case you aren’t near a computer.
Figure 6.2 demonstrates what happens when you click the critter image.
128
Figure 6.2: When the user clicks the image, the critter speaks.
I have attached code to the image so that when it is clicked, a message appears. The critter asks the user to change the critter’s name. Take a look at Figures 6.3 and 6.4 to see how the user can edit the name in the rectangle on the left side of the form.
129
Figure 6.3: The user can rename the critter by typing in the little box.
130
Figure 6.4: After the user clicks the Change My Name button, the critter reports its new name. Any subsequent clicks on the critter will return the new name.
You can do other interesting things with the critter. You can change its mood by clicking the drop−down list of various temperaments. Figure 6.5 illustrates the critter after the user chooses a different mood.
131
Figure 6.5: When the user chooses a new mood from the drop−down list, the image changes accordingly.
The user can also change the critter’s size, by manipulating the scroll bar. Changing the location of the rectangle inside the elevator shaft changes the size of the critter image. Figures 6.6 and 6.7 illustrate this phenomenon.
132
Figure 6.6: The elevator shaft is near the top, and the critter image is very small.
133
Figure 6.7: When the user moves the scroll bar down, the critter grows.
You can also change the color of the background on which the critter resides. Illustrating these color changes on a black−and−white page is impossible, so you need to experiment with the program to see this phenomenon.
Creating a Windows−Style Program with a GUI
The Windows operating system, like most modern computer operating systems, provides a graphical user interface (GUI). The GUI, pronounced “gooey,” (I love it when technical terms sound silly) has several purposes. It is intended to make the user’s life easier. Manipulating a mouse and clicking screen elements is presumably easier than typing commands from a text−based menu. Visual elements on the screen are more aesthetically interesting than the kinds of programs you have seen so far in this book. Graphical elements, such as text boxes, list boxes, and scroll bars, also have practical benefits. Many of them are designed to limit user input. This prevents the user from entering invalid data and minimizes the error−checking code the programmer must write. Also, most graphical elements are already familiar to computer users. If you use only standard components in your programs, most of your users will already know the basic operation of these objects. Finally, the visual components are predefined by the Windows operating system, so you don’t have to write all the code for them every time. All the visual elements are available as objects.
134