Leaf and Cocos Creator game (ii) registration and landing

Source: Internet
Author: User

For the installation and configuration of MongoDB, refer to the following:

https://blog.csdn.net/heshushun/article/details/77776706

Proto Registration Protocol Extension:

1. Service side:

Compile the Lobby.proto file (not known about this?) Please read the article "using Protobuf in Golang") to get the Lobby.pb.go file with the following command:
protoc --go_out=. lobby.proto
Place the Lobby.pb.go under the Leafserverexample src/msg folder.

2. Client:

Copy the Lobby.proto into the Leafservercocosclient Node_modules.bin folder and compile the proto file into a static file using:

pbjs -t static-module -w commonjs -o protocol.js lobby.protopbts -o protocol.d.ts protocol.js

Copy the Protocol.js and protocol.d.ts to the Leafservercocosclient Assets\script\protocol folder.

3.lobby.proto:

syntax = "proto3";package msg;enum Result {    REGISTER_SUCCESS=0;    REGISTER_FAIL=1;    LOGIN_SUCCESS=2;    LOGIN_FAIL=3;}message Test {    string Test = 2;}// 用户登陆协议message UserLogin  {    string LoginName = 1;   // 用户名    string LoginPW =2;      // 密码}// 注册协议message UserRegister {    string LoginName =1;    // 用户名    string LoginPW =2;      // 密码}// 消息返回协议message UserResult {    Result RetResult =1;    string ErrorInfo = 2;}// 玩家有角色的情况message UserST {    string UID    =1;       // 账号ID    string ServerID =2;     // 服务器ID    string RoleUID  =3;     // 角色UID    string RoleName =4;     // 角色名字    string RoleLev =5;      // 角色等级    string Coin  =6;        // 金币    // 其他的暂时不做定义}

Registering a message handler with the current module (game module)

func init() {    handler(&msg.UserLogin{}, handleUserLogin)    handler(&msg.UserRegister{}, handleUserRegister)}

Handling related messages

Func handleuserregister (args []interface{}) {m: = Args[0]. ( *msg. Userregister) A: = Args[1]. (Gate. Agent) Name: =m.getloginname () pwd: =M.GETLOGINPW () log. Debug ("Receive Userregister name=%v", M.getloginname ()) Reg: = Regexp.mustcompile ('/^[a-za-z\d]\w{2,10}[a-za-z\d]$/' ) Matched: = Reg. FindString (name) if (matched!= "") {log. Debug ("Userregister name is Licit",)} ERR: = Mongodbmgr. Find ("Game", "Login", Bson. m{"name": Name,}) If Err = = Nil {fmt. PRINTLN (Err) log. Debug ("Userregister Find in Fail",) Retbuf: = &msg. userresult{retresult:msg. Result_register_fail, ErrorInfo: "The account already exists!" ",} a.writemsg (RETBUF)} err =mongodbmgr. Insert ("Game", "Login", Bson. m{"name": Name, "Password":p WD}) If Err! = Nil {fmt. PRINTLN (Err) log. Debug ("Userregister write in Fail",) Retbuf: = &msg. userresult{retresult:msg. Result_register_fail, ErrorInfo: "Registration failed, please try again later!" ",} a.writemsg (RETBUF)} else{log. Debug ("Userregister write in Success",) Retbuf: = &msg. userresult{retresult:msg. Result_register_success,} a.writemsg (RETBUF)}}
func handleUserLogin(args []interface{}) {    m := args[0].(*msg.UserLogin)    a := args[1].(gate.Agent)    log.Debug("receive UserLogin name=%v", m.GetLoginName())    retBuf := &msg.UserResult{        RetResult: msg.Result_LOGIN_SUCCESS,        ErrorInfo:"登陆失败,请稍后再试!",    }    a.WriteMsg(retBuf)}

Connect MongoDB when initializing

