Game client programming

Game client programming

IDE: Visual Studio 2019

System: Windows10

C# version: 8.0

Write an online game client. The campus intranet IP address of the game server is 10.1.230.74, the port is 3900, and TCP connection is adopted.

  1. After the connection is successful, the messages sent by the server can be continuously displayed in the listbox;
  1. Enter the data to be sent by the client to the server through textbox or click button;

  2. Able to play background music;

  3. Change the game background image every 30 seconds.

1, Preparatory work

  1. New project

    Create a new form application.

    After new creation, it will go to the form design interface.

  2. Add a WindowsMediaPlayer control

    First, you need to add a Windows Media Player control (if it already exists, it will be ignored). You need to use it to play background music later.
    Right click general in the toolbox and click options.

    Select "COM component", check "Windows Media Player", and then click "OK".

    This is a music playback control, but I don't know whether it's my C# version or the installed package is incomplete. You can't call that control here

  3. Interface design

    textbox - 2 (input box, display box)
    button - 3 (send, enter the game, exit the game)
    picturebox - 1 (picture display)
    trackbar - 1 (volume adjustment), please ignore this item, because it is meaningless if you can't use the music player.
    label - 1 (volume display)
    groupbox - 2 (input box and volume adjustment)
    The following red font content is the name of the control.

  4. Set control properties

    Set the font for both textbox es

    The following are special settings.

    textBox2 property setting: the Multiline property needs to be set to True, which is represented as a Multiline text box; The ScrollBars property is set to Vertical to indicate a Vertical scroll bar.

2, Connect server

1. Implementation code:

Click the connect game button to connect to the server. If the connection is successful, the messages sent by the server will be continuously displayed in the textbox; If the connection fails, "server not started" is displayed in textbox.

Double click the "connect game" button to go to the code editing area.
In button2_ In the click function body, write the connection code, and define two global variables outside the function body. Here I simply write a function strDelete to remove terminal escape characters.

//Create TcpClient and NetworkStream objects respectively
TcpClient tcpClient;
NetworkStream stream;

/*****************

Enter the game
*****************/
private void button2_Click(object sender, EventArgs e)
{
/*

   * Connect server
     */
     try
     {
         //instantiation 
         tcpClient = new TcpClient();
         //Issue a connection request to the server with the specified IP address
         tcpClient.Connect("10.160.52.106", 3900);
         //Get network transport stream
         stream = tcpClient.GetStream();
         //Accept data and convert to string
         byte[] data = new byte[1024];
         int receive = stream.Read(data, 0, 1024);
         string msg = Encoding.Default.GetString(data, 0, receive);
         //Remove terminal escape characters from string
         msg = strDelete(msg);
         //Show
         textBox2.AppendText(msg);
     }
     catch
     {
         textBox2.AppendText("The server is not started" + Environment.NewLine);
     }
     }

/*****************

Remove terminal transfer characters
*****************/
private string strDelete(string str)
{
int flag = -1, de = 0;
for (int i = 0; i < str.Length; i++)
{
    if (str[i] == '')
    {
        flag = i;
    }
    if (flag != -1)
    {
        de++;
    }
    if (str[i] == 'm' && flag != -1)
    {
        str = str.Remove(flag, de);
        i = flag - 1;
        flag = -1;
        de = 0;
    }
}
return str;
}

2. Operation results

3, Transmit data

1. Implementation code

The data to be sent by the client to the server is input through the textbox, then click button to send it, and the returned results from the server are displayed in the textbox.

In the interface design file, double-click the "send" button to go to the file of editing code, and click button 1_ Write the following code in the click function.

private void button1_Click(object sender, EventArgs e)
{
    //Get the text content in textBox1
    string msg = textBox1.Text + "\n";
    //Convert the text content into a bitstream and send it to the server
    byte[] data = new byte[1024];
    data = Encoding.Default.GetBytes(msg);
    stream.Write(data, 0, data.Length);
    //Receive the data stream from the server and convert it into a string
    byte[] data1 = new byte[1024];
    int receive = stream.Read(data1, 0, 1024);
    msg = Encoding.Default.GetString(data1, 0, receive);
    //Remove terminal escape characters from string
    msg = strDelete(msg);
    //Clears the contents before the display box
    textBox2.Clear();
    //Display data
    textBox2.AppendText(msg);
    //Refresh input box
    textBox1.Clear();
    //Focus the cursor on the input box
    textBox1.Focus();
}

In the code, sending data will add a \ n, because the command line input ends with a newline.

2. Operation results

4, Transform background picture

1. Implementation code

Change the game background image every 30 seconds.

First, add a timer control.
You should pay particular attention to dragging to the form instead of the control so that its parent class is Forms.

Right click the timer1 control and click properties.

  • Set Enabled to True
  • Set the Interval to 3000, which means 3000 ms = 3 s. 30 seconds is not set here. It is easy to display the effect after subsequent execution.

Double click the timer1 control to go to the code editing area.
At Timer1_ Add the following code to the tick function.
Note: four pictures will be prepared in advance:

        private int flag = 0;

        /*****************
         * Automatic map change
         *****************/
        private void timer1_Tick(object sender, EventArgs e)
        {
            flag++;
            string picturePath = @"C:\Users\12711\Pictures\APEX PIXIV" + flag + ".jpg";
            //Set picture fill
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox1.Image = Image.FromFile(picturePath);
            if (flag == 4)
            {
                flag = 0;
            }
        }

2. Operation results:

5, Complete code

github: HomeWork11-5

6, Summary

Through this experiment, I further learned C# visual programming and how to establish a connection through C# TcpClient class and use NetworkStream class to transmit data. It should be noted that when encoding a string into a bitstream, the main encoding method should be the same as the decoding method, otherwise there will be garbled code.

7, References

Coke is a little delicious: C# write online game client to connect to game server

Keywords: Python Network Protocol wireshark

Added by Cless on Tue, 30 Nov 2021 19:33:00 +0200