当前位置:网站首页>From scratch, we will completely develop an online chess game [Gobang] Based on websocket, and only use dozens of lines of code to complete all the logic.
From scratch, we will completely develop an online chess game [Gobang] Based on websocket, and only use dozens of lines of code to complete all the logic.
2022-07-26 07:07:00 【51CTO】
Gobang is a strategic game with simple and clear rules , The first to form five links wins .
In this course, two people play chess online , It's especially suitable to play on the way to work with your mobile phone .
The whole process is carried out on the crowdsource low code application platform , Use expressions to describe game logic ( Highly simplified version JS).
This course focuses on websocket Send and receive real-time messages .
Demonstration of two people playing chess online

Start playing : https://gobang.zc-app.cn Because it's an online game , Need to log in , You can register with your mobile phone and email respectively , Play with yourself on your computer and mobile phone .
URL Back plus /z Go into development mode :https://gobang.zc-app.cn/z
For detailed teaching, please move to BiliBili video : https://www.bilibili.com/video/BV1QX4y1A7FW
Chessboard structure
Use nested data components 14 * 14 Rendered from a two-dimensional array of , That is, the grid with black lines in the figure .

Square array structure
Use nested data components 15 * 15 Rendered from a two-dimensional array of , That is, the point where the black lines cross , mouse hover Highlighted circle when on component .

Player status
undefined、 Invitation in progress 、 The opponent plays chess 、 Your side plays chess
The default is no value , It means that you haven't started playing chess or it's over ( The game is divided ). When the opponent plays chess, his own side cannot fall behind .
To login
Since I play online , Just log in . You can register with your mobile phone or email .
Open the connection immediately after logging in , Some players are online , A player invited , The other party fell in love through this connection socket Instant notification .
Open the connection socket:onLogin
The first parameter $c.exp It's an object , Can contain onConnect, onData, onReconnect, onError, The first two are necessary .
The second parameter is option Options ,channels Put the channels you need to pay attention to in the array ,onOnline Indicates whether you should be notified when someone goes online ,onOffline If someone goes offline, whether to notify ,allowMultiLogin Indicates whether the same account can be logged in multiple places without forcing the previously logged in account to be offline .
After connecting :onConnect
After connecting, check and pay attention " match " Online players of channel , Exclude yourself and put it in $v.onlines Get user information in turn after the list .
The message format
There are more than one on The first expression only receives socket news . They all have a common format :type Is the message type ,x It's the message body ,from Is the sender of the message . Message recipient to And sending time d In this case .
Someone's online :onOnline
Put the online person on the top $v.onlines in , And remove the weight .
Someone is disconnected :onOffline
If you break the line, take him / She from $v.onlines remove . If it happens to be the player who is playing with you, a warning notice will be thrown .
After receiving the data :onData
First, exclude the data sent by yourself , because socket It's for broadcasting messages , I can also receive .
Then execute the corresponding expression according to the message type , The possible types are :on Invited 、on Refuse to invite 、on Be invited 、on Move later .
When someone else logs in ,【 rival 】 The question mark circle on the right will flash , Click it to pop up the online player list , Select one of them to send a chess invitation .
Send an invitation to play chess
Received a message :on Invited
If you are playing chess, send it directly "on Refuse to invite " news , Refuse to invite .
Get the other party's user information , Pop up a modal window to prompt to accept if you refuse the invitation .
Received a message :on Refuse to invite
Ahead of ” Invitation in progress “ The status of is set to null , Pop up the rejection message sent by the other party
Selectors
Accept the invitation : Be invited
Send... To the other party “on Invited “ news , Take the son of your choice .
Clear the square , Ready to play chess .
Received a message :on Invited
from It's a rival user ID,x It's the other party's choice , I can only choose another seed .
Move later
If it's not your chess playing state , Or the falling position is not in the square array , Or it has been formed 4 No more than consecutive pieces can fall .
issue "on Move later " news , Take the coordinate axis of the falling point just now .
Play the falling sound , And put your chess pieces on the falling point of the square array , And emit a halo through the dynamic class name .
Check whether the fall just now wins .
Check to win ( Form a five child connection )
To judge the victory or defeat, you only need to start from the falling point [y, x] Check in the positive and negative directions of the four lines , Cumulative 4 More than consecutive pieces of the same color are sound .
$v. Check the direction
-1 It means to check later ,0 Indicates immobility ,1 It means to check forward . such as [-1, 0] Yes X Check the axis in the direction of negative value , That is, due West ;[1, -1] Means to go first X Check the positive direction of the shaft and then go Y Shaft negative direction inspection , Northeast .
namely

Whether Luozi wins
First, take the current position as the first continuous chess piece , The first $v. Check the direction The first direction of the provided pair of directions tries to move 4 Time ( It's a cycle 4 All over ) See if there are adjacent homochromatons , Try it in another direction 4 Time .
If you get it through trial $v. Consecutive pieces Greater than 4 individual , Then the current loser wins .
Check the same chromophore adjacent to the drop
A tentative direction includes X Axis direction and Y Axis direction , Yes -1、0、1 Three kinds of shifting methods , Move the coordinates separately , Check the chess pieces of the new coordinates in the square matrix , If there are children on the coordinates , And now it's your side playing chess, and this sub is just your color , Then this piece is part of a continuous piece . In other cases, it cannot be regarded as a continuous homochromaton , For example, there is no sub on the coordinates , Or the other party's son , Or it has been discontinuous before , There is no need to continue the inspection this time .
Winning streak 5 A chess piece should also glow . The newly fallen child in front has been haloed by the dynamic class name , Now find out the other pieces of the continuous pieces .
We look for it from the continuous pieces , See if there is a chess piece with the same coordinate position as the current check .$x[0] It's a continuous piece X coordinate ,$x[1] yes Y coordinate . Be careful , Here is the dynamic class name in the nested data component ,$index Is the subscript of the current data component ,$parent.$index Is the subscript of the data component of the upper layer . But because they are placed in find() Inside the function , You need to add $ext. Represent the data provided by the context outside their functions , without $ext., That's it find() The context data provided by the function .
边栏推荐
猜你喜欢

Precious metal knowledge: lethal short-term secret script
![[749. Isolate virus]](/img/12/b8c3cdb664f4415d20c2fc5c697a41.png)
[749. Isolate virus]

What are the basics of getting started with spot silver

“蔚来杯“2022牛客暑期多校训练营1补题记录(ACDGIJ)

二叉树知识总结

Huffman coding principle

String and memory functions

Rectification ideas for the previous article

Drools(3):Drools基础语法(1)

火焰图分析Flink反压
随机推荐
曲线曲率展示
Make a chase game with pyGame
Linux c SQLite database usage
火焰图分析Flink反压
Kernel pwn 入门 (5)
Precious metal knowledge: lethal short-term secret script
20220725 convolution in automatic control principle
[database] CTE (common table expression)
屏:框贴、0贴合、全贴合
Queue assistant | product update log in June 2022
Common programming shortcut keys of idea (take off after learning the operation)
哈夫曼编码原理
Docker modifying the MySQL configuration file attached to the host does not take effect?
[romance understood by technical talents] tidb community has prepared a gift for your partner for the "Tanabata Festival". Reply: if I want to challenge, I can participate in the activity!
优炫数据库JDBC打开日志方式有哪些
Contents mismatch at: 08000000H (Flash=FFH Required=00H) ! Too many errors to display !
Curl post request on the server, using postman tool for parameter conversion
On the difference between Eval and assert
Fastdfs supports dual IP and IPv6
Depth cloning and reflection of typescript class objects