Package Mongodbmgrimport ("FMT" "Github.com/name5566/leaf/db/mongodb" "Github.com/name5566/leaf/log" "gopkg.i N/mgo.v2 "" Gopkg.in/mgo.v2/bson ")//connection message var Dialcontext = new (MongoDB. Dialcontext) Func init () {connect ()}func Connect () {c, err: = MongoDB. Dial ("localhost", ten) if err! = Nil {fmt.     PRINTLN (ERR) return}//defer C.close ()//Index C.ensureuniqueindex ("Game", "Login", []string{"name"}) Log. Release ("MongoDB Connect success") Dialcontext = C Test ()}func test () {err: =find ("Game", "Login", Bson. m{"name": "Hello"}) if Err = = Nil {log. Debug ("Test has data,regfail!",)}else{err =insert ("Game", "Login", Bson. m{"name": "Hello", "password": "123456"}) if err! = Nil {fmt. PRINTLN (Err) log. Debug ("Test write in Fail",)}}}func Example () {c, err: = MongoDB. Dial ("localhost", ten) if err! = Nil {fmt. PRINTLN (ERR) return} defer C.close ()//SessiOn s: = C.ref () defer c.unref (s) Err = s.db ("Test"). C ("counters"). RemoveID ("test") if err! = Nil && Err! = MgO. Errnotfound {fmt.  PRINTLN (ERR) return}//auto Increment err = c.ensurecounter ("Test", "counters", "test") if err! = Nil {FMT. PRINTLN (ERR) return} for I: = 0; I < 3; i++ {id, err: = C.nextseq ("Test", "counters", "test") if err! = Nil {fmt. PRINTLN (ERR) return} FMT.    Println (ID)}//Index C.ensureuniqueindex ("Test", "counters", []string{"Key1"})//Output://1//2 3}func Find (DB string, collection string, Docs interface{}) error{c:=dialcontext s: = C.ref () Defer c.unref ( s) type person struct {id_ Bson.    ObjectId ' Bson: "_id" ' Name string ' Bson: ' name '};    User:=new (person); ERR: = S.db (DB). C (collection). Find (Docs). One (&user)//idstr:=user. Id_. Hex ()//fmt.  Println (IDSTR) if err! = Nil {      Fmt. PRINTLN (ERR) return err} return err;}    Goroutine safefunc Insert (db string, collection string, Docs interface{}) error {C:=dialcontext s: = C.ref () Defer C.unref (s)////CREATE index//index: = MgO. index{//Key: []string{"Name"},//index field, default ascending, if required in descending order in front of field plus-//unique:true,//Unique index with MySQL unique    Index//Dropdups:true,//index re-replace old document, unique True when invalid//background:true,///Background CREATE INDEX//} If err: = S.db (DB). C (collection). Ensureindex (index); Err! = Nil {//FMT. PRINTLN (ERR)//Return err//}//if ERR: = S.db (DB). C (collection). Ensureindexkey ("$2dsphere:location"); Err! = Nil {//Create a range index//FMT. PRINTLN (ERR)//Return err//} ERR: = S.db (DB). C (collection). Insert (DOCS) if err! = Nil {fmt. PRINTLN (ERR) return err} return err}

Cocos Creator Client Registration and Login

Simple legality Judgment Tool class

Import Messagedialog from './messagedialog '; interface checkret{Ret:boolean, msg:string}interface message{title: String, text:string}export default class Utils {//Detect if user name is valid static CHECK_USR (str:string): checkret{let c=        <CheckRet>{};        var b:regexp=/^[a-za-z\d]\w{2,10}[a-za-z\d]$/;            if (B.test (str)) {C.ret = true;        c.msg = "User name is legal";            } else {C.ret = false;        c.msg = "User name is not valid";    } return C;        }//Determine if password entry is legal, one is length, one is no special character static CHECK_PSW (str:string): checkret{let c=<checkret>{};            if (Str.length > 5 && str.length<21) {C.ret = true;        C.msg = "";            }else {C.ret = false;        c.msg = "Password length is irregular";        } var b:regexp =/^[a-za-z\d]\w{2,10}[a-za-z\d]$/;            if (B.test (str)) {C.ret = true;        C.msg = "";            }else {C.ret = false; C.msg = "DenseCode character is not standard ";    } return C;        }//Determine if the mobile phone number format is valid static Check_tel (str:string): checkret{let c=<checkret>{};        var regx=/^ (?: 13\d|15\d|18[123456789])-?\d{5} (\d{3}|\*{3}) $/;            if (Regx.test (str)) {C.ret = true;        C.msg = "";            }else{C.ret = false;        c.msg = "Cell phone number is not compliant";    } return C;        }//Determine if the email address format is valid static Check_mail (str:string): checkret{let c=<checkret>{}; var regm =/^[a-za-z0-9_-]+@[a-za-z0-9_-]+ (\.[            a-za-z0-9_-]+) +$/;//Verify Mail's regular expression, ^[a-za-z0-9_-]: must begin with a letter, underscore, number, if (Str.match (REGM)) {C.ret = true;                    C.msg = "";            } else{C.ret = false;        c.msg = "Email address is not compliant";    } return C;  } static Showtips (title:string,text:string) {messagedialog.getinstance (). Showtips ({Title:title,text:text})}}

Registration Process

Import Netmessagectrl from './netmessagectrl '; import Utils from './utils '; const {Ccclass, property} = CC._DECORATOR@CCCL Assexport default class Register extends Cc.component {@property (cc. EditBox) name:cc.    EditBox = null; @property (CC. EditBox) pwd:cc.    EditBox = null; OnLoad () {} onbtnpanel () {this.node.parent.active = false} onbtncomfirm () {var name = this.        name.string; var pwd = this.        pwd.string;            if (name && pwd) {Let check = UTILS.CHECK_USR (name) Let checkpwd = UTILS.CHECK_PSW (name) if (Check.ret) {if (Checkpwd.ret) {netmessagectrl.getinstance (). Sendregister (name,p                WD);                 } else{utils.showtips ("hint", Checkpwd.msg)}} else{ Utils.showtips ("hint", Check.msg)}} else{Utils.showtips ("Prompt", "Please enter the full number of registrations According to ")}}}

Handling incoming replies

  dealMessage(id: number,data: Uint8Array ){      switch(id){            case netConfig.ProtocolId.Test:                this.dealTest(data)                break;            case netConfig.ProtocolId.UserResult:                this.dealUserResult(data)                break;            default:                break;        }    }  //注册登陆登一系列用户行为的结果都通过netConfig.ProtocolId.UserResult协议返回   dealUserResult(data: Uint8Array){        console.log("get UserResult message!");        let gameMsg = msg.UserResult.decode(data);        console.log(gameMsg);    }

Example Gihub Address:

Server:https://github.com/ddkgo/leafserverexample.git
Client:https://github.com/ddkgo/leafservercocosclient.git

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.