player.cpp
#include <stdio.h>
#include
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
using namespace std;
#define PORT_ID 1024
#define SOCKET_IP “127.0.0.1”
#define MAXLEN 1024
int main(int argc, char* argv[])
{
int n;
char inbuff[1024],outbuff[1024];
string msg;
int socket_fd = socket(AF_INET,SOCK_STREAM,0);
if (-1 == socket_fd)
{
cout<< “socket create fail” << endl;
exit(1);
}
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_ID);
addr.sin_addr.s_addr = inet_addr(SOCKET_IP);
int res = connect(socket_fd,(struct sockaddr*)&addr,sizeof(addr));
if (-1 == res)
{
cout << “connect create fail” <<endl;
exit(-1);
}
cout<<“ip — “<<argv[1]<<endl;
msg = “(”;
msg.append(argv[1]).append(”)”);
strcpy(outbuff,msg.c_str());
printf("send : %s ",outbuff);
sleep(1);
send(socket_fd,outbuff,strlen(outbuff),0);
while (true)
{
memset(inbuff,0,MAXLEN);
n = recv(socket_fd,inbuff,MAXLEN,0);
if(-1 == n){
cout << “recieve fail” <<endl;
exit(-1);
}
inbuff[n] = ‘\0’;
msg = inbuff;
if(“OK”==msg)
{
continue;
}
else if (NULL == inbuff)
{
break;
}
else
{
printf(“来自服务端的消息: %s \n”,inbuff);
string action[4] = {“w”,“a”,“s”,“d”};
string fire[2] = {"_"," “};
msg = “[”;
for (int i = 0; i < 7; i++)
{
msg.append(action[rand()%4]);
msg.append(fire[rand()%2]);
}
msg.append(”]");
strcpy(outbuff,msg.c_str());
printf(“send %s \n”,outbuff);
send(socket_fd,outbuff,strlen(outbuff),0);
}
}
close(socket_fd);
return 0;
}
修改版player.cpp(可指挥一个坦克进行偷家):
#include <stdio.h>
#include
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include “json/json.h”
using namespace std;
#define PORT_ID 10059
#define SOCKET_IP “127.0.0.1”
#define MAXLEN 1024
int main(int argc, char* argv[])
{
int n;
char inbuff[1024],outbuff[1024];
string msg;
int socket_fd = socket(AF_INET,SOCK_STREAM,0);
if (-1 == socket_fd)
{
cout<< “socket create fail” << endl;
exit(1);
}
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_ID);
addr.sin_addr.s_addr = inet_addr(SOCKET_IP);
int res = connect(socket_fd,(struct sockaddr*)&addr,sizeof(addr));
if (-1 == res)
{
cout << “connect create fail” <<endl;
exit(-1);
}
cout<<“ip — “<<argv[1]<<endl;
msg = “(”;
msg.append(argv[1]).append(”)”);
strcpy(outbuff,msg.c_str());
printf(“send : %s “,outbuff);
sleep(1);
send(socket_fd,outbuff,strlen(outbuff),0);
int count=100;
while (true)
{
memset(inbuff,0,MAXLEN);
n = recv(socket_fd,inbuff,MAXLEN,0);
if(-1 == n){
cout << “recieve fail” <<endl;
exit(-1);
}
inbuff[n] = ‘\0’;
msg = inbuff;
if(“OK”==msg)
{
continue;
}
else if (NULL == inbuff)
{
break;
}
else
{
//printf(“来自服务端的消息: %s \n”,inbuff);
printf(“count value: %d \n”,count);
string action[4] = {“w”,“a”,“s”,“d”};
string fire[5] = {” “,”^”,“V”,"<",">"};
msg = “[”;
for (int i = 0; i < 1; i++)
{
if(count>90)
msg.append(action[0]);
else if(count>58) msg.append(action[3]);
else if(count>48) msg.append(action[2]);
else msg.append(action[3]);
if(count<48)
msg.append(fire[2]);
else
msg.append(fire[0]);
count–;
}
for (int i = 1; i < 7; i++)
{
msg.append(action[1]);
msg.append(fire[0]);
}
msg.append("]");
strcpy(outbuff,msg.c_str());
printf(“send %s \n”,outbuff);
send(socket_fd,outbuff,strlen(outbuff),0);
printf(“发送出去的消息: %s \n”,outbuff);
}
}
close(socket_fd);
return 0;
}
README.md
1.代码编译
sudo apt-get install g++
g++ player.cpp -o player.out
2.代码运行
运行服务器
python3 MainController.py --player1-id=123 --player2-id=456
运行客户端
./a.out 123 & ./a.out 456
json解析a.cpp
#include <stdio.h>
#include <stdlib.h>
#include <json/json.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include
#include
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
//模拟从服务器接收的数据
string gamejson="{“winner”: “p1”, “map_data”: “OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO12321YY44_______534435_______44YY12321OO12321YY0________4YYYY4________0YY12321OO12321YY0________4Y55Y4________0YY12321OO12321YYO________4Y55Y4________OYY12321OO123451234Y____0000YY0000____Y432154321OO123451234Y____3443333443____Y432154321OO_____12341234_34YYYYYY43_43214321_____OOO_W__12341234_34Y5555Y43_43214321____OOO___A_12341234O45Y5115Y54O43214321_da__OO_AAA_12341234O45Y5115Y54O43214321a____OO__AA_12341234O34Y5555Y43O43214321_____OOO____12341234_34YYYYYY43_43214321_ss_OOO_____12341234_3443333443_43214321_____OO123451234Y____0000YY0000____Y432154321OO12321YYO________4Y55Y4________OYY12321OO12321YY0________4Y55Y4________0YY12321OO12321YY0________4YYYY4________0YY12321OO12321YY44_______534435_______44YY12321OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO”, “countdown”: 298, “allow_fire”: {“0”: 1, “1”: 1, “2”: 1, “5”: 1, “6”: 1}, “score”: {“p1”: 494, “p2”: 494}, “status”: “running”, “p2”: {“0”: 395, “1”: 396, “2”: 434, “5”: 515, “6”: 516}} ";
Json::Reader reader;
Json::Value value;
Json::Reader preader;
Json::Value pvalue;
//定义json字段
int a = reader.parse(gamejson,pvalue);
string winner = pvalue[“winner”].asString();
string mapdata = pvalue[“map_data”].asString();
int countdown = pvalue[“countdown”].asInt();
int allowfire0 = pvalue[“allow_fire”][“0”].asInt();
int allowfire1 = pvalue[“allow_fire”][“1”].asInt();
int allowfire2 = pvalue[“allow_fire”][“2”].asInt();
int allowfire3 = pvalue[“allow_fire”][“3”].asInt();
int allowfire4 = pvalue[“allow_fire”][“4”].asInt();
int allowfire5 = pvalue[“allow_fire”][“5”].asInt();
int allowfire6 = pvalue[“allow_fire”][“7”].asInt();
int score1 = pvalue[“score”][“p1”].asInt();
int score2 = pvalue[“score”][“p2”].asInt();
string status = pvalue[“status”].asString();
int player0 = pvalue[“p2”][“0”].asInt();
int player1 = pvalue[“p2”][“1”].asInt();
int player2 = pvalue[“p2”][“2”].asInt();
int player3 = pvalue[“p2”][“3”].asInt();
int player4 = pvalue[“p2”][“4”].asInt();
int player5 = pvalue[“p2”][“5”].asInt();
int player6 = pvalue[“p2”][“6”].asInt();
//输出
cout<<pvalue[“winner”].asString()<<endl;
cout<<mapdata<<endl;
cout<<countdown<<endl;
cout<<allowfire0<<endl;
cout<<allowfire1<<endl;
cout<<allowfire2<<endl;
cout<<allowfire3<<endl;
cout<<allowfire4<<endl;
cout<<allowfire5<<endl;
cout<<score1<<endl;
cout<<score2<<endl;
cout<<status<<endl;
cout<<player0<<endl;
cout<<player1<<endl;
cout<<player2<<endl;
cout<<player3<<endl;
cout<<player4<<endl;
cout<<player5<<endl;
return 0;
}
运行命令:
g++ a.cpp -o a -ljsoncpp
player.py
import argparse
import socket # 导入socket模块
import random
import time
import GameFrame
from GameFrame import Globals
parser = argparse.ArgumentParser(description=‘manual to this script’)
parser.add_argument(’–player-id’, type=str, default=’’)
parser.add_argument(’–ip’, type=str, default=‘127.0.0.1’)
parser.add_argument(’–port’, type=int, default=10059)
args = parser.parse_args()
client = socket.socket() # 创建socket对象
client.connect((args.ip, args.port))
number = 0
msg = ‘(’ + args.player_id + ‘)’
time.sleep(1)
client.send(msg.encode(“utf-8”))
while True:
from_server_msg = client.recv(1024)
print(“来自服务端的消息:”, from_server_msg.decode(encoding=‘utf-8’))
str_msg = str(from_server_msg, encoding=‘utf-8’)
if str_msg == ‘OK’:
continue
if not Globals.key_control:
if number % 5 == 0:
msg = ‘[’
action = [‘w’, ‘a’, ‘s’, ‘d’]
fire = [’’, '’, ‘_’,]
for i in range(7):
msg = msg + action[random.randint(0, len(action) - 2)] + fire[random.randint(0, len(fire) - 1)]
msg += ‘]’
print("send " + msg)
client.send(msg.encode(“utf-8”))
number += 1
if not from_server_msg:
break
client.close()