我正在使用RakNet库,这是我第一次尝试与网络做任何事情。 我已初始化所有内容并已连接,但现在是什么?
每当玩家按下服务器键,然后从服务器按键到其他玩家时,我是否应该发送具有新位置的数据包?
这就是我现在所拥有的:(我认为这里的一切都很重要,所以我认为没有办法为你缩短代码)
#include "Main.h"
void Init();
void Logic();
void Render();
void Clear();
AllegroWrapper al;
RakNet::RakPeerInterface *peer = 0;
RakNet::Packet *packet = 0;
char str[512];
bool isServer;
const int maxPlayers = 2;
const int serverPort = 60000;
Bitmap *bmpPlayer = 0;
int playerID = 0;
bool readyToPlay = false;
class Player
{
public:
int x;
int y;
bool alive;
Player()
{
x = 100;
y = 100;
alive = false;
}
};
Player player[2];
int main()
{
Init();
while( al.mainLoop )
{
Logic();
if(al.doRender())
Render();
}
Clear();
return 0;
}
void Init()
{
al.Init();
peer = RakNet::RakPeerInterface::GetInstance();
cout<<"Are we (0)Server, or (1)Client?\n";
int buf;
cin>>buf;
if( buf == 0 )
{
RakNet::SocketDescriptor sd(serverPort, 0);
peer->Startup(maxPlayers, &sd, 1);
isServer = true;
cout<<"\nStarting a server...\n";
peer->SetMaximumIncomingConnections(maxPlayers);
}
else
{
RakNet::SocketDescriptor sd;
peer->Startup(1, &sd, 1);
isServer = false;
cout<<"\nStarting a client...\n";
peer->Connect("127.0.0.1", serverPort, 0, 0);
}
bmpPlayer = al_load_bitmap("player.png");
}
void Logic()
{
al.Logic();
/*if(al.ev.type == ALLEGRO_EVENT_KEY_DOWN)
al.mainLoop = false;*/
for(packet = peer->Receive(); packet; peer->DeallocatePacket(packet), packet = peer->Receive())
{
switch(packet->data[0])
{
case ID_NEW_INCOMING_CONNECTION:
{
cout<<"A connection is incoming.\n";
} break;
case ID_NO_FREE_INCOMING_CONNECTIONS:
{
cout<<"The server is full.\n";
} break;
case ID_REMOTE_NEW_INCOMING_CONNECTION:
{
cout<<"Another client has connected.\n";
} break;
case ID_CONNECTION_REQUEST_ACCEPTED:
{
cout<<"Our connection request has been accepted.\n";
player[playerID].alive = true;
readyToPlay = true;
} break;
case ID_CONNECTION_LOST:
{
if (isServer)
{
cout<<"A client lost the connection.\n";
}else
{
cout<<"Connection lost.\n";
}
} break;
case ID_REMOTE_CONNECTION_LOST:
{
cout<<"Another client has lost the connection.\n";
} break;
case ID_DISCONNECTION_NOTIFICATION:
{
if (isServer)
{
cout<<"A client has disconnected.\n";
}else
{
cout<<"We have been disconnected.\n";
}
} break;
case ID_REMOTE_DISCONNECTION_NOTIFICATION:
{
cout<<"Another client has disconnected.\n";
} break;
default:
{
cout<<"Message with identifier " << packet->data[0] << " has arrived.\n";
} break;
}
}
if( isServer == false && readyToPlay == true )
{
if(al.ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(al.ev.keyboard.keycode)
{
case ALLEGRO_KEY_D:
{
player[playerID].x += 5;
}
break;
}
}
}
}
void Render()
{
al.ClearToColor(al.SetRGB(0,0,200));
//if( isServer == false )
{
for(int i = 0 ; i < 2 ; i ++)
{
if( player[i].alive == true )
{
al_draw_bitmap(bmpPlayer, player[i].x, player[i].y, 0);
}
}
}
al.FlipDisplay();
}
void Clear()
{
al.Clear();
RakNet::RakPeerInterface::DestroyInstance(peer);
}