Experience Microsoft.Net - write a digital game with the beginner.

zhaozj2021-02-08  222

Experience

Microsoft is leading a new Internet technology revolution, which is .NET. .NET is a new Internet-based programming model. February 13 Microsoft officially released a new .NET platform-based development tool in the United States - Visual Studio.net, which marks the comprehensive arrival of Microsoft .NET era.

I want to use this article, with everyone to develop a simple little game - guess the number, share some experience in learning .NET technology, share .NET brings us a new development experience.

Experience the basic articles of Microsoft .NET

As a new development platform, Microsoft has officially released the SDK of .NET Framework before the Visual Studio.Net is released, which is the basic conditions for us .NET development. This SDK once known as NGWS (Next Generation Windows Services) provides us with a series of .NET support platforms such as C # (pronunciation for C Sharp) compiler, VB compiler, ASP.NET running environment, and related documents. .

SDK is just a simple development platform. If you install .Net Framework SDK, you can develop a series of .NET applications, but you will not be able to fully experience the rapid development of .NET brings us quickly, you still need to use The ancient MSDOS command line is to compile your program. Therefore, we also need to install the Visual Studio.net integration development environment. We can really experience the fun of .NET development. Visual Studio.NET Chinese official version was officially released on March 22. Due to the limited conditions, Visual Studio.net used herein is English official version, but the procedures involved can compile operation in Chinese official version.

Microsoft Visual Studio.NET is a series of development tools based on an integrated development environment based on .NET platform applications, including Visual Basic.Net, Visual C . Net and the latest Visual C # .NET, etc. A series of development tools, through this powerful development environment, we Various .NET applications including Windows Forms applications, ASP.NET, or XML Web Service can be easily constructed.

Said so much, you should understand how to do it, open your computer, install .NET Framework SDK and Visual Studio.net, then start our .NET tour with me!

Experience the C # programming of Microsoft .NET

The C # language is a very important part of the .NET platform, which is a new generation of components-oriented programming developed by Microsoft's leadership research. It maintains the powerful functions of the C language, but also on this basis. More simple, safe programming tools. The .NET platform itself is developed in this new type of C # language.

In accordance with the practice, we started from "Hello World!" To experience the C # language. Here is a typical C # HelloWorld program:

Using system; public class hello {public static void main () {console.writeline ("Hello World!");}}

how about it? It's not difficult. It is a bit like C, a bit like C , a bit like Visual Basic, more like Java.

The first line of the program specifies a reference to the System name space (Namespace), which references this name space, we can easily use the class in this name space, such as the following Console class is the name space of SYSTEM. The second row starts we define a Hello class. It contains a static main method (Method), there is no concept of member functions in C #, and the original member function is now called "method", and the original member variable is called "Field". The MAIN method is the beginning of a C # program. In our example, the only line of the MAIN method calls the output method of the system Console class Display string "Hello World!". Let's take a simple contrast of C # and C : First, C # is a programming language that is fully object-to-object, which no longer has a global function, and any function is included in a certain class. The forward declaration of the function is no longer required in C #, which you need can define anywhere in the class. C # minimizes the use of pointers, at the same time, the original C :, ->, and. Operators are unified in. C # no longer uses #include to include other program text, which makes the .NET platform language independence is reflected. For example, you can use Viusal Basic.net to write a class, then call it with C # to derive new classes based on it, which makes the software reach a new realm.

You can try it now, here, we don't use Visual Studio.net, we use the command line to compile this program.

Open a notepad, enter the source code above, pay attention to case, save the disk, change the file extension to .cs (here we put this file as hello.cs), this is the extension of the C # source program requirements. Then open a DOS window and find the directory you store .cs file, enter

CSC Hello.cs

The system began to compile your program. If there is no error, you will generate a hello.exe file, you can see the output on the screen.

Let's use Visual Studio.NET to develop C # programs.

First, it is definitely to start Visual Studio.net software. Below is its development interface, very beautiful and friendly.

We click the "New Project" button on the start page to create a new project, select the item type "Visual C # Project" in the "New Project" dialog box, and select "Console Application" template, enter Suitable project name (us here with Guesnum1) and storage location, determine. At this time, the system will generate a framework for the simplest C # application, we can modify our own procedure on the basis.

