示例#1
0
static DSK_CMDLINE_CALLBACK_DECLARE(handle_make_maze)
{
  unsigned width, height;
  unsigned y;
  Game *game;
  DSK_UNUSED (arg_name); DSK_UNUSED (callback_data);
  if (arg_value == NULL)
    width = height = 10;
  else
    {
      if (sscanf (arg_value, "%ux%u", &width, &height) != 2)
        {
          dsk_set_error (error, "error parsing WIDTHxHEIGHT for --make-maze");
          return DSK_FALSE;
        }
    }


  game = create_game ("name doesn't matter", width, height);
  for (y = 0; y < height; y++)
    {
      render_hwall_line_ascii (width, game->h_walls + width * y);
      render_vwall_line_ascii (width, game->v_walls + width * y);
    }
  render_hwall_line_ascii (width, game->h_walls);
  exit (0);
  return DSK_TRUE;
}
示例#2
0
void
ejoy2d_win_init(int orix, int oriy, int width, int height, float scale, const char* folder) {
	G = create_game();
	lua_State *L = ejoy2d_game_lua(G->game);
	lua_pushcfunction(L, traceback);
	int tb = lua_gettop(L);
	int err = luaL_loadstring(L, startscript);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

  lua_pushstring(L, folder);
  lua_pushstring(L, "examples/ex03.lua");

	err = lua_pcall(L, 2, 0, tb);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

	lua_pop(L,1);

	screen_init(width,height,scale);
	ejoy2d_game_start(G->game);
}
示例#3
0
文件: winfw.c 项目: ywxzm/ejoy2d
void
ejoy2d_win_init(int argc, char *argv[]) {
	G = create_game();
	screen_init(WIDTH,HEIGHT,1.0f);
	lua_State *L = ejoy2d_game_lua(G->game);
	lua_pushcfunction(L, traceback);
	int tb = lua_gettop(L);
	int err = luaL_loadstring(L, startscript);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

	char modname[1024];

	int sz = GetModuleFileNameA(0,  modname, 1024);

	lua_pushlstring(L, modname, sz);

	int i;
	for (i=1;i<argc;i++) {
		lua_pushstring(L, argv[i]);
	}

	err = lua_pcall(L, argc, 0, tb);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

	lua_pop(L,1);

	ejoy2d_game_start(G->game);
}
示例#4
0
文件: winfw.c 项目: Coolxiaoo/ejoy2d
void
ejoy2d_win_init(int argc, char *argv[]) {
	G = create_game();
	lua_State *L = ejoy2d_game_lua(G->game);
	lua_pushcfunction(L, traceback);
	int tb = lua_gettop(L);
	int err = luaL_loadstring(L, startscript);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}
  
  lua_pushstring(L, "./");
  lua_pushstring(L, "examples/ex03.lua");
  
	err = lua_pcall(L, 2, 0, tb);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

	lua_pop(L,1);

	screen_init(WIDTH,HEIGHT,1.0f);
	ejoy2d_game_start(G->game);
}
示例#5
0
void
engine2d_win_init(struct STARTUP_INFO* startup) {
    STARTUP = startup;
    G = create_game();
    
    screen_init(startup->width, startup->height, startup->scale);

    
    lua_State *L = engine2d_game_lua(G->game);
    
    lua_pushcfunction(L, traceback);
    
    int tb = lua_gettop(L);
    int err = luaL_loadstring(L, startscript);
    if (err) {
        const char *msg = lua_tostring(L,-1);
        fault("%s", msg);
    }
    
    lua_pushstring(L, startup->folder);
    lua_pushstring(L, startup->script);
    push_startup_info(L, startup);
    err = lua_pcall(L, 3, 0, tb);
    if (err) {
        const char *msg = lua_tostring(L,-1);
        fault("%s", msg);
    }
    
    lua_pop(L,1);
    

    engine2d_game_logicframe(LOGIC_FRAME);

    engine2d_game_start(G->game);
}
示例#6
0
int main(int argc, char **argv)
{
  int sockfd, newfd;
  struct sockaddr_in sin, cli;
  int clilen;
  fd_set allfds, fds;                        /* ビットマスク */
  int fd, fd_min, fd_max;

  create_game(&g);

  if ( (sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ) /* ソケット */
    error("cannot create socket");
  bzero((char *)&sin, sizeof(sin));          /* sin に 0 をつめる */
  sin.sin_family = PF_INET;                  /* Internet ドメイン */
  sin.sin_addr.s_addr = htonl(INADDR_ANY);   /* アドレスは何でもOK */
  sin.sin_port = htons(SERVER_PORT);         /* ポートは SERVER_PORT */
  if ( bind(sockfd, (struct sockaddr *)&sin, sizeof(sin)) < 0 )
    error("cannot bind");
  if ( listen(sockfd, 5) < 0 )
    error("cannot listen");
  FD_ZERO(&allfds);                          /* すべてゼロにクリア */
  FD_SET(sockfd, &allfds);                   /* sockfdのところに1を立てる */
  fd_min = sockfd; fd_max = sockfd;
  search_min_max(allfds, &fd_min, &fd_max);
  printf("min %d max %d\n", fd_min, fd_max);
  while ( 1 ) {
    fds = allfds;                            /* fdsはselectにより変化するかも */
    if ( select(FD_SETSIZE, &fds, NULL, NULL, NULL) < 0 )
      error("cannot select");
    for ( fd = 0; fd < FD_SETSIZE; fd++ )    /* ファイル記述子を順に調査 */
      if ( FD_ISSET(fd, &fds) ) {            /* ビットが立っていた */
        update_min_max(fd, &fd_min, &fd_max);
        if ( fd == sockfd ) {                /* 入力受付用ファイル記述子の場合 */
          clilen = sizeof(cli);              /* 接続を受け入れる準備 */
          if ( (newfd = accept(sockfd, (struct sockaddr *)&cli, &clilen)) < 0 )
            error("cannot accept");
          if (battle[0] == 0 ){
            battle[0] = newfd;
            write(newfd, "0", 6);
          } else if(battle[0] != 0) {
            battle[1] = newfd;
            write(newfd, "1", 6);
          } else if (battle[1] != 0) {
          }
          update_min_max(newfd, &fd_min, &fd_max);
          printf("Accetpted new connection: fd = %d\n", newfd);
          FD_SET(newfd, &allfds);            /* selectによる調査対象に加える */
        } else if ( service(fd, &g) == 0 ) {     /* クライアントからの要求処理 */
          printf("Closed connection: fd = %d\n", fd);
          if ( shutdown(fd, SHUT_RDWR) < 0 ) /* これ以上の送受信を禁止 */
            error("cannot shutdown");
          FD_CLR(fd, &allfds);               /* selectによる調査対象から外す */
          close(fd);
          search_min_max(allfds, &fd_min, &fd_max);
        }
      }
  }
  return 0;
}
JNIEXPORT void JNICALL Java_com_intel_deferredgles_JNIWrapper_init(JNIEnv * env, jobject obj, int width, int height)
{
    _game = create_game();

    UNUSED_PARAMETER(env);
    UNUSED_PARAMETER(obj);
    UNUSED_PARAMETER(width);
    UNUSED_PARAMETER(height);
}
示例#8
0
文件: game.c 项目: chypriote/allum1
void	game(t_opt *options)
{
  int	*game;

  game = xmalloc(options->nblines);
  game = create_game(options);
  aff_game(game, options);
  start_playing(game, options);
  credits(options);
}
int main(int argc, char **argv) {
    Game *game = create_game(argc, argv);
    {
        ShellWin32 shell(*game);
        shell.run();
    }
    delete game;

    return 0;
}
示例#10
0
文件: main.c 项目: Gwagwa7/Arkanoid
int			main(int ac, char **av)
{
	t_game	*game;

	(void)ac;
	game = uf_get_game();
	create_game(game, av[1]);
	app(game);
	terminate_glfw(game);
	return (0);
}
void android_main(android_app *app) {
    Game *game = create_game(ShellAndroid::get_args(*app));

    try {
        ShellAndroid shell(*app, *game);
        shell.run();
    } catch (const std::runtime_error &e) {
        __android_log_print(ANDROID_LOG_ERROR, game->settings().name.c_str(), "%s", e.what());
    }

    delete game;
}
示例#12
0
Code game(SDL_Renderer *renderer, CommandTable *table) {
  char name[MAXIMUM_PLAYER_NAME_SIZE];
  Player player;
  Game game;
  Code code;
  code = read_player_name(name, MAXIMUM_PLAYER_NAME_SIZE, renderer);
  if (code == CODE_QUIT || code == CODE_CLOSE) {
    return code;
  }
  player = create_player(name, table);
  game = create_game(&player);
  code = run_game(&game, renderer);
  destroy_game(&game);
  return code;
}
示例#13
0
static void
handle_create_new_game (DskHttpServerRequest *request)
{
  DskCgiVariable *game_var = dsk_http_server_request_lookup_cgi (request, "game");
  DskCgiVariable *user_var = dsk_http_server_request_lookup_cgi (request, "user");
  char buf[512];
  Game *game;
  User *user;
  DskJsonValue *state_json;
  unsigned width, height;
  if (game_var == NULL)
    {
      dsk_http_server_request_respond_error (request, DSK_HTTP_STATUS_BAD_REQUEST, "missing game=");
      return;
    }
  if (user_var == NULL)
    {
      dsk_http_server_request_respond_error (request, DSK_HTTP_STATUS_BAD_REQUEST, "missing user="******"game %s already exists", game_var->value);
      dsk_http_server_request_respond_error (request, DSK_HTTP_STATUS_BAD_REQUEST, buf);
      return;
    }
  user = find_user (user_var->value);
  if (user != NULL)
    {
      snprintf (buf, sizeof (buf), "user %s already found in %s", user->name, user->base.game->name);
      dsk_http_server_request_respond_error (request, DSK_HTTP_STATUS_BAD_REQUEST, buf);
      return;
    }

  game = create_game (game_var->value, DEFAULT_UNIVERSE_WIDTH, DEFAULT_UNIVERSE_HEIGHT);
  width = 700;
  height = 400;
  user = create_user (game, user_var->value, width, height);
  state_json = create_user_update (user);
  respond_take_json (request, state_json);
}
示例#14
0
文件: winfw.c 项目: lvshaco/ejoy2d
void
ejoy2d_win_init(int argc, char *argv[]) {
	G = create_game();
	lua_State *L = ejoy2d_game_lua(G->game);
    int top = lua_gettop(L);
    luaL_requiref(L, "socket.c", luaopen_socket_c, 0);
    luaL_requiref(L, "socketbuffer.c", luaopen_socketbuffer_c, 0);
    luaL_requiref(L, "audio.c", luaopen_audio_c, 0);
    luaL_requiref(L, "png", luaopen_png, 0);
    lua_settop(L, top);

    lua_pushcfunction(L, traceback);
	int tb = lua_gettop(L);

    char buf[BUFSIZE];
    const char *pathbuf = read_exepath(buf, BUFSIZE);
    if (pathbuf == NULL)
        fault("can't read exepath");

	int err = luaL_loadstring(L, startscript);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

    lua_pushstring(L, pathbuf);
	int i;
	for (i=1;i<argc;i++) {
		lua_pushstring(L, argv[i]);
	}
    screen_init(WIDTH,HEIGHT,1.0f);
	err = lua_pcall(L, argc, 0, tb);
	if (err) {
		const char *msg = lua_tostring(L,-1);
		fault("%s", msg);
	}

	lua_pop(L,1);	
	ejoy2d_game_start(G->game);
}
示例#15
0
/**
 * void process_dgram(char *dgram, struct sockaddr_in *addr)
 * 
 * Processes accepted datagram. Checks if sequential ID is correct, if it's lower,
 * we resend the ACK packet and dont bother with that datagram anymore, because
 * it was already processed before.
 */
void process_dgram(char *dgram, struct sockaddr_in *addr) {
    /* Protocol token */
    char *token;
    /* Token length */
    int token_len;
    /* Command */
    char *type;
    /* Generic char buffer */
    char *generic_chbuff;
    /* Sequential ID of received packet */
    int packet_seq_id;
    /* Client which we receive from */
    client_t *client;
    /* Generic unsigned int var */
    unsigned int generic_uint;
    /* String representation of address */
    char addr_str[INET_ADDRSTRLEN];

    inet_ntop(AF_INET, &addr->sin_addr, addr_str, INET_ADDRSTRLEN);
    
    /* Log */
    sprintf(log_buffer,
            "DATA_IN: %s <--- %s:%d",
            dgram,
	    addr_str,
	    htons(addr->sin_port)
            );
    log_line(log_buffer, LOG_DEBUG);
    
    token = strtok(dgram, ";");
    token_len = strlen(token);
    
    generic_chbuff = strtok(NULL, ";");
    packet_seq_id = (int) strtol(generic_chbuff, NULL, 0);
    
    /* Check if datagram belongs to us */
    if( (token_len == strlen(STRINGIFY(APP_TOKEN))) &&
            strncmp(token, STRINGIFY(APP_TOKEN), strlen(STRINGIFY(APP_TOKEN))) == 0 &&
            packet_seq_id > 0) {
        
        type = strtok(NULL, ";");
        
        /* New client connection */
        if(strncmp(type, "CONNECT", 7) == 0) {
            
            add_client(addr);            
            client = get_client_by_addr(addr);
            
            if(client) {
                send_ack(client, 1, 0);
                send_reconnect_code(client);
                
                /* Release client */
                release_client(client);
            }
            
        }
        /* Reconnect */
        else if(strncmp(type, "RECONNECT", 9) == 0) {            
            client = get_client_by_index(get_client_index_by_rcode(strtok(NULL, ";")));
            
            if(client) {
                /* Sends ACK aswell after resetting clients SEQ_ID */
                reconnect_client(client, addr);
                
                /* Release client */
                release_client(client);
            }
        }
        /* Client should already exist */
        else {
            client = get_client_by_addr(addr);
            
            if(client != NULL) {
                /* Check if expected seq ID matches */
                if(packet_seq_id == client->pkt_recv_seq_id) {
                    
                    /* Get command */
                    if(strncmp(type, "CREATE_GAME", 11) == 0) {
                                                
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        create_game(client);
                        
                    }
                    /* Receive ACK packet */
                    else if(strncmp(type, "ACK", 3) == 0) {
                        
                        recv_ack(client, 
                                (int) strtoul(strtok(NULL, ";"), NULL, 10));
                        
                        update_client_timestamp(client);
                        
                    }
                    /* Close client connection */
                    else if(strncmp(type, "CLOSE", 5) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        leave_game(client);
                        remove_client(&client);
                        
                    }
                    /* Keepalive loop */
                    else if(strncmp(type, "KEEPALIVE", 9) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                    }
                    /* Join existing game */
                    else if(strncmp(type, "JOIN_GAME", 9) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        join_game(client, strtok(NULL, ";"));
                        
                    }
                    /* Leave existing game */
                    else if(strncmp(type, "LEAVE_GAME", 10) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        leave_game(client);
                    }
                    /* Start game */
                    else if(strncmp(type, "START_GAME", 10) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        start_game(client);
                    }
                    /* Rolling die */
                    else if(strncmp(type, "DIE_ROLL", 8) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        roll_die(client);
                    }
                    /* Moving figure */
                    else if(strncmp(type, "FIGURE_MOVE", 11) == 0) {
                        
                        /* ACK client */
                        send_ack(client, packet_seq_id, 0);
                        
                        /* Parse figure id */
                        generic_chbuff = strtok(NULL, ";");
                        generic_uint = (unsigned int) strtoul(generic_chbuff, NULL, 10);

                        move_figure(client, generic_uint);
                    }

		   else if(strncmp(type, "MESSAGE", 7) == 0) {
			
			/* ACK client */
			send_ack(client, packet_seq_id, 0);
			
			broadcast_message(client, strtok(NULL, ";"));
		   }
                                        
                }
                /* Packet was already processed */
                else if(packet_seq_id < client->pkt_recv_seq_id &&
                        strncmp(type, "ACK", 3) != 0) {
                    
                    send_ack(client, packet_seq_id, 1);
                    
                }
                
                /* If client didnt close conection */
                if(client != NULL) {
                    
                    /* Release client */
                    release_client(client);
                }
            }
        }
    }
}
示例#16
0
文件: fiar.c 项目: ghuysmans/fiar
int main(int argc, char *argv[]) {
	Game *game = create_game(ROWS, COLS);
	if (argc==3 && !strcmp(argv[1], "display")) {
		char *p = argv[2];
		char *err;
		while (*p) {
			int col = *p - '0';
			if (col>=0 && col<COLS) {
				if (can_play(game, col)) {
					play(game, col);
					if (victory(game, col))
						printf("victory!\n");
				}
				else {
					err = "illegal move";
					goto err_handler;
				}
			}
			else {
				int i;
				err = "unknown move syntax";
err_handler:
				fprintf(stderr, "error: %s.\n%s\n", err, argv[2]);
				for (i=0; i<p-argv[2]; i++)
					fprintf(stderr, " ");
				fprintf(stderr, "^\n");
				return 2;
			}
			p++;
		}
		print_board(game);
	}
	else if ((argc==2 || argc==3) && !strcmp(argv[1], "play")) {
		int j;
		if (argc==3 && !strcmp(argv[2], "red"))
			goto red;
		while (1) {
			print_board(game);
			do {
				printf("Your move: ");
				if (scanf("%d", &j) != 1) {
					printf("\n");
					goto out;
				}
			} while (!can_play(game, j));
			play(game, j);
			if (victory(game, j)) {
				printf("You've won!\n");
				break;
			}
			else {
				int ret = negamax(game, DEFEAT, VICTORY, 12, &j);
red:
				if (ret == CUT)
					printf("I've got no idea what to do...\n"
						"I'm gonna try %d.\n", j);
				else
					printf("I'll play %d (score %d)\n", j, ret);
				play(game, j);
				if (victory(game, j)) {
					printf("You've lost!\n");
					break;
				}
			}
		}
		print_board(game);
	}
	else {
		fprintf(stderr, "usage:\t%s display moves\n", argv[0]);
		fprintf(stderr, "\t%s play [yellow|red]\n", argv[0]);
		fprintf(stderr, "try:\t%s display 01221\n", argv[0]);
		fprintf(stderr, "\t%s play\n", argv[0]);
		return 1;
	}
out:
	destroy_game(game);
	return 0;
}
示例#17
0
void show_menu()
{

    int licznik=0;
    int x,y;
    x=500;
    y=100;

    ALLEGRO_FONT * font_ttf    = al_load_ttf_font("cour.ttf",80, 0);
    ALLEGRO_FONT * font_ttfbolt   = al_load_ttf_font("courbd.ttf",80, 0);
    ALLEGRO_BITMAP  *bitmapa = al_load_bitmap( "media/menu.png" );

    bool done=false,draw=false;

    al_draw_bitmap (bitmapa, 0, 0, 0);
    al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");


    al_flip_display();

    ALLEGRO_EVENT_QUEUE *event_queue1 = al_create_event_queue();
    ALLEGRO_KEYBOARD_STATE keyState;

    //al_register_event_source(event_queue, al_get_mouse_event_source());
    al_register_event_source(event_queue1, al_get_display_event_source(display));
    al_register_event_source(event_queue1, al_get_keyboard_event_source());
    while(!done)
    {
        ALLEGRO_EVENT events;
        al_wait_for_event(event_queue1, &events);
        al_get_keyboard_state(&keyState);

        if(events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;

        }
        else if (al_key_down( &keyState, ALLEGRO_KEY_ESCAPE))
        {
            done=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_ENTER))
        {
            if(licznik==3)
            {
                done=true;
                draw=false;
            }
            else if(licznik==0)
            {

                roszada_w_long=true;
                roszada_w_short=true;
                roszada_b_long=true;
                roszada_b_short=true;
                czyjruch=0;
                create_game();
                show_game();
                break;
                done=true;
            }
            else if(licznik==1)
            {
                // create_game();
                load_game();
                show_game();
                done=true;
            }
            else
            {
                show_options();
                draw=true;
            }
        }
        else  if(al_key_down(&keyState, ALLEGRO_KEY_UP))
        {

            licznik--;
            if(licznik<0)licznik=3;
            draw=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_DOWN))
        {
            licznik++;
            if(licznik>3)licznik=0;

            draw=true;
        }
        if(draw)
        {
            draw=false;
            al_draw_bitmap (bitmapa, 0, 0, 0);
            if(licznik==0)
            {
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else if(licznik==1)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else if(licznik==2)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            al_flip_display();
        }
    }
    al_destroy_bitmap(bitmapa);
    al_destroy_event_queue(event_queue1);
    al_destroy_font(font_ttf);
    al_destroy_font(font_ttfbolt);

}
示例#18
0
int main(int argc, char** argv)
{
	//connect to server, given as the first argument
	string usage = string(argv[0]) + " <server> <port> [game #]";
	if(argc < 3) {
		cerr <<  usage << endl;
		return 0;
	}
	
	bool end_game = false;
	bool start_game = true;
	if(argc == 4) {
		// they specified a game number,
		// do something different?
		start_game = false;
		//cout << "Trying to joing game #" << argv[3] << endl;
	}
	
	// we got enough command-line arguments,
	// start tying to connect:
	int sock_server = open_server_connection(argv[1], argv[2]);
	if(sock_server == -1) {
		return 0;
	}

	// create an instance of the player's AI class
	myAI gameAI;
	
	string comm_buffer;
	sexp_t* sexp;

	// log into the server, using the AI's team name
	string whos_turn;
	my_user_id = login_to_server(sock_server, gameAI.PlayerName() );
	
	// setup the logging filename
	ostringstream stream;
    tm* myTime;
    time_t theTime = time(NULL);
    myTime = localtime(&theTime);
	stream << myTime->tm_hour << "." << myTime->tm_min;
	
    string name = string(argv[0]);
    for(int i=name.size()-1; i >=0; i--)
    {
        if(name[i] == ' ' || name[i] == '/' || name[i] == '\\' || name[i] == '.' || name[i] == ':')
        {
            name.erase(i,1);
        }
    }
    string log_filename = stream.str() + "-" + name + string(".gamelog");
	cout << "Filename: " << log_filename << endl;
	
	#ifdef DEBUG
	cout << "DEBUG: logged in as user #" << my_user_id << endl;
	#endif
	
	// okay, we've succesfully logged in,
	// now start or join a game

	if(start_game) {
		// create a new game:
		string game_number = create_game(sock_server);
		
		gameAI.playerNumber = 1;
		gameAI.myBase = coordinate(0,0);
		gameAI.enemyBase = coordinate(25,25);
		
	} else {
	
		gameAI.playerNumber = 2;
		gameAI.myBase = coordinate(0,0);
		gameAI.enemyBase = coordinate(25,25);
		
		// join an existing game
		cout << "Trying to join game " << argv[3] << "..." << endl;
		string join_string = "(join-game " + string(argv[3]) + ")";
		send_string(sock_server, join_string);
		sexp = rec_sexp(sock_server);
		if(!check_sexp(sexp, "join-accepted")) {
			cout << "Unabled to join game " << argv[3] << endl;
			goto GAME_SHUTDOWN;
		}

		// we should only try to start the game if we're the
		// player that just joined; otherwise, the server
		// will sorta freak out...
		send_string(sock_server, "(game-start)");
	}
	
	// the server is going to spit a ton of SEXP's at us;
	// wade through them until we get a "new-turn" msg.
	sexp = rec_sexp(sock_server);
	while(!check_sexp(sexp, "new-turn")) {
		// okay, what kind of data have we gotten from the server,
		// and what are we supposed to do about it?
		
		if(check_sexp(sexp, "game-start-accepted")) {
			// the server accepted our reqeust to begin the game;
			// we don't care, because earlier we just assumed
			// that it worked :|		
		}
		
		if(check_sexp(sexp, "unit-types")){
			// this should be sent only during this initialization:
			// it contains the details of each type of unit
			#ifdef DEBUG
			cout << "DEBUG: updating unit types" << endl;
			#endif
			update_unit_types((myAI*)&gameAI, sexp);
		}
		
		if(check_sexp(sexp, "status")) {
			// An actual game-status message: this might not
			// mean much right now, but try to parse it anyway.
			// Don't bail if it fails, but warn us.

			if(!game_status(gameAI, sexp, my_user_id)) {
				cout << "WARN: error parsing game status" << endl;
			}
		}
		
		// get another S-expression to test:
		sexp = rec_sexp(sock_server);
	}
	
	// okay, now sexp should contain a "new-turn" message
	// pull out who's turn it is, then start the main game loop
	whos_turn = string(sexp->list->next->val);
	
	#ifdef DEBUG
	cout << "DEBUG: got all our pregame stuff, starting main loop!" << endl;
	#endif
				
	while(!end_game) {
		// ask the server for an update:
		//send_string(sock_server, "(game-status)");
		//sexp = rec_sexp(sock_server);
		
		// we're not guaranteed to get a "status" message,
		// so handle anything unexpected before we get to
		// the main game loop
		while(!check_sexp(sexp, "status")) {

			#ifdef DEBUG
			cout << "DEBUG: waiting for game status, got \"" << sexp->list->val << "\" message" << endl;
			#endif

			if(check_sexp(sexp, "game-over")) {
				cout << "Game Over: ";
				string winner = string( sexp->list->next->val );
				if( winner == my_user_id )
					cout << "You Win!";
				else
					cout << "You Lose...";
				cout << endl;
				
				end_game = true;
				goto GAME_SHUTDOWN;
			}
			
			if(check_sexp(sexp, "new-turn")) {
				whos_turn = string(sexp->list->next->val);
				#ifdef DEBUG
				cout << "DEBUG: It's player " << whos_turn << "'s turn" << endl;
				#endif
			}
			
			sexp = rec_sexp(sock_server);	
		}
		
		if(!check_sexp(sexp, "status")) {
			cerr << "WARN: expected 'status', got '" << sexp->list->val << "'" << endl;
		}
		
		if(!game_status(gameAI, sexp, my_user_id)) {
			cerr << "WARN: couldn't parse game status!" << endl;
		}
		
		// update the turn number
		gameAI.turnNumber = atoi( sexp->list->next->list->val);
		
		if(whos_turn == my_user_id) {
		
			//cout << endl << "Starting my turn... ";
		
			// 4a. Run their custom 'Play()' function
			gameAI.Play();
			
			// 4b. Send their orders to the server
			while( gameAI.orders.size() != 0){
			
				string myOrder = gameAI.orders.front().s_expression;
				gameAI.orders.pop();
				
				// send this command to the server
				send_string(sock_server, myOrder);
				// there's no need to listen for an incoming message;
				// we assume errors will be handled at the beginning
				// of the next loop.
			}

			// let the server know we've finished out turn
			send_string(sock_server, "(end-turn)");
			//cout << "done with my turn" << endl;

		} else {
			// it's not your turn, so take it easy for a second
			//cout << "Not my turn, waiting...." << endl;
			#ifndef WIN32 // the usleep function insn't avaible in Windows
			//usleep(100000); // this helps prevent climbing to 100% CPU usage
			#endif
		}
		
		// get another sexp to jump-start the next iteration of the loop
		sexp = rec_sexp(sock_server);
		
	}
     
	GAME_SHUTDOWN:   
	cout << "Shutting down..." << endl;
	send_string(sock_server, "(leave-game)");
	sexp = rec_sexp(sock_server);
	send_string(sock_server, "(logout)");
	sexp = rec_sexp(sock_server);	
   
	//End of game
	#ifdef WIN32
	closesocket(sock_server);
	#else
	close(sock_server);
	#endif
   
   log_file.open(log_filename.c_str());
   if(log_file.fail())
   {
      cout << "Error writing to log file" << endl;
   }
   else
   {
      log_file << log_stream.str();
      log_file.close();
   }
   
	return 0;
}
示例#19
0
文件: server_hangman.c 项目: Haini/OS
/**
 * @brief Program entry point.
 * @param argc The argument count
 * @param argv The argument vector
 * @return EXIT_SUCCESS, EXIT_PARITY_ERROR, EXIT_MULTIPLE_ERRORS
**/
int main(int argc, char *argv[])  
{
    uint8_t client_count = 0;
    int shmfd;
    
    
    /* setup signal handlers */
    const int signals[] = {SIGINT, SIGTERM};
    struct sigaction s;

    s.sa_handler = signal_handler;
    s.sa_flags   = 0;
    if(sigfillset(&s.sa_mask) < 0) {
        bail_out(EXIT_FAILURE, "sigfillset");
    }
    for(int i = 0; i < COUNT_OF(signals); i++) {
        if (sigaction(signals[i], &s, NULL) < 0) {
            bail_out(EXIT_FAILURE, "sigaction");
        }
    }
    
    /* Handle arguments */
    if (argc > 0) {
       progname = argv[0]; 
    }
    
    if (argc > 2) {
        fprintf(stderr, "USAGE: %s [input_file]", progname);
        exit(EXIT_FAILURE);
    }

    switch (argc) {
    /* Handle dict input from stdin */
    case 1: 
        printf("Please input your dictionary: \n");
        in_stream = stdin;
        read_dict();
    break;
    /* Handle dict input from file */
    case 2: 
		if ((in_stream = fopen(argv[1], "r")) == NULL)
		{
            bail_out(EXIT_FAILURE, "Invalid File");
		}
        read_dict();
    break;
    default:
        fprintf(stderr, "USAGE: %s [input_file]", progname);
        exit(EXIT_FAILURE);
        break; 
    }

    /* Create a new Shared Memory Segment (shm_open) */
    shmfd = shm_open(SHM_NAME, O_RDWR | O_CREAT | O_EXCL, PERMISSION);

    if (shmfd == (-1)) {
        bail_out(EXIT_FAILURE, "shm_open failed");
    }
    
    /*  Truncate a file to a specified length 
        extend (set size) */ 
    if (ftruncate(shmfd, sizeof *shared) == -1) {
        (void) close(shmfd);
        bail_out(EXIT_FAILURE, "ftruncate failed");
    }

    /* Map shared memory object */
    shared = mmap(NULL, sizeof *shared,
                    PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);

    if (shared == MAP_FAILED) {
        (void) close(shmfd);
        bail_out(EXIT_FAILURE, "MMAP failed");
    }

    if (close(shmfd) == -1) {
        bail_out(EXIT_FAILURE, "close(shmfd) failed");
    }
    
    shared->sc_terminate = -1;

    /* Create new named semaphores */
    s_server = sem_open(S_SERVER, O_CREAT | O_EXCL, PERMISSION, 0);
    s_client = sem_open(S_CLIENT, O_CREAT | O_EXCL, PERMISSION, 1);
    s_return = sem_open(S_RETURN, O_CREAT | O_EXCL, PERMISSION, 0);
    
    if(s_server == SEM_FAILED || 
        s_client == SEM_FAILED || 
        s_return == SEM_FAILED) {
        bail_out(EXIT_FAILURE, "sem_open(3) failed"); 
    }

    sem_set = 1;

    struct ClientList *el_pre = NULL;
    struct ClientList *el_cur = NULL;
    
    /* Keep server open until it gets killed. */
    while (!want_quit) {
        /* Critical section entry. */
        /* Wait until server is allowed to access SHM. */
        if (sem_wait(s_server) == -1) {
            if(errno == EINTR) continue;
            bail_out(EXIT_FAILURE, "sem_wait(3) failed");
        }
        
        /* Setup data for existing client. */
        if (shared->s_id >= 0) {
            el_cur = client_list;
            while (el_cur != NULL && el_cur->server_id != shared->s_id) {
                printf("elpre\n");
                el_pre = el_cur;
                printf("elcur\n");
                el_cur = el_cur->next;
            }

            if (el_cur == NULL) {
                bail_out(EXIT_FAILURE, "Client does not exist");
            }

            el_cur->guess = shared->c_guess;
        }
        
        /* Setup new client to list. */
        if (shared->s_id == -1) {
            /* Allocate element and set to zero. */
            el_cur = 
                 (struct ClientList *) calloc (1, sizeof(struct ClientList)); 
            if (el_cur == NULL) {
                bail_out(EXIT_FAILURE, "calloc(3) failed");
            }

            /* Assign unique ID based on client count. */
            el_cur->server_id = client_count++;
            el_cur->game_count = 0;
            
            /* Add the current element to our list. */
            el_cur->next = client_list;
            client_list = el_cur;
        }
        
        /* Check if client has terminated. */
        if (shared->sc_terminate >= 1) {
            DEBUG("Terminating client...\n");
            /* Remove client from list. */
            if (client_list == el_cur) {
                client_list = el_cur->next;
            } else {
                el_pre->next = el_cur->next;
            }

            free(el_cur);
            /* Free allocated resources. */
            /* Reset sc_terminate. */
            shared->sc_terminate = -1;
            if (sem_post(s_client) == -1) {
                bail_out(EXIT_FAILURE, "sem_post(3) failed");
            }
            /* Skip the rest of the game as we have nothing to do here */
            continue;
        }

        /* Check game status of client. */
        if (shared->status_id == CreateGame) {
            /* Start a new game. */
            DEBUG("Setting up game for client %d\n", shared->s_id);
            create_game(el_cur);
            
        }

        if (shared->status_id == Running) {
            /* Check guess. */
            DEBUG("Checking guess of client %d\n", shared->s_id);
            check_guess(el_cur);
        }
        
        /* Write server answer back into SHM. */
        shared->s_id = el_cur->server_id;
        shared->status_id = el_cur->status_id;
        shared->s_errors = el_cur->errors;
        strncpy(shared->s_word, el_cur->client_word, MAX_DATA);
        
        /* Let the client know that there is an answer. */
		if (sem_post(s_return) == -1) { 
            bail_out(EXIT_FAILURE, "sem_post(3) failed");
        }

        /* critical section end. */

    }
    /* Free stuff */
    free(strings);
}
示例#20
0
void MessageWriter::send_create_game(size_t map_id, const std::string &game_name, int players_size) {
  char message_type = NEW_GAME;
  socket_->send_buffer(&message_type, 1);
  CreateGameMessage create_game(socket_);
  create_game.send(map_id, game_name, players_size);
}
示例#21
0
// Show and loop main menu
void show_menu_loop() {
    char *ip = "";
    FILE *han;
    SDL_Event event;
    int createserver = 0;
    SDL_Thread *ReadThread;
    //GConfClient *gcc = NULL;

    // Init GConf
    //g_type_init();
    //gcc = gconf_client_get_default();
    //createserver = gconf_client_get_bool(gcc, BATTLEGWELED_CREATESERVER, NULL);
    //ip = gconf_client_get_string(gcc, BATTLEGWELED_SERVERIP, NULL);

    // Single player
    if (!createserver && !strcmp(ip, "")) {
	han = fopen("/tmp/.battlegweled-save", "rb");
	if (han) {
		fread(&total_score, sizeof(int), 1, han);
		fread(&single_timer, sizeof(int), 1, han);
		fread(&timer_delay, sizeof(int), 1, han);
		fread(&score, sizeof(int), 1, han);
       		fread(nb_of_tiles, sizeof(nb_of_tiles), 1, han);
       		fread(matrix, BOARD_WIDTH * BOARD_HEIGHT, sizeof(int), han);
       		fclose(han);
       		new_game(true, GM_SINGLE, true);
    	} else new_game(true, GM_SINGLE, false); 
       	if (game_loop()) {
		flush_callback(0);
		quit_callback(0);
	} else exit_callback(0);
    } else {
	    int joined;
	    if (createserver) create_game();
	    else joined = join_game(ip);

            while (1) {

	        // If connected then start the game
	        if (ss == SS_CONNECTED) {
	            new_game(true, GM_MULTIPLAYER, false);
	            ReadThread = SDL_CreateThread(multi_player_loop, "ReadThread", NULL);
	            game_loop();
	            //SDL_KillThread(ReadThread);
                    SDL_WaitThread(ReadThread, NULL);
		    break;
                }

		if (ss == SS_ERROR || (SDL_PollEvent(&event) && ((event.key.state == SDL_PRESSED && (event.key.keysym.sym == SDLK_ESCAPE
			|| event.key.keysym.sym == SDLK_F4 || event.key.keysym.sym == SDLK_F5 || event.key.keysym.sym == SDLK_F6))
			|| event.type == SDL_QUIT || (event.type == SDL_MOUSEBUTTONDOWN && event.button.x >= BACK_OFFSETX
			&& event.button.y >= BACK_OFFSETY && event.button.x < BACK_OFFSETX2 && event.button.y < BACK_OFFSETY2)))) {
                        SDL_WaitThread(ThreadConnect, NULL);
                        SDL_WaitThread(ThreadAccept, NULL);
			//if (ThreadConnect) SDL_KillThread(ThreadConnect);
                        //if (ThreadAccept) SDL_KillThread(ThreadAccept);
			break;
                }

		// Update screen
        	draw_waiting_screen();
        }
	quit_callback(0);
    }
}
示例#22
0
int main(int argc, char* argv[])
{
	struct game *game = create_game();

	apply_sc(0, &zero_value, game); switch_turn(game);

	apply_sc(100, &help_value, game); switch_turn(game);
	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game); switch_turn(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);

	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game); switch_turn(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game);  switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game); // 8192

	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game); switch_turn(game);

	print_game(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);

	apply_sc(100, &attack_value, game); switch_turn(game);
	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game); switch_turn(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);

	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game); switch_turn(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game);  switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game); // 16384

	apply_cs(&K_value, 100, game); switch_turn(game);
	apply_cs(&S_value, 100, game); switch_turn(game);
	apply_sc(100, &get_value, game); switch_turn(game);
	apply_sc(100, &zero_value, game);

	print_game(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&copy_value, 0, game); switch_turn(game);

	print_game(game);

	apply_cs(&put_value, 0, game); switch_turn(game);
	apply_sc(0, &zero_value, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&dbl_value, 0, game); switch_turn(game);
	apply_cs(&succ_value, 0, game); switch_turn(game);
	apply_cs(&revive_value, 0, game); switch_turn(game);

	print_game(game);

	destroy_game(game);

	return 0;
}
示例#23
0
/* true return value indicates that connection must be closed */
int process_msg(int fd, char* msg)
{
    int client_proto_major;
    int client_proto_minor;
    char * args;
    char * ptr, * ptr2;
    char * msg_orig;

    /* check for leading protocol tag */
    if (!str_begins_static_str(msg, "FB/")
            || strlen(msg) < 8) {  // 8 stands for "FB/M.m f"(oo)
        send_line_log(fd, fl_line_unrecognized, msg);
        return 1;
    }

    /* check if client protocol is compatible; for simplicity, we don't support client protocol more recent
     * than server protocol, we suppose that our servers are upgraded when a new release appears (but of
     * course client protocol older is supported within the major protocol) */
    client_proto_major = charstar_to_int(msg + 3);
    client_proto_minor = charstar_to_int(msg + 5);
    if (client_proto_major != proto_major
            || client_proto_minor > proto_minor) {
        send_line_log(fd, fl_proto_mismatch, msg);
        return 1;
    }

    if (remote_proto_minor[fd] == -1)
        remote_proto_minor[fd] = client_proto_minor;

    msg_orig = strdup(msg);

    /* after protocol, first word is command, then possible args */
    current_command = msg + 7; // 7 stands for "FB/M.m "
    if ((ptr = strchr(current_command, ' '))) {
        *ptr = '\0';
        args = current_command + strlen(current_command) + 1;
    } else
        args = NULL;

    if (streq(current_command, "PING")) {
        send_line_log(fd, ok_pong, msg_orig);
    } else if (streq(current_command, "NICK")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            if ((ptr = strchr(args, ' ')))
                *ptr = '\0';
            if (strlen(args) > 10)
                args[10] = '\0';
            if (!is_nick_ok(args)) {
                send_line_log(fd, wn_nick_invalid, msg_orig);
            } else {
                if (nick[fd] != NULL) {
                    free(nick[fd]);
                }
                nick[fd] = strdup(args);
                calculate_list_games();
                send_ok(fd, msg_orig);
            }
        }
    } else if (streq(current_command, "GEOLOC")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            if ((ptr = strchr(args, ' ')))
                *ptr = '\0';
            if (strlen(args) > 13)  // sign, 4 digits, dot, colon, sign, 4 digits, dot
                args[13] = '\0';
            if (geoloc[fd] != NULL) {
                free(geoloc[fd]);
            }
            geoloc[fd] = strdup(args);
            calculate_list_games();
            send_ok(fd, msg_orig);
        }
    } else if (streq(current_command, "CREATE")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            if ((ptr = strchr(args, ' ')))
                *ptr = '\0';
            if (strlen(args) > 10)
                args[10] = '\0';
            if (!is_nick_ok(args)) {
                send_line_log(fd, wn_nick_invalid, msg_orig);
            } else if (!nick_available(args)) {
                send_line_log(fd, wn_nick_in_use, msg_orig);
            } else if (already_in_game(fd)) {
                send_line_log(fd, wn_already_in_game, msg_orig);
            } else if (games_open == 16) {  // FB client can display 16 max
                send_line_log(fd, wn_max_open_games, msg_orig);
            } else {
                create_game(fd, strdup(args));
                send_ok(fd, msg_orig);
            }
        }
    } else if (streq(current_command, "JOIN")) {
        if (!args || !(ptr = strchr(args, ' '))) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            struct game * g;
            char* nick = ptr + 1;
            *ptr = '\0';
            if ((ptr2 = strchr(ptr, ' ')))
                *ptr2 = '\0';
            if (strlen(nick) > 10)
                nick[10] = '\0';
            if (!is_nick_ok(nick)) {
                send_line_log(fd, wn_nick_invalid, msg_orig);
            } else if (!nick_available(nick)) {
                send_line_log(fd, wn_nick_in_use, msg_orig);
            } else if (already_in_game(fd)) {
                send_line_log(fd, wn_already_in_game, msg_orig);
            } else if (!(g = find_game_by_nick(args))) {
                send_line_log(fd, wn_no_such_game, msg_orig);
            } else {
                if (add_player(g, fd, strdup(nick)))
                    send_ok(fd, msg_orig);
                else
                    send_line_log(fd, wn_game_full, msg_orig);
            }
        }
    } else if (streq(current_command, "KICK")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            if ((ptr = strchr(args, ' ')))
                *ptr = '\0';
            if (strlen(args) > 10)
                args[10] = '\0';
            if (!already_in_game(fd)) {
                send_line_log(fd, wn_not_in_game, msg_orig);
            } else {
                struct game * g = find_game_by_fd(fd);
                if (g->players_conn[0] != fd) {
                    send_line_log(fd, wn_not_creator, msg_orig);
                } else {
                    kick_player(fd, g, args);
                }
            }
        }
    } else if (streq(current_command, "PART")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            player_part_game(fd);
            send_ok(fd, msg_orig);
        }
    } else if (streq(current_command, "LIST")) {
        send_line_log(fd, list_games_str, msg_orig);
    } else if (streq(current_command, "STATUS")) {  // 1.0 command
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            status(fd, msg_orig);
        }
    } else if (streq(current_command, "STATUSGEO")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            status_geo(fd, msg_orig);
        }
    } else if (streq(current_command, "PROTOCOL_LEVEL")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            protocol_level(fd, msg_orig);
        }
    } else if (streq(current_command, "TALK")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else {
            talk(fd, args);
        }
    } else if (streq(current_command, "START")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            start_game(fd);
        }
    } else if (streq(current_command, "CLOSE")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            close_game(fd);
        }
    } else if (streq(current_command, "SETOPTIONS")) {
        if (!args) {
            send_line_log(fd, wn_missing_arguments, msg_orig);
        } else if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            setoptions(fd, args);
        }
    } else if (streq(current_command, "LEADER_CHECK_GAME_START")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            leader_check_game_start(fd);
        }
    } else if (streq(current_command, "OK_GAME_START")) {
        if (!already_in_game(fd)) {
            send_line_log(fd, wn_not_in_game, msg_orig);
        } else {
            ok_start_game(fd);
        }
    } else if (streq(current_command, "ADMIN_REREAD")) {
        if (!admin_authorized[fd]) {
            send_line_log(fd, wn_denied, msg_orig);
        } else {
            reread();
            send_ok(fd, "ADMIN_REREAD");
        }
    } else {
        send_line_log(fd, wn_unknown_command, msg);
    }

    free(msg_orig);
    current_command = NULL;

    return 0;
}
示例#24
0
int main (int argc, char *argv[])
{
	// Allowing server to gracefully handle SIGINT and SIGTERM.
	signal(SIGINT, interrupt_handler);
	signal(SIGTERM, interrupt_handler);

	// Making a buffer for the log file and setting it to null.
    char log_buf[LOG_MSG_LEN];
    memset(log_buf, '\0', LOG_MSG_LEN);

    // Stuff for making, binding and then listening on the socket.
	struct sockaddr_in server, client;
	char *host;
	socklen_t len;
	int s, new_s, count, server_port;

	// Setting the correct code to NULL. This will be set for the whole
	// server execution if it was passed as an arg.
	char *correct = NULL;

	// Code for reading in the port number (and code if supplied).
	if (argc == 2) {
		server_port = atoi(argv[1]);
	} else
	if (argc == 3) {
		server_port = atoi(argv[1]);
		correct = argv[2];
	}
	else {
		fprintf(stderr, "Usage: %s [port_number] <code>\n", argv[0]);
		exit(1);
	}

	// Initialising the file pointer for writing to log.
	log_f = fopen("log.txt", "w");
	if (log_f == NULL)
	{
	    printf("Error opening file!\n");
	    exit(1);
	}

	// Setting up the mutex log for writing to log / collecting stats.
	if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        exit(1);
    }

	printf("Server port %i\n",server_port);
	
	/* Building data structures for sockets */
	/* Identify two end points; one for the server and the other for the client 
	when it connects to the server socket */
	memset (&server, 0, sizeof (server));
	memset (&client, 0, sizeof (client));
	
	/* 
	** Server socket initializations.
	** AF_INET: specifies the connection to Internet. In our example we use 
	** TCP port 5431 as the known server port; Any client needs to connect to
	** this port. INADDR_ANY specifies the server is willing to accept 
	** connections on any of the local host's IP addresses.
	*/
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons (server_port); 

	// Preliminary server steps: Setup: creation of passive open socket.
	if ((s = socket (AF_INET, SOCK_STREAM, 0)) < 0)
	{
      perror ("Error creating socket");
      exit (1);
	}
	printf("Socket descriptor:  %d\n", s);

	// Bind the socket to local address.
	if (bind (s, (struct sockaddr *) &server, sizeof (server)) < 0)
	{
      perror ("Error in binding to the specified port");
      exit (1);
	}
	printf("sock:  family = %d\n", server.sin_family);
	printf("       saddr  = %d\n", server.sin_addr.s_addr);
	printf("       port   = %d\n", ntohs(server.sin_port));

	// Sets the maximum number of pending connections to be allowed.
	if (listen (s, LISTEN_QUEUE) < 0)
	{
        perror("listen() failed with error");
        exit(1);
	}
	else
	{
		printf("Listening on port %d...\n", ntohs(server.sin_port));
	}

	// Creating the struct that will keep track of all the instances.
	StateInfo *state_info = create_state_info_struct(MAX_PLAYERS);

	// Build tge welcome message in game.c so we only have to do it once.
	build_welcome();

	// Creating the struct for file descriptors to be polled.
	struct pollfd poll_list[1];
	poll_list[0].fd = s;
	poll_list[0].events = POLLIN|POLLPRI;

	// The return value of poll, which runs each POLL_INTERVAL milliseconds.
	int poll_res;

	// Main server loop.
	while (1) {
		len = sizeof(client);

		/*
		** We use the poll() function outside of the accept so that we can
		** properly handle incoming signal interrupts. accept() is a blocking
		** function, it wouldn't process the SIGINT/SIGTERM until a connection
		** had been accepted. poll() checks if there is anything to be read on
		** the socket first (every POLL_INTERVAL) before running the accept().
		**
		** A fork could also have been used to catch the SIGINT/SIGTERM.
		** The polling solution however gives you a greater degree of fine tuned
		** control both due to the non-blocking nature and the programmer
		** defined checking interval, which also reduces computational expense.
		**
		** poll_res >= 0: Something ready to be read on the target fd/socket.
		** poll_res == 0: Nothing ready to be read on the target fd/socket.
		** poll_res <= 0: An error occurred, hopefully just because the SIGINT/
		**                SIGTERM interrupted the poll. We catch this and 
		**                gracefully shutdown the server.
		*/
		poll_res = poll(poll_list, 1, POLL_INTERVAL);

		// This block runs if there is something to be read on the socket.
		if (poll_res > 0) {
			// Accepting the new connection and assigning the socket number.
			if ((new_s = accept(s, (struct sockaddr *) &client, &len)) < 0)
			{
				printf("errno = %d, new_s = %d\n", errno, new_s);
				perror ("Accept failed");
				exit (1);
			}
			else
			{
				// Preparing ip4 for the ipv4 address.
	    		char ip4[INET_ADDRSTRLEN];
	    		inet_ntop(AF_INET,&(client.sin_addr), ip4, INET_ADDRSTRLEN);

	    		// Creating the individual game instance.
	    		if (create_game(new_s, ip4, correct, state_info) < 0){
	                sprintf(log_buf, "(0.0.0.0) Max players (%d) reached. \
Connection from %s rejected.\n", MAX_PLAYERS, ip4);
	                write_log(log_buf);
	            } else {
	                num_connections += 1;
	            }
	            memset(ip4, '\0', INET_ADDRSTRLEN);
			}
		} else if (poll_res == 0) {
示例#25
0
	void server_base::handle_message(send_function send_fn, 
		boost::function<void(client_info&)> close_fn, 
		boost::function<socket_info&(void)> socket_info_fn,
		int session_id, 
		const variant& msg)
	{
		const std::string& type = msg["type"].as_string();

		if(session_id == -1) {
			if(type == "create_game") {

				game_info_ptr g(create_game(msg));

				if(!g) {
					send_fn(json::parse("{ \"type\": \"create_game_failed\" }"));
					return;
				}

				send_fn(json::parse(formatter() << "{ \"type\": \"game_created\", \"game_id\": " << g->game_state->game_id() << " }"));
			
				status_change();

				return;
			} else if(type == "get_status") {
				const int last_status = msg["last_seen"].as_int();
				if(last_status == status_id_) {
					status_fns_.push_back(send_fn);
				} else {
					send_fn(create_lobby_msg());
				}
				return;
			} else if(type == "get_server_info") {
				send_fn(get_server_info());
				return;
			} else {
				std::map<variant,variant> m;
				m[variant("type")] = variant("unknown_message");
				m[variant("msg_type")] = variant(type);
				send_fn(variant(&m));
				return;
			}
		}

		if(type == "observe_game") {
			fprintf(stderr, "ZZZ: RECEIVE observe_game\n");
			const int id = msg["game_id"].as_int(-1);
			const std::string user = msg["user"].as_string();

			game_info_ptr g;
			foreach(const game_info_ptr& gm, games_) {
				if(id == -1 || gm->game_state->game_id() == id) {
					g = gm;
					break;
				}
			}

			if(!g) {
				fprintf(stderr, "ZZZ: SEND unknown_game\n");
				send_fn(json::parse("{ \"type\": \"unknown_game\" }"));
				return;
			}

			if(clients_.count(session_id)) {
				fprintf(stderr, "ZZZ: SEND reuse_ssoin_id\n");
				send_fn(json::parse("{ \"type\": \"reuse_session_id\" }"));
				return;
			}

			client_info& cli_info = clients_[session_id];
			cli_info.user = user;
			cli_info.game = g;
			cli_info.nplayer = -1;
			cli_info.last_contact = nheartbeat_;
			cli_info.session_id = session_id;

			g->clients.push_back(session_id);

			send_fn(json::parse(formatter() << "{ \"type\": \"observing_game\" }"));
			fprintf(stderr, "ZZZ: RESPONDED TO observe_game\n");

			return;
		}