Main loop: Switch to infinite ticking paradigm; agents connect on the fly, cannot reconnect yet

This commit is contained in:
Petr Baudis 2011-11-26 23:50:07 +01:00
parent 978a080656
commit 1d15adac48

35
main.cc
View file

@ -3,6 +3,7 @@
#include <iostream> #include <iostream>
#include <cstring> #include <cstring>
#include <fcntl.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <signal.h> #include <signal.h>
#include <sys/types.h> #include <sys/types.h>
@ -23,7 +24,6 @@ main(int argc, char *argv[])
srandom(time(NULL)); srandom(time(NULL));
signal(SIGPIPE, SIG_IGN);
int lfd = socket(AF_INET, SOCK_STREAM, 0); int lfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sin; struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin)); memset(&sin, 0, sizeof(sin));
@ -35,22 +35,29 @@ main(int argc, char *argv[])
bind(lfd, (struct sockaddr *) &sin, sizeof(sin)); bind(lfd, (struct sockaddr *) &sin, sizeof(sin));
listen(lfd, 10); listen(lfd, 10);
int cfd; signal(SIGPIPE, SIG_IGN);
while ((cfd = accept(lfd, NULL, NULL)) >= 0) { int flags = fcntl(lfd, F_GETFL, 0);
class connection conn(cfd); fcntl(lfd, F_SETFL, flags | O_NONBLOCK);
class tile &agentpos = map.tile_at(random() % map.w, random() % map.h);
class agent agent(0, agentpos, conn);
while (true) { class agent *agent = NULL;
std::cout << "tick " << tick_id << '\n'; while (true) {
map.print_map(); std::cout << "tick " << tick_id << '\n';
std::cout << '\n'; map.print_map();
std::cout << '\n';
agent.on_tick(); if (agent) {
agent->on_tick();
usleep(1000000); } else {
tick_id++; int cfd = accept(lfd, NULL, NULL);
if (cfd >= 0) {
class connection *conn = new class connection(cfd);
class tile &agentpos = map.tile_at(random() % map.w, random() % map.h);
agent = new class agent(0, agentpos, *conn);
}
} }
usleep(1000000);
tick_id++;
} }
return 0; return 0;