We modified the system framework generated into the following:

Using system; // Reference System System Name Space Namespace GuessNum1 // Defines the namespace belonging to this program {///

/// Summary Description for class1./// class class1 // system automatic generation Class1 {/// /// The main entry point for the application. /// [stathread] static void main (string [] args) // static main method {/// Todo: add code to start appliment here // Guesnum gn = new guestnum (); // Generate an object Gn.GenereanderAndomnumber (), generating random number as a guess number String Answer; // String Valent For the speculation value DO {Answer = console.readline (); console.writeline (gngettip (anisanswer);} while (! Gn.isanswerright (answer); // Repeatedly required users to guess the number Until guess the correct}} Class Guessnum // We define the guessnum class, you will use the {Private String Correctanswer; // Guessnum class's private field (member variable) for saving the correct answer public guest guessnum () { Correctanswer = ""; public guessnum (string answer) {correctanswer = answer;} public string generatingrandomnumber () {int [] a = new int [10]; // Open up a tenth unit's plastic array // Put 0 to 99 Number Fill in A [0] to A [9] for (int i = 0; i <10; i ) a [i] = i; // put this ten numbers randomly disrupt Random J = New Random () For (INT i = 0; i <10; i ) {INT T = J.Next (10); int S; s = a [i]; a [i] = a [t]; a [t] = s;} // Take the four numbers in front of the four digits as a correct answer of guessing numbers CORRECTANSWER = a [0] .tostring () a [1] .tostring () a [2] .tostring () a [3] .tostring (); returnorctanswer;} public string gettiP (String answer) // This method provides users with guessing prompts, there is no truly completion {IF (iSanswerright (Answer) Return "4A0B"; Else Return "WRONG!";

} Public Bool Isanswerright (String Answer) // This method determines whether the user's guess is correct {if (answer == Correctanswer) Return true; Else Return false;}}} I will experience Visual Studio during code input. .NET powerful code editing function, automatic indented alignment, intelligent induction, code folding should be. The above program itself does not have much more explanation, you can see that this program randomly generates a four-digit number of four digits, and then waits for user input, if the input is correct, display "4A0B" ( This doesn't need me to explain it in detail. I have a friend who guess the numbers know the meaning of this tip. A front of the number indicates that you guessed the number of numbers in the place, and the numbers in front indicate that you guessed the number. But the number of numbers in the wrong position), if you guess, you will display "WRONG!", Let the user re-guess. Obviously this game is still not fun, guessing only "WRONG!" Is far less enough, you should tell the user to guess a few numbers and play a few numbers. Don't worry, we will slowly improve this procedure later.

Among this program is worth noting that it uses "///" forms of comments, such annotations can be used to generate program documents, and if you add some tags, you can generate documents in XML form.

Now you can press the CTRL F5 key to run the program, enter a 4-digit, if correct, the system is prompt "4A0B" and exits the program if it is not correct, and "WRONG" is output. Since there is not enough tips, I am afraid you are unlikely to guess the correct number, so I still shut down the window, we continue the following.

Experience Microsoft .NET Windows Forms Program Design

As we have conducted a point of C # program in the console environment, the purpose is to let everyone be familiar with the C # language, and we will transplant our program developed under the console to the Windows window interface.

Here, we first introduce the concept of Windows Forms: Windows Forms is a programming framework that Microsoft provides under the .NET platform, which supports multiple programming, mainly to develop client window applications.

Below we use Visual Studio.net to help us generate a simple Windows Forms source program, we will work on it, the methods are as follows:

Open Visual Studio.net, click "New Project", select the project type "Visual C # Project", then select the program template to "Windows Application", enter the project name "Guessnum2", and determine.

We press the F5 key to compile this program, and a blank window will appear. What we have to do now is to add the blank window to the features we need.

First, we have the construct of visual interface part, find the appropriate control from the left Toolbox, drag to the blank window, make it the following:

