////////////////////////////////////////////////////////////////////////////
// simple lite-C online game
////////////////////////////////////////////////////////////////////////////
#include <acknex.h>
#include <default.c>
function on_client_event() // terminate client when server disconnects
{
if (event_type == EVENT_LEAVE) sys_exit("Disconnected!");
}
function player_remove() // remove player when client disconnects
{
if (event_type == EVENT_DISCONNECT) ent_remove(me);
}
action player_move() // control the player on its client, move it on the server, animate it on all clients
{
my.event = player_remove;
my.emask |= ENABLE_DISCONNECT;
my.smask |= NOSEND_FRAME;
var walk_percentage = 0;
VECTOR my_last_pos;
while (1)
{
if (my.client_id == dplay_id) // player created by this client?
{
if (key_a-key_d) {
my.pan += (key_a-key_d)*5*time_step; // rotate the entity directly on its client
send_skill(my.pan,SEND_UNRELIABLE|SEND_RATE);
}
if (connection == CONNECT_CLIENT)
my.smask |= NOSEND_ANGLES;
if (key_w-key_s != my.skill1) { // if the key state changed
my.skill1 = key_w-key_s; // forward/backward
send_skill(my.skill1,0); // send skill1 to the server
}
}
if (connection & CONNECT_SERVER) // the following line runs on the server only
c_move(me,vector(my.skill1*5*time_step,0,0), NULL, GLIDE); // move the entity using its skill1
walk_percentage += vec_dist(my.x,my_last_pos); // calculate the distance for animation
vec_set(my_last_pos,my.x);
ent_animate(my, "walk", walk_percentage, ANM_CYCLE); // animate the entity
wait (1);
}
}
function main()
{
if (!connection) { // not started with -cl / -sv -cl?
if (!session_connect(app_name,"")) // no client found on the localhost?
session_open(app_name); // start as server
}
do { wait(1); }
while (dplay_status < 2); // wait until the session is opened or joined
dplay_entrate = 1;
dplay_localfunction = 2;
level_load ("multiplayer6.wmb");
vec_set(camera.x, vector (-600, 0, 100)); // set a proper camera position
if (connection & CONNECT_SERVER) { // this instance of the game runs on the server
video_window(0,0,0,"Server");
ent_create ("redguard.mdl",vector(100,50,40),player_move); // then create the red guard!
} else { // otherwise, it runs on a connected client
video_window(0,0,0,player_name);
random_seed(0); // allow random player positions
ent_create ("blueguard.mdl",vector(-100+random(200),-50+random(100),40),player_move); // create the blue guard
}
}