Udp-based five-play games and Udp five-play games

Source: Internet
Author: User
Tags sendmsg

Udp-based five-play games and Udp five-play games
Introduction

This article mainly describes how to use c # in the LAN to write a Wuzi game based on Udp protocol. This article mainly describes the use of Udp, game rendering, and combat logic.

Development Environment: vs2013,. Net4.0. The source code download address is provided at the end of the article.

Udp Communication

Udp is a connectionless transmission protocol, featuring low resource consumption, fast processing speed, and convenient use. messages can be sent without establishing a connection with the receiver, however, the recipient may fail to receive the sent message. In. Net, the UdpClient class is provided to Implement Udp-based communication. The following describes the basic use of Udp. 1. send informationFirst declare a UdpClient object.
UdpClient udpSend;
Then, create a method to send information.
  public void Send(string sendMsg)
        {
            udpSend = new UdpClient();
            byte[] byteMsg = Encoding.Default.GetBytes(sendMsg);
            udpSend.Send(byteMsg, byteMsg.Length, this.sendIp, sendPort);
            udpSend.Close();
        }
  2. Accept InformationFirst, declare a UdpClient object.
 UdpClient  udpReceive;
Create a method to initialize the UdpClient object, and open up a thread to receive messages and a method to receive messages.
public void StartReceive ()
         {
             // Accept message from port 5888
             udpReceive = new UdpClient (5888);
             Thread threadReceive = new Thread (ReceiveMessages);
             threadReceive.IsBackground = true;
             threadReceive.Start ();
         }
     private void ReceiveMessages ()
         {
             IPEndPoint remoteIPEndPoint = new IPEndPoint (IPAddress.Any, 0); // Get the IP and port information of the sender
             while (true)
             {
                 try
                 {
                     // This sentence will generate an exception when receivingUdpClient is closed
 
                     byte [] receiveBytes = udpReceive.Receive (ref remoteIPEndPoint);
 
                     string message = Encoding.Default.GetString (receiveBytes, 0, receiveBytes.Length);
                     MessageParse (message); // To analyze the message and process
                 }
                 catch
                 {
                     break;
                 }
             }
         }
At this point, the accept information and the send information are accepted, which is simpler to use than the Tcp protocol ,. It is the best choice for communication between games in the LAN. However, it is worth noting that. You cannot run two identical programs at the same time. When receiving information, two upd instances cannot listen to the same port number at the same time. For example, after writing the program, you need to use the ip address 127.0.0.1 on the local machine to debug the program you have changed. Then the program will be like this. Program 1: the port number accepted by UdpReceive is 5888. The ip addresses and port numbers sent by UdpSend are 127.0.0.1 and 5888 respectively ". Program 2: the port number accepted by UdpReceive is 5888. The ip addresses and port numbers sent by UdpSend are 127.0.0.1 and 5888 respectively ". In this way, an error occurs when you run program 2, because program 1 and Program 2 listen to the same port number, which is not allowed (the udp listening port number cannot be occupied by other programs, must be unique), so small modifications are required. Program 1: the port number accepted by UdpReceive is 5888. The ip addresses and port numbers sent by UdpSend are 127.0.0.1 and 5887 respectively ". Program 2: the port number accepted by UdpReceive is 5887. The ip addresses and port numbers sent by UdpSend are 127.0.0.1 and 5888 respectively ". In this way, a slight change will not cause errors.

Game Rendering

Anyone who has played wuziqi knows that it is mainly used to draw boards and pawns. A little more humane, it is to mark the last piece placed by the other party, let us know more clearly which of the following is the opponent's pawn.

Create a global variable to save the status of each position on the board. Const int BOARDSIZE = 15; const int BOARDLENGTH = 800; int [,] chessMap = new int [BOARDSIZE, BOARDSIZE]; // where the value is 0: no chess piece, 1: white chess, 2: The following code is written for the Paint method of the PictureBox control of the checker control:
// paint method
   private void picChessboard_Paint (object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            // Draw the chessboard
            chessBoard.DrawBoard (g);
            // Draw chess pieces
            chessBoard.DrawChess (g);
        }
 
  // initialize global variables
        public void InitialChess ()
        {
            for (int i = 0; i <BOARDSIZE; i ++)
            {
                for (int j = 0; j <BOARDSIZE; j ++)
                {
                    chessMap [i, j] = 0;
                }
            }
            this.picChessboard.Invalidate ();
        }
        // Draw the chessboard
        public void DrawBoard (Graphics g)
        {
            Pen p = new Pen (Brushes.Black, 3.0f);
            // p.Width = 2f;
            // horizontal line
            for (int i = 0; i <BOARDSIZE; i ++)
            {
                g.DrawLine (p, new Point (0, (i + 1) * 50), new Point (BOARDLENGTH, (i + 1) * 50));
            }
            // vertical line
            for (int i = 0; i <BOARDSIZE; i ++)
            {
                g.DrawLine (p, new Point ((i + 1) * 50, 0), new Point ((i + 1) * 50, BOARDLENGTH));
            }
        }
 
        // Draw chess pieces
        public void DrawChess (Graphics g)
        {
 
            for (int i = 0; i <BOARDSIZE; i ++)
            {
                for (int j = 0; j <BOARDSIZE; j ++)
                {
                    if (chessMap [i, j] == 1)
                    {
                        g.DrawImage (Properties.Resources.whitechess, new Point (50 * (i + 1)-20, 50 * (j + 1)-20));
                    }
                    if (chessMap [i, j] == 2)
                    {
                        g.DrawImage (Properties.Resources.blackchess, new Point (50 * (i + 1)-20, 50 * (j + 1)-20));
                    }
                }
            }
            if (pCurrent.X! =-1)
            {
                // Draw the red callout on the last fallen piece
                g.FillEllipse (Brushes.Red, new Rectangle ((pCurrent.X + 1) * 50-5, (pCurrent.Y + 1) * 50-5, 10, 10));
            }
        }