One point to explain is that when constructing TextBox2, pay attention to set its multiline property and readOnly property to true. And set the ScrollBars property to Vertical. The modification of the control attribute value is implemented by selecting the control after selecting the "Properties" area in the lower right corner, the modified property, the font of its attribute value is thicker. This Properties area has a functionality that can be switched for the control to connect to different events, and can switch the function by clicking on the above Events button. Double-click the blank section of the form, the system automatically generates this form of the LOAD event response function form1_load (), we don't need to revise it, first put the code of the Guessnum class written in the last program (excluding Class1 class Code) Before the last} of the code in the current code window, this class has become a class in the current Guessnum2 name space.

Then write the following code in the Form1 class, that is, the object GN of a Guessnum class is defined in the Form1 class. Since the C # does not require the forward statement, this line code can be written in any location in the Form1 class, of course, does not include the form1 class, if you write this line code in a method of the Form1 class, this Not to define objects in the class, it is a local object defined in a method.

PRIVATE GUESSNUM GN;

Then we modify FORM1_LOAD (), modify it into the following:

Private Void Form1_Load (Object Sender, System.EventArgs E)

{

TextBox1.text = ""

Button1.text = "guess!";

// Generate an object with the Guesnum class, then let it produce the number of guess, and finally display this number in TextBox2.

// The reason why it is displayed in TextBox2 is to facilitate your "peeking" answer, otherwise it is almost impossible to guess the answer.

/ / We will improve Guessnum in the later program so that its gettip () method can truly work

Gn = new guessnum ();

TextBox2.text = gn.generatrandomnumber ();

}

Click on the tab on the upper part of the code editor, switch back to the window designer, double-click the Button1 button, add button response to it:

Private void Button1_Click (Object Sender, System.Eventargs E)

{

TextBox2.text = (TextBox1.text " gn.gettip (textbox1.text) " / r / n ") TextBox2.Text;

IF (gn.isanswerright (TextBox1.text))

TextBox2.text = "CONGRATULATIONS! You get! / r / n" TextBox2.Text;

TextBox1.text = ""

}

We use F5 compile to run this program, see, very convenient, we change the program that has just running under the console into a Windows application.

Experience the ASP.NET of Microsoft .NET

Let's take a look at the important part of the .NET's ASP.NET. We will deliver a guess digital game that can be quickly developed with ASP.NET.

In Visual Stuido.net, we create a new ASP.NET application, the operation method is the same as the above, but select "ASP.NET Web Application" when selecting the project template, this time, we use Guesnum3 as our Project Name, after confirmation, the system will automatically contact IIS server to create a virtual directory and some related files. As in the previous, we press F5 to run this ASP.NET project, and we also got a blank page.

The work you want to do is similar to the previous, first you want to add a server control on a blank ASP.NET page. What is a server control? Simply put, the server control is a control placed on the ASP.NET page. The normal operation of this control is done on the server side. After the server is processed, the standard HTML file is sent to the client. . For example: We placed a Label control on the page and change it to "Hello World" through the program, and the server controls the Label control when it receives the request to access this page, change its title properties. The HTML file finally generated to the user, the user does not know everything behind this scene, the data he finally received is an HTML page containing the "Hello World" string.

The method of adding a server control on the page is exactly the same as the method of adding a control on the form, as long as the corresponding control in the Toolbox can be dragged onto the page. The page we finally completed is like this:

Similarly, don't forget to set the ReadOx2 ReadOnly property to true, set the TextMode property to Multiline. In addition, for the later operation, it is convenient. Please change the first letter of the three controls (ID) attributes to lowercase, ie the two controls of the two controls are changed from the original TextBox1, TextBox2, button1 to TextBox1, TextBox2 Button1.

The work to be done will make you feel a bit of acquaintance:

Double-click the page blank, the system generates the page_load () method, no matter whether it, add the Guessnum class in our last program before the last} of the source, and join the line in the WebForm1 class:

PRIVATE GUESSNUM GN;

Then modify Page_Load () into the following:

Private Void Page_Load (Object Sender, System.EventArgs E)

