CocosConsoleはゲーム内にTCPサーバを立てネットワーク越しに実行中のゲームと通信する機能で、タッチイベントの発行やノードツリーの出力などができます。cocos2d-xに標準で搭載されており、CocosCodeIDEなどから利用されています。既存のコマンドを使用するだけでなく独自のコマンドを追加することも可能なので、デバッグや自動テストなど様々な応用が可能です。
初期化
ConsoleのインスタンスにはDirector経由でアクセスでき、listenOnTCPで接続を待機します。
Console *_console = Director::getInstance()->getConsole();
_console->listenOnTCP(6010);
ゲーム内で上記コードが実行されていれば、あとはTCPで接続すればいいので、例えば対話的にコマンドを実行するpythonコードは以下のようになります。
import os
import sys
from socket import *
from threading import Thread
CMD_PORT = 6010
BUFFER = 1024
cmdSocket = None
def receiver():
while True:
res = cmdSocket.recv(BUFFER)
if len(res) == 0: break
print(res)
if __name__ == "__main__":
cmdSocket = socket(AF_INET, SOCK_STREAM)
cmdSocket.connect((sys.argv[1], CMD_PORT))
Thread(target = receiver).start()
try:
while True:
cmdSocket.send(raw_input() + '\n')
except:
pass
cmdSocket.send('exit\n')
cmdSocket.close()
ゲームをエミュレータで実行している場合、localhostを指定すれば接続できます。
$ python cocos_client.py localhost
>
代表的なコマンド
標準で搭載されているコマンドをいくつか紹介します
help
登録されているコマンドとそのヘルプを一覧で表示します。
>
help
Available commands:
allocator Display allocator diagnostics for all allocators
config Print the Configuration object
debugmsg Whether or not to forward the debug messages on the console. Args: [on | off]
director director commands, type -h or [director help] to list supported directives
...
debugmsg
デバッグメッセージを受信します。cocos2d::logで出力されるメッセージが表示されるようになります。
>
debugmsg on
>
cocos2d: fullPathForFilename: No file found at src/main.luac. Possible missing file.
[LUA-print] [INFO]
[LUA-print] [INFO] # DEBUG = 2
[LUA-print] [INFO] #
[LUA-print] [INFO] # device.platform = ios
[LUA-print] [INFO] # device.model = unknown
[LUA-print] [INFO] # device.language = en
...
scenegraph
現在のシーングラフをテキストで出力します。各文字列はNodeクラスのgetDescriptionで返される値を表示しているため、このメソッドを上書きすると独自の形式で表示できます。
>
scenegraph
>
<Scene | tag = -1>
- <Node | Tag = -1
- <Node | Tag = -1
-- <Sprite | Tag = -1, TextureID = 9>
-- <Menu | Tag = -1>
--- <MenuItem | tag = -1>
---- <Sprite | Tag = 1, TextureID = 10>
---- <Sprite | Tag = 2, TextureID = 10>
-- <Layer | Tag = -1>
Total Nodes: 9
touch
画面をタッチします。オプションでスワイプも可能です。
>
touch tap 100 100
>
touch swipe 100 100 200 100
>
その他、標準で搭載されているコマンドはこの辺りで一覧されています。
https://github.com/cocos2d/cocos2d-x/blob/cocos2d-x-3.4/cocos/base/CCConsole.cpp#L290
コマンドの拡張
コマンドは独自に定義することもできます。例えば実行中のスクリーンショットを撮ってそのファイルパスを返すコマンドを登録するのは次のようになります。
#include <sys/socket.h>
...
auto name = "ss";
auto help = "take screen shot";
auto callback = [](int fd, const string& args) {
utils::captureScreen([fd](bool succeed, const string &outputFile) {
send(fd, outputFile.c_str(), outputFile.size(), 0);
}, "ss.png");
};
Director::getInstance()->getConsole()->addCommand({name, help, callback});