Now the game interface is complete, and the effect is as follows.

Battle Logic

The logic of combat is simply two parts. 1. Play chess on your own, and then set the global variable chessMap to draw the chess piece on the notification page. Accept the message from the opponent and set the global variable chessMap to draw the chess piece on the notification page. 2. Check the winning or losing status after playing chess.

Only key code is posted here. For details, you can download the source code and write the comments in it in details.

1. Chess code

/// <summary>
        /// play chess
        /// </ summary>
        /// <param name = "flag"> Set the flag of the global map chessMap </ param>
        /// <param name = "x"> Chessboard x coordinate </ param>
        /// <param name = "y"> Y coordinate of the chessboard </ param>
        public void PutOneChess (int flag, int x, int y)
        {
            if (isPut | myFlag! = flag) // Judgment whether to play chess by yourself or someone else
            {
                // Calculate the position of the row and column of the mouse click position in the chessboard
                int tolerance = 8;
                int row = y / 50;
                int rows = y% 50;
                int col = x / 50;
                int cols = x% 50;
 
                if (rows + tolerance> = 50)
                {
                    row ++;
                }
                else if (rows-tolerance <= 0)
                {
                }
                else
                {
                    return; // Not selected
                }
 
                if (cols + tolerance> = 50)
                {
                    col ++;
                }
                else if (cols-tolerance <= 0)
                {
                }
                else
                {
                    return;
                }
 
                col--;
                row--;
 
                if (col> = 0 && col <BOARDSIZE && row> = 0 && row <BOARDSIZE)
                {
                    this.chessMap [col, row] = flag;
                    pCurrent = new Point (col, row); // Save the latest position where the pieces were placed for labeling and remorse
                    this.picChessboard.Invalidate ();
                    if (myFlag == flag) // If you play chess yourself
                    {
                        this.isPut = false; // the opponent's turn
                        UpdateRemoteChessBoardDelegate (flag, x, y); // will update the opponent's chessboard
 
                        if (IsWin (col, row)) /// I won
                        {
                            InformRemoteResultDelegate ();
                        }
                    }
                    else
                    {
                        this.isPut = true; // It's your turn to play chess.
                    }
                }
            }
        }

 

2. Check the winning or losing code

// horizontal
        private bool Is1 (int c, int r)
        {
            int count = 1;
            for (int i = c + 1; i <c + 5; i ++)
            {
                if (i <BOARDSIZE)
                {
                    if (chessMap [i, r] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            for (int i = c-1; i> c-5; i--)
            {
                if (i> = 0)
                {
                    if (chessMap [i, r] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if (count> 4)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
        // vertical
        private bool Is2 (int c, int r)
        {
            int count = 1;
            for (int i = r + 1; i <r + 5; i ++)
            {
                if (i <BOARDSIZE)
                {
                    if (chessMap [c, i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            for (int i = r-1; i> r-5; i--)
            {
                if (i> = 0)
                {
                    if (chessMap [c, i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if (count> 4)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
        // Top left-bottom right
        private bool Is3 (int c, int r)
        {
            int count = 1;
            for (int i = 1; i <5; i ++)
            {
                if ((c-i)> = 0 && (r-i)> = 0)
                {
                    if (chessMap [c-i, r-i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            for (int i = 1; i <5; i ++)
            {
                if ((c + i) <BOARDSIZE && (r + i) <BOARDSIZE)
                {
                    if (chessMap [c + i, r + i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if (count> 4)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
 
        // bottom right-top left
        private bool Is4 (int c, int r)
        {
            int count = 1;
            for (int i = 1; i <5; i ++)
            {
                if ((c-i)> = 0 && (r + i) <BOARDSIZE)
                {
                    if (chessMap [c-i, r + i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            for (int i = 1; i <5; i ++)
            {
                if ((c + i) <BOARDSIZE && (r-i)> = 0)
                {
                    if (chessMap [c + i, r-i] == myFlag)
                    {
                        count ++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if (count> 4)
            {
                return true;
            }
            else
            {
                return false;
            }
        } 
You can view the source code by yourself. 3. Final game interface effect  4. NoteCommunication is sent in the form of a string, separated by the character "|. Information is divided into information headers and content.
  • Send message: Talk | "hello"
  • Notify the opponent to play chess: Put | 1 | 230 | 400
  • Notify the other party to play the game: Lose |
  • Apply for repentance: ReSet |
  • The other party agrees: OkSet |
  • The other party exits the game: Exit |
 

Summary

By writing this little game, I learned the specific usage of Udp and realized the convenience of delegation in the window program design. In the past, the program delegation I wrote was useless, we only know how to use the delegate syntax, but do not know how to use it or where to use it.

So much is shared. If you have any questions about this program, you can trust me in private; if you have suggestions for this program, you can also trust me in private. Hey.
Download link: http://download.csdn.net/detail/mingge38/9387603


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.