{

// put user code to initialize the page

// Judgment is the first access page or refresh the page

// If it is the first visit, generate the random number and there is session

/ / If it is not the first access, read the previously generated value from the session is used to construct the Guessnum object.

IF (! page.ispostback)

{

TextBox1.text = ""

Button1.text = "guess!";

Gn = new guessnum ();

// The following is used in the ASP, but the session in the ASP.NET is more powerful than the ASP.

Session ["ANSWER"] = gn.generatrandomnumber ();

// Like a Windows Forms program, we will display the standard answer first in TextBox2, which is convenient for your test.

TEXTBOX2.TEXT = session ["Answer"]. TOSTRING ();

Else

GN = New Guessnum (session ["Answer"]. TOSTRING ());

}

Returns the web form designer, double-click the Button button, add the same code as the previous Windows Forms program in the Button1_Click () appearing.

Ok, try it. No, a guess number game that can be run on the web has begun to take shape.

After the above demonstration, are you a preliminary understanding of ASP.NET? In ASP.NET, it is not necessary to plug the script in the HTML file like it before the ASP, and the interface design and program design is separated (partially designed in one .aspx file, put the code part) In a .cs or .vb code file, this technology is referred to as Code Behind, and the ASP.NET page also presents an event-driven feature. This makes the code reuse greatly, as you can see, the code we used in ASP.NET is quite consistent with the code used in the development of Windows Forms desktop applications.

On the other hand, the code separation technology of ASP.NET not only improves the development efficiency, but also improves operational efficiency, ASP.NET is no longer interpreted, it is the page when the user visits a new page for the user, The code is compiled, and the user access is executed is the compiled code, and the operational efficiency has naturally improved. This is why we feel the cause of the ASP.NET web page for the first time, the speed is particularly slow.

From a user's point of view, ASP.NET is also easier to use, accessing an ASP.NET page is like using an application. In fact, the Windows Forms app written above is different from the general application. If the user is placed on the web, the browser will automatically download and run it directly when the user clicks to point to its link (of course, Microsoft) The company did a lot of work to ensure its security). In the .NET era, the network and desktop applications have become more unambiguous.

Experience Web Service Microsoft .NET

The Web Service is a newer concept introduced in .NET. During the traditional application development process, developers have always constructed the application by integrating local system services. Now the appearance of Web Service can make developers to easily build an N layer system with complex structures. Web Server is an application that uses standard HTTP protocols and XMLs to reflect the functionality of the software on the network. Clearly, it is to develop an application on the web server, which can respond to the request of the remote program, accept the data sent by the transcript, and return the data after processing.

Below we want to provide a service for our guess digital game through Web Service, that is, the client application will guess the number of standard answers to the server to provide the web service, server, server Determine the correctness of the user, and return to guessing and placing the number of numbers and guessing but not in the number of numbers. Some friends will definitely ask, this operation can be done locally, why do you want to turn a large circle, use the Web Service to complete it on the server? This operation can indeed adding code directly to the C # program above. We don't do this is to demonstrate the use of Web Service for everyone. You can envision the program to access a database on the remote server, return different data according to the different information submitted by the user, then the Web Service is very useful. First, we still use Visual Studio.net to generate an empty Web Service project for us. Unlike the front, this time, we use another important language in .NET - Visual Basic.Net - to develop our web service, this is not a special meaning, just want to experience it with everyone. New Visual Basic.NET language.

Open Visual Studio.net, click "New Project", select Visual Basic Project in Project Type, select ASP.NET Web Service in Template, enter the project name GuesnumService, and then determine.

After the project is constructed, we can see a design page. There are two lines above, click "Click Here to Switch To Code View" to switch to the code edit view, start our code. The design page is mainly used to add some components or database connections.

In the code view, we can see an annotated HelloWorld function, which is actually an example, telling you how to establish a web service, follow its look, we enter the following code:

' is an attribute specified by the function, indicating that this function will be published as a function in a web service.

Public Function Gettip (Byval Correctanswer As String) AS String

DIM I as integer

DIM J AS INTEGER

Dim a as integer

DIM B AS INTEGER

For i = 1 TO 4

For j = 1 to 4

IF MID (Correctanswer, J, 1) = MID (Useranswer, i, 1) THEN

IF j = I Then

A = 1 'VB programmers often envy C programmers this simple way of writing, now VB's programmers can use!

Else

B = 1

END IF

END IF

NEXT

NEXT

'The TSTRING () method used below is almost any type of conversion function supported by any type of data.

How to convert an integer 4 in VB to a string type? Str (4). In VB.NET, you can write 4.toString ()!

Gettip = a.tostring () "a" b.toString () "b"

END FUNCTION

Below we can test this Web Service, press F5 key, Visual Studio.net automatically open IE to test this web service, we see the following screen:

This is the service test page that .NET is automatically generated, this page lists all the functions provided in the current Service1 service, and now there is only one gettip (). At the same time, this page also provides a link to Service Description, click on it, you can see the service instructions described in XML, we call WSDL, the Web Service Description Language.

Here, I remind you to put the address COPY in the browser address bar, we will use it, in my machine, this address is http://localhost/guessnumservice/service1.asmx, from here, we can also see Out, the web service's file extension is ASMX.

Now we click "gettip" to test this web service, enter numbers in the Correctanswer and Useranswer two text boxes, then click Invoke, the result will return in XML.

For example, we will enter 3684 and 4628 respectively. In this case, the user is guessing a number "6", but also guess two numbers "4" and "8", but in the wrong position, the return prompt should be 1A2B, Test it, sure enough!

Web service test successfully! We can finally begin to construct a complete guess number game!

Newly built a Visual C # Windows Application (you can also open the front of the guessnum2, let's first modify it on it), name GuessnumFinal, design the game form as you do Guessnum 2, and In the same way, add the Guesnum class to the GuessnumFinal name space, add a private member of GuessNum to the Form1 class, then add the form's Form1_Load and button's Button1_Click method.

The following is to modify the Gettip method of the Guessnum class, so that it is no longer simply returns a "WRONG!" But by calling the Web Service, providing the standard answer and user input to it, let it return a "xayb" Form prompt string, then return this string. Of course, you can also do not modify the Guessnum, but it is derived from it based on it, and this work is left to you.

It's easy to say, do it? It is not difficult! You don't have to worry about writing a web application with Winsock to access Web Service, and process the returned XML files, these work Visual Studio.net has helped us do well!

In the upper right corner of the Visual Studio.net integration interface, there is a solution Explorer, we use the mouse to right-click, then select "Add Web Reference" to add a reference to the Web Service.

Enter the address recorded in front of the address bar of the pop-up Add Web Reference dialog box and enter. After the Web Service's test page appears, click the "Add Reference" button.

At this time, we can see a new Web Reference in Solution Explorer, there is our web service. In fact, we have completed such a simple operation with the help of Visual Studio.Net. The first is to obtain WSDL from the server based on the input address, and then generate a C # proxy class according to the description of the WSDL, and then add it to the project. Now, we can easily use this class to make our program contact Web Service to complete our needs.

Below you can truly modify the code of Guessnum gettip (). First, we join the top of the program source code:

Using GuessnumFinal.localhost;

Quote our namespace where our web service's proxy class is set to facilitate the writing of our back code. (If you don't have a new GuessNumFinal project, but change the above GuessnumFinal on the basis of Guessnum2.)

