Zero-based development of small game voice open black Demo

Play online games with friends and family. If the game has real-time voice capabilities, it can shorten the distance between players and add more fun. We take the classic Chinese chess as an example to develop online voice chess. This article mainly involves the following points:

  1. The rules of online games, this article takes Chinese chess as an example.
  2. With the help Zego SDKof real-time messaging capabilities, real-time data transmission for online games is realized.
  3. With the help Zego SDKof voice capabilities, online voice is realized.

Note: Although this article takes Chinese Chess as an example, other online mini games can also be applied, but the game rules are different.

The final effect is as follows:

insert image description here

1 Chinese Chess Game Rules

Regarding the game rules of Chinese chess, I will give a brief introduction here.

  1. Car: Can only go in a straight line.
  2. Horse: You can only move diagonally. If there are chess pieces on the long side in the diagonal direction, you cannot move.
  3. Bishop: You can only walk diagonally according to the word, and you cannot cross the river. If there is a chess piece in the center of the word, you cannot go.
  4. Shi: You can only walk on the diagonal of the Nine Palaces.
  5. Shuai: You can only walk in the Nine Palaces. You need to pay attention. If the two handsome players are on the same straight line, there must be chess pieces in the middle, otherwise they are not allowed to be on the same straight line.
  6. Run: If you do not capture, the same rules as the rook. If you capture a piece, you need to have a chess piece between the piece that is captured and the run.
  7. Bing: You can only move forward when you have not crossed the river. After crossing the river, you can move left and right and move forward, but you cannot move backwards.

Every time a player plays chess, he first needs to verify whether the target position is a valid position, that is, whether it complies with the rules of the game:

// 判断是否可以移动
public static boolean canMove(Chessboard chessboard, int fromX, int fromY, int toX, int toY) {
    
    
    //不能原地走
    if (fromX == toX && fromY == toY)
        return false;

    Chess chess = chessboard.board[fromY][fromX];
    // 首先,确保目标位置不是自己的子
    Chess[][] board = chessboard.board;
    if (board[toY][toX] != null && board[toY][toX].isRed() == chessboard.isRed) {
    
    
        return false;
    }

    switch (chess.type) {
    
    
        case RED_SHUAI:
        case BLACK_SHUAI:
            return canShuaiMove(chessboard, fromX, fromY, toX, toY);
        case RED_SHI:
        case BLACK_SHI:
            return canShiMove(chessboard, fromX, fromY, toX, toY);
        case RED_XIANG:
        case BLACK_XIANG:
            return canXiangMove(chessboard, fromX, fromY, toX, toY);
        case RED_MA:
        case BLACK_MA:
            return canMaMove(chessboard, fromX, fromY, toX, toY);
        case RED_CHE:
        case BLACK_CHE:
            return canCheMove(chessboard, fromX, fromY, toX, toY);
        case RED_PAO:
        case BLACK_PAO:
            return canPaoMove(chessboard, fromX, fromY, toX, toY);
        case RED_ZU:
        case BLACK_ZU:
            return canZuMove(chessboard, fromX, fromY, toX, toY);
    }

    return true;
}

