Example #1
0
Socket::~Socket()
{
    Close();

    // Finalize the network when the last connection closes.
    if (--numAliveSockets == 0)
    {
        NetShutdown();
    }
}
Example #2
0
void Game::PlayScreen() 
{
    // init

    play_state = {};
    play_state.my_turn = server;

    // set ships

    const std::vector<Ship>& shipsToAdd = scrships_state.ships_grid.GetShips();
    for (const Ship& ship : shipsToAdd) 
    {
        play_state.battlefields[0].AddShip(ship.x, ship.y, ship.kind, ship.orient);
    }

    // send ships to second player
    PacketHead ph = { PT_ENEMY_SHIPS };
    PacketEnemyShips esp;

    for (size_t i = 0; i < _countof(esp.ships); ++i) 
    {
        esp.ships[i] = shipsToAdd[i];
    }
    int resulta = send( my_socket, ( const char * ) &ph, sizeof( ph ), 0 );
    int resultb = send( my_socket, ( const char * ) &esp, sizeof( esp ), 0 );

    if ( resulta < 1 || resultb < 1 ) {

        NetShutdown();
        NextState( G_MAIN_MENU );
        return;
    }

    // loop
    while ( true ) {

        // update screen
        PlayScreenDraw();

        // keys
        int key {};
        if (Console::GetInstance().KeyPressed(&key)) 
        {
            // exit
            if (key == 27) 
            {
                break;
            }

            // move sign
            else if (key == 'w' || key == 's' || key == 'a' || key == 'd') {
                if ( play_state.my_turn ) {

                    switch ( key ) {
                        case 'w' : play_state.sign_y --; break;
                        case 'a' : play_state.sign_x --; break;
                        case 's' : play_state.sign_y ++; break;
                        case 'd' : play_state.sign_x ++; break;
                    }
                    play_state.sign_y = max( min( play_state.sign_y, BattleFieldSizeH - 1 ), 0 );
                    play_state.sign_x = max( min( play_state.sign_x, BattleFieldSizeW - 1 ), 0 );
                }
            }

            // make shot
            else if ( key == ' ' && play_state.enemy_ready ) {
                if ( play_state.my_turn ) {

                    PlayShot( play_state.sign_x, play_state.sign_y, 0 );
                }
            }
            else ;
        }

        // read net
        if ( NETR_ERROR == PlayReadNet()) {
            break;
        }

        // check game over
        if ( play_state.enemy_ready && PlayCheckDone()) {

            break;
        }

        // pause
        Sleep( 2 );
    }

    NetShutdown();
    NextState( G_MAIN_MENU );
}