Next, change the Guessnum class gettip () method to the following code:

Public String gettip (String Answer)

{

Service1 service = new service1 (); // Generate an object with the service1 class in the guestnumfinal.localhost name space

Return Service.gettip (CORRECTANSWER, ANSWER); // Call Web Service, return to the return value

}

Finally, find the Form1_Load () method

TextBox2.text = gn.generatrandomnumber ();

Change it to the following code, we no longer need to steal the answer!

TextBox2.text = ""

Gn.generanderAndomnumber ();

At this point, our program is finally completed! Press the F5 running program to experience the first game program written by .NET!

Experience the end of Microsoft .NET

Our guess number game is finished, our .NET trip will also close the end. As a new platform for Microsoft, although there are still many controversy about .NET, many people still believe that .NET will become more mature with strong support of Microsoft,. Net will become a Microsoft platform software to develop a mileage.

In order to make everyone better understand and learn .NET, and finally I will list some good references to you with reference:

1. Samples and quickstart tutorials included in .NET Framework SDK

2. Contains Microsoft Visual Studio .Net Documentation in Visual Studio.net

3. Microsoft website, MSDN website

4. Http://www.cndot.net and other domestic and foreign .NET technology website

转载请注明原文地址:https://www.9cbs.com/read-1897.html

New Post(0)