If it is a walk that conforms to the rules, then directly remove the chess piece at the target position (you must first judge that there is a chess piece and it is the opponent's chess piece). The game can continue like this until one side is eaten, and the game is over.

2 Real-time game data transmission

Real-time transmission of game data can TCPbe realized based on its own, but it has the following disadvantages:

  1. Both parties must be on the same LAN, or both parties must use valid Internet ipaddresses.
  2. It is necessary to carefully maintain the sending and receiving of message data, the code volume is large and inconvenient to maintain.

We can use Zego SDKthe powerful real-time message capability of ZTE to realize real-time chessboard synchronization. For details on how to access it, please refer to the official document:
https://doc-zh.zego.im/article/3575 . Through this official document, Zego SDKthe access work can basically be completed.

2.1 Login/logout room

Before using it Zego SDK, you must first log in to the room, because whether it is real-time voice or real-time message, it is based on the room. It is assumed that the reader has created the engine object according to the official document tutorial mEngine. Next is the login implementation code:

public boolean loginRoom(String userId, String userName, String roomId, String token) {
    
    

    ZegoUser user = new ZegoUser(userId, userName);
    ZegoRoomConfig config = new ZegoRoomConfig();
    config.token = token; // 请求开发者服务端获取
    config.isUserStatusNotify = true;
    mEngine.loginRoom(roomId, user, config, (int error, JSONObject extendedData) -> {
    
    
        // 登录房间结果,如果仅关注登录结果,关注此回调即可
    });
    Log.e(TAG, "登录房间:" + roomId);
    return true;
} 

The logout operation is relatively simple, mEngine.logoutRoom(roomId);just specify the room ID.

2.2 Send real-time message

With the previous preparations, the next step is to achieve real-time board synchronization. Encapsulate a send message function:

public void sendMsg(String roomId, ArrayList<ZegoUser> userList, Msg msg) {
    
    

    String msgPack = msg.toString();
    // 发送自定义信令,`toUserList` 中指定的用户才可以通过 onIMSendCustomCommandResult 收到此信令
    // 若 `toUserList` 参数传 `null` 则 SDK 将发送该信令给房间内所有用户
    mEngine.sendCustomCommand(roomId, msgPack, userList, new IZegoIMSendCustomCommandCallback() {
    
    
        /**
          * 发送用户自定义消息结果回调处理
          */
        @Override
        public void onIMSendCustomCommandResult(int errorCode) {
    
    
            //发送消息结果成功或失败的处理
            Log.e(TAG, "消息发送结束,回调:" + errorCode);
        }
    });

}

Among them, roomIdit represents the room number and userListthe list of recipients, msgwhich is an entity class customized by us. Create an entity class representing the real-time chessboard interface:

public class MsgBoard extends Msg {
    
    
    public boolean isRedPlaying; //接下来是否是红方下棋
    public byte[][] board; //当前棋局面
    public int fromX;
    public int fromY;
    public int toX;
    public int toY;

    public MsgBoard(int msgType, String fromUserId, boolean isRedPlaying, byte[][] board, int fromX, int fromY, int toX, int toY) {
    
    
        super(msgType, fromUserId);
        this.board = board;
        this.isRedPlaying = isRedPlaying;
        this.fromX = fromX;
        this.fromY = fromY;
        this.toX = toX;
        this.toY = toY;
    }
}

After each player finishes playing chess, send the current position of the chess piece (if there is a server, for safety, it is best to let the server do this work). In this way, it is not limited to 2 game players. If there are multiple viewers, any viewer can watch the game online at any time.

3 Access to real-time voice

Section 2 completed Zego SDKthe access, and then completed the real-time voice function. For the real-time voice implementation process, please refer to the official document https://doc-zh.zego.im/article/7636 . In short,
the most important are 2 steps:

  1. push voice stream
  2. pull voice stream

Note: All operations must be done after successfully logging into the room, otherwise it will fail.

3.1 Streaming

The real-time voice streaming code is as follows:

public void pushStream(String streamId) {
    
    
    //不管有没有推流,先停止推流
    mEngine.stopPublishingStream();
    mEngine.startPublishingStream(streamId);
    Log.e(TAG, "已推流:" + streamId); 
}

Here's the streamIdsuggested RoomID_UserID_后缀form, to ensure uniqueness, to avoid 串流.

3.2 Streaming

As the name suggests, streaming is to pull the real-time voice stream of the other party. How do you know each other streamID? The following callback functions can be monitored:

 public void onRoomStreamUpdate(String roomID, 
                                ZegoUpdateType updateType,
                                ArrayList<ZegoStream> streamList,
                                JSONObject extendedData) ;

This callback function will be triggered once there is a new streaming push in the room or the streaming stops pushing. We updateTypejudge whether to add or delete according to the parameters:

if(updateType == ZegoUpdateType.ADD){
    
    
   //表示有新增流
} else if (updateType == ZegoUpdateType.DELETE) {
    
    
   //表示有流停止推送
}

Once it is judged that there is a new stream, you can directly pull the other party's stream. The code for pulling and stopping the stream is as follows:

public void pullStream(String streamId) {
    
    
    mEngine.startPlayingStream(streamId);
}

public void stopPullStream(String streamId) {
    
    
    mEngine.stopPlayingStream(streamId);
}

4 Summary

The online voice Chinese chess game is realized, and the real-time synchronization and real-time voice capabilities of this article can be directly applied to any other game. I have encapsulated these two capabilities, and readers can directly download the source code for reuse.

The source code is as follows:
https://github.com/KaleTom/OnlineGame

Developers who have development plans in the near future can check it on the official website of iGoo, which coincides with the 10% discount on all audio and video products for the seventh anniversary of iGou, suitable for small and medium-sized enterprises and personal development studios with budget requirements.
The author strives for small benefits for everyone: contact the business to get RTC product discounts, and send "RTC Seventh Anniversary Benefits" to have a surprise!

Guess you like

Origin blog.csdn.net/RTC_SDK_220704/article/details/125766860