Esempio n. 1
0
void CMapGenOptions::updateCompOnlyPlayers()
{
	// Remove comp only players only from the end of the players map if necessary
	for(auto itrev = players.end(); itrev != players.begin();)
	{
		auto it = itrev;
		--it;
		if (players.size() <= getPlayerCount()) break;
		if(it->second.getPlayerType() == EPlayerType::COMP_ONLY)
		{
			players.erase(it);
		}
		else
		{
			--itrev;
		}
	}

	// Add some comp only players if necessary
	int compOnlyPlayersToAdd = getPlayerCount() - players.size();

	if (compOnlyPlayersToAdd < 0)
	{
		logGlobal->error("Incorrect number of players to add. Requested players %d, current players %d", playerCount, players.size());
		assert (compOnlyPlayersToAdd < 0);
	}
	for(int i = 0; i < compOnlyPlayersToAdd; ++i)
	{
		CPlayerSettings pSettings;
		pSettings.setPlayerType(EPlayerType::COMP_ONLY);
		pSettings.setColor(getNextPlayerColor());
		players[pSettings.getColor()] = pSettings;
	}
}
Esempio n. 2
0
const CRmgTemplate * CMapGenOptions::getPossibleTemplate(CRandomGenerator & rand) const
{
	// Find potential templates
	const auto & tpls = getAvailableTemplates();
	std::list<const CRmgTemplate *> potentialTpls;
	for(const auto & tplPair : tpls)
	{
		const auto & tpl = tplPair.second;
		int3 tplSize(width, height, (hasTwoLevels ? 2 : 1));
		if(tpl->matchesSize(tplSize))
		{
			bool isPlayerCountValid = false;
			if (getPlayerCount() != RANDOM_SIZE)
			{
				if (tpl->getPlayers().isInRange(getPlayerCount()))
					isPlayerCountValid = true;
			}
			else
			{
				// Human players shouldn't be banned when playing with random player count
				auto playerNumbers = tpl->getPlayers().getNumbers();
				if(countHumanPlayers() <= *boost::min_element(playerNumbers))
				{
					isPlayerCountValid = true;
				}
			}

			if (isPlayerCountValid)
			{
				bool isCpuPlayerCountValid = false;
				if(compOnlyPlayerCount != RANDOM_SIZE)
				{
					if (tpl->getCpuPlayers().isInRange(compOnlyPlayerCount))
						isCpuPlayerCountValid = true;
				}
				else
				{
					isCpuPlayerCountValid = true;
				}

				if(isCpuPlayerCountValid)
					potentialTpls.push_back(tpl);
			}
		}
	}

	// Select tpl
	if(potentialTpls.empty())
	{
		return nullptr;
	}
	else
	{
		return *RandomGeneratorUtil::nextItem(potentialTpls, rand);
	}
}
Esempio n. 3
0
void CMapGenOptions::setCompOnlyPlayerCount(si8 value)
{
	assert(value == RANDOM_SIZE || (getPlayerCount() == RANDOM_SIZE || (value >= 0 && value <= getPlayerCount())));
	compOnlyPlayerCount = value;

	if (getPlayerCount() != RANDOM_SIZE && getCompOnlyPlayerCount() != RANDOM_SIZE)
		humanPlayersCount = getPlayerCount() - getCompOnlyPlayerCount();

	resetPlayersMap();
}
Esempio n. 4
0
void Server_Game::removePlayer(Server_Player *player)
{
	room->getServer()->removePersistentPlayer(QString::fromStdString(player->getUserInfo()->name()), room->getId(), gameId, player->getPlayerId());
	players.remove(player->getPlayerId());
	
	GameEventStorage ges;
	removeArrowsRelatedToPlayer(ges, player);
	unattachCards(ges, player);
	ges.enqueueGameEvent(Event_Leave(), player->getPlayerId());
	ges.sendToGame(this);
	
	bool playerActive = activePlayer == player->getPlayerId();
	bool playerHost = hostId == player->getPlayerId();
	bool spectator = player->getSpectator();
	player->prepareDestroy();
	
	if (!getPlayerCount()) {
		gameClosed = true;
		deleteLater();
		return;
	} else if (!spectator) {
		if (playerHost) {
			int newHostId = -1;
			QMapIterator<int, Server_Player *> playerIterator(players);
			while (playerIterator.hasNext()) {
				Server_Player *p = playerIterator.next().value();
				if (!p->getSpectator()) {
					newHostId = p->getPlayerId();
					break;
				}
			}
			if (newHostId != -1) {
				hostId = newHostId;
				sendGameEventContainer(prepareGameEvent(Event_GameHostChanged(), hostId));
			}
		}
		stopGameIfFinished();
		if (gameStarted && playerActive)
			nextTurn();
	}
	
	ServerInfo_Game gameInfo;
	gameInfo.set_room_id(room->getId());
	gameInfo.set_game_id(gameId);
	gameInfo.set_player_count(getPlayerCount());
	gameInfo.set_spectators_count(getSpectatorCount());
	emit gameInfoChanged(gameInfo);
}
Esempio n. 5
0
void Server_Game::getInfo(ServerInfo_Game &result) const
{
	QMutexLocker locker(&gameMutex);
	
	result.set_room_id(room->getId());
	result.set_game_id(gameId);
	if (gameClosed)
		result.set_closed(true);
	else {
		for (int i = 0; i < gameTypes.size(); ++i)
			result.add_game_types(gameTypes[i]);
		
		result.set_max_players(getMaxPlayers());
		result.set_description(getDescription().toStdString());
		result.set_with_password(!getPassword().isEmpty());
		result.set_player_count(getPlayerCount());
		result.set_started(gameStarted);
		result.mutable_creator_info()->CopyFrom(*getCreatorInfo());
		result.set_only_buddies(onlyBuddies);
		result.set_only_registered(onlyRegistered);
		result.set_spectators_allowed(getSpectatorsAllowed());
		result.set_spectators_need_password(getSpectatorsNeedPassword());
		result.set_spectators_can_chat(spectatorsCanTalk);
		result.set_spectators_omniscient(spectatorsSeeEverything);
		result.set_spectators_count(getSpectatorCount());
		result.set_start_time(startTime.toTime_t());
	}
}
Esempio n. 6
0
bool BaseAI::startTurn()
{
  static bool initialized = false;
  int count = 0;
  count = getShipTypeCount(c);
  shipTypes.clear();
  shipTypes.resize(count);
  for(int i = 0; i < count; i++)
  {
    shipTypes[i] = ShipType(getShipType(c, i));
  }

  count = getPlayerCount(c);
  players.clear();
  players.resize(count);
  for(int i = 0; i < count; i++)
  {
    players[i] = Player(getPlayer(c, i));
  }

  count = getShipCount(c);
  ships.clear();
  ships.resize(count);
  for(int i = 0; i < count; i++)
  {
    ships[i] = Ship(getShip(c, i));
  }

  if(!initialized)
  {
    initialized = true;
    init();
  }
  return run();
}
Esempio n. 7
0
Response::ResponseCode Server_Game::checkJoin(ServerInfo_User *user, const QString &_password, bool spectator, bool overrideRestrictions)
{
	Server_DatabaseInterface *databaseInterface = room->getServer()->getDatabaseInterface();
	{
		QMapIterator<int, Server_Player *> playerIterator(players);
		while (playerIterator.hasNext())
			if (playerIterator.next().value()->getUserInfo()->name() == user->name())
				return Response::RespContextError;
	}
	if (!(overrideRestrictions && (user->user_level() & ServerInfo_User::IsModerator))) {
		if ((_password != password) && !(spectator && !spectatorsNeedPassword))
			return Response::RespWrongPassword;
		if (!(user->user_level() & ServerInfo_User::IsRegistered) && onlyRegistered)
			return Response::RespUserLevelTooLow;
		if (onlyBuddies)
			if (!databaseInterface->isInBuddyList(QString::fromStdString(creatorInfo->name()), QString::fromStdString(user->name())))
				return Response::RespOnlyBuddies;
		if (databaseInterface->isInIgnoreList(QString::fromStdString(creatorInfo->name()), QString::fromStdString(user->name())))
			return Response::RespInIgnoreList;
		if (spectator) {
			if (!spectatorsAllowed)
				return Response::RespSpectatorsNotAllowed;
		}
	}
	if (!spectator && (gameStarted || (getPlayerCount() >= getMaxPlayers())))
		return Response::RespGameFull;
	
	return Response::RespOk;
}
bool BaseAI::startTurn()
{
    static bool initialized = false;
    int count = 0;
    count = getPlayerCount(c);
    players.clear();
    players.resize(count);
    for(int i = 0; i < count; i++)
    {
        players[i] = Player(getPlayer(c, i));
    }

    count = getCheckerCount(c);
    checkers.clear();
    checkers.resize(count);
    for(int i = 0; i < count; i++)
    {
        checkers[i] = Checker(getChecker(c, i));
    }

    if(!initialized)
    {
        initialized = true;
        init();
    }
    return run();
}
Esempio n. 9
0
bool
ServerRoom::join( ClientConnection* clientConnection, const std::string& name, const std::string& password, int& chairIndex )
{
    // REFACTOR - this code and rejoin() have a LOT in common

    // This could be a rejoin - find the human by name.
    HumanPlayer* humanPlayer = getHumanPlayer( name );
    if( humanPlayer  )
    {
        mLogger->debug( "join: rejoining existing player to room" );
        return rejoin( clientConnection, name );
    }

    if( !mPassword.empty() && (password != mPassword) )
    {
        sendJoinRoomFailureRsp( clientConnection, proto::JoinRoomFailureRsp::RESULT_INVALID_PASSWORD, mRoomId );
        return false;
    }

    int playerIdx = getNextAvailablePlayerIndex();
    if( playerIdx == -1 )
    {
        sendJoinRoomFailureRsp( clientConnection, proto::JoinRoomFailureRsp::RESULT_ROOM_FULL, mRoomId );
        return false;
    }
    chairIndex = playerIdx;

    HumanPlayer *human = new HumanPlayer( playerIdx, mDraftPtr, mLoggingConfig.createChildConfig( "humanplayer" ), this );
    connect( human, &HumanPlayer::readyUpdate, this, &ServerRoom::handleHumanReadyUpdate );
    connect( human, &HumanPlayer::deckUpdate, this, &ServerRoom::handleHumanDeckUpdate );
    human->setName( name );
    human->setClientConnection( clientConnection );
    mClientConnectionMap.insert( clientConnection, human );
    mHumanList.append( human );
    mPlayerList[playerIdx] = human;
    mChairStateList[playerIdx] = CHAIR_STATE_STANDBY;
    mLogger->debug( "joined human {} with connection {} to player map at index {}:",
            (std::size_t)human, (std::size_t)clientConnection, playerIdx );
    for( int i = 0; i < mPlayerList.count(); ++i )
    {
        mLogger->debug( "   {}", (std::size_t)(mPlayerList[i]) );
    }

    // With at least one connection don't let the room expire.
    mRoomExpirationTimer->stop();

    // The human must observe the draft to get the observation callbacks.
    mDraftPtr->addObserver( human );

    // Inform the client that the room join was successful.
    sendJoinRoomSuccessRspInd( clientConnection, mRoomId, false, chairIndex );

    emit playerCountChanged( getPlayerCount() );

    // Inform all client connections of the room occupants changes.
    broadcastRoomOccupantsInfo();

    return true;
}
Esempio n. 10
0
void
ServerRoom::leave( ClientConnection* clientConnection )
{
    QMap<ClientConnection*,HumanPlayer*>::iterator iter = mClientConnectionMap.find( clientConnection );
    if( iter != mClientConnectionMap.end() )
    {
        HumanPlayer* human = iter.value();
        const int chairIndex = human->getChairIndex();

        human->removeClientConnection();
        mClientConnectionMap.remove( clientConnection );
        mLogger->debug( "removed client {} from map", (std::size_t)clientConnection );

        if( mChairStateList[chairIndex] == CHAIR_STATE_ACTIVE )
        {
            // We removed the connection above, but leave the human in the
            // human list and maintain state in case the connection is
            // re-established.
            mChairStateList[chairIndex] = CHAIR_STATE_DEPARTED;

            // Draft was started so if the room now has no more connectons
            // start the room expiration timer.
            if( mClientConnectionMap.isEmpty() )
            {
                mLogger->debug( "starting room expiration timer" );
                mRoomExpirationTimer->start( ABANDONED_ROOM_EXPIRATION_SECONDS * 1000 );
            }
        }
        else
        {
            // The draft hasn't started yet, so remove and destroy the human.

            mDraftPtr->removeObserver( human );
            mHumanList.removeOne( human );
            delete human;

            // Null out player list entry and mark chair state as empty
            mPlayerList[chairIndex] = 0;
            mChairStateList[chairIndex] = CHAIR_STATE_EMPTY;

            // Draft hasn't started, so if the room now has no more
            // connections treat it as expired.
            if( mClientConnectionMap.isEmpty() )
            {
                emit roomExpired();
            }
        }

        emit playerCountChanged( getPlayerCount() );

        // Inform all client connections of the room occupants changes.
        broadcastRoomOccupantsInfo();
    }
    else
    {
        mLogger->warn( "unknown client disconnect" );
    }
}
Esempio n. 11
0
void CMapGenOptions::resetPlayersMap()
{

	std::map<PlayerColor, TFaction> rememberTownTypes;

	for (auto p : players)
	{
		auto town = p.second.getStartingTown();
		if (town != RANDOM_SIZE)
			rememberTownTypes[p.first] = town;
	}


	players.clear();
	int realPlayersCnt = humanPlayersCount;
	int realCompOnlyPlayersCnt = (compOnlyPlayerCount == RANDOM_SIZE) ? (PlayerColor::PLAYER_LIMIT_I - realPlayersCnt) : compOnlyPlayerCount;
	int totalPlayersLimit = realPlayersCnt + realCompOnlyPlayersCnt;
	if (getPlayerCount() == RANDOM_SIZE || compOnlyPlayerCount == RANDOM_SIZE)
		totalPlayersLimit = static_cast<int>(PlayerColor::PLAYER_LIMIT_I);

	//FIXME: what happens with human players here?
	for(int color = 0; color < totalPlayersLimit; ++color)
	{
		CPlayerSettings player;
		auto pc = PlayerColor(color);
		player.setColor(pc);
		auto playerType = EPlayerType::AI;
		if (getPlayerCount() != RANDOM_SIZE && color < realPlayersCnt)
		{
			playerType = EPlayerType::HUMAN;
		}
		else if((getPlayerCount() != RANDOM_SIZE && color >= realPlayersCnt)
		   || (compOnlyPlayerCount != RANDOM_SIZE && color >= (PlayerColor::PLAYER_LIMIT_I-compOnlyPlayerCount)))
		{
			playerType = EPlayerType::COMP_ONLY;
		}
		player.setPlayerType(playerType);
		players[pc] = player;

		if (vstd::contains(rememberTownTypes, pc))
			players[pc].setStartingTown(rememberTownTypes[pc]);
	}
}
Esempio n. 12
0
void CMapGenOptions::setPlayerCount(si8 value)
{
	assert((value >= 1 && value <= PlayerColor::PLAYER_LIMIT_I) || value == RANDOM_SIZE);
	playerCount = value;

	auto possibleCompPlayersCount = value;
	if (compOnlyPlayerCount > possibleCompPlayersCount)
		setCompOnlyPlayerCount(possibleCompPlayersCount);

	if (getPlayerCount() != RANDOM_SIZE)
	{
		if (getCompOnlyPlayerCount() != RANDOM_SIZE)
			humanPlayersCount = getPlayerCount() - getCompOnlyPlayerCount();
		else
			humanPlayersCount = getPlayerCount();
	}

	resetPlayersMap();
}
Esempio n. 13
0
void OnlineRaceLogic::destroy()
{
	if (m_initialized) {
		m_client->disconnect();

		// remove cars from level
		const int playerCount = getPlayerCount();

		for (int i = 0; i < playerCount; ++i) {
			Player &player = getPlayer(i);
			getLevel().removeCar(&player.getCar());
		}

		getProgress().destroy();
		getLevel().destroy();
	}
}
Esempio n. 14
0
void CMapGenOptions::updatePlayers()
{
	// Remove AI players only from the end of the players map if necessary
	for(auto itrev = players.end(); itrev != players.begin();)
	{
		auto it = itrev;
		--it;
		if (players.size() == getPlayerCount()) break;
		if(it->second.getPlayerType() == EPlayerType::AI)
		{
			players.erase(it);
		}
		else
		{
			--itrev;
		}
	}
}
Esempio n. 15
0
void Server_Game::addPlayer(Server_AbstractUserInterface *userInterface, ResponseContainer &rc, bool spectator, bool broadcastUpdate)
{
	QMutexLocker locker(&gameMutex);
	
	Server_Player *newPlayer = new Server_Player(this, nextPlayerId++, userInterface->copyUserInfo(true), spectator, userInterface);
	newPlayer->moveToThread(thread());
	
	Event_Join joinEvent;
	newPlayer->getProperties(*joinEvent.mutable_player_properties(), true);
	sendGameEventContainer(prepareGameEvent(joinEvent, -1));
	
	const QString playerName = QString::fromStdString(newPlayer->getUserInfo()->name());
	if (spectator)
		allSpectatorsEver.insert(playerName);
	else
		allPlayersEver.insert(playerName);
	players.insert(newPlayer->getPlayerId(), newPlayer);
	if (newPlayer->getUserInfo()->name() == creatorInfo->name()) {
		hostId = newPlayer->getPlayerId();
		sendGameEventContainer(prepareGameEvent(Event_GameHostChanged(), hostId));
	}
	
	if (broadcastUpdate) {
		ServerInfo_Game gameInfo;
		gameInfo.set_room_id(room->getId());
		gameInfo.set_game_id(gameId);
		gameInfo.set_player_count(getPlayerCount());
		gameInfo.set_spectators_count(getSpectatorCount());
		emit gameInfoChanged(gameInfo);
	}
	
	if ((newPlayer->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) && !spectator)
		room->getServer()->addPersistentPlayer(playerName, room->getId(), gameId, newPlayer->getPlayerId());
	
	userInterface->playerAddedToGame(gameId, room->getId(), newPlayer->getPlayerId());
	
	createGameJoinedEvent(newPlayer, rc, false);
}
Esempio n. 16
0
void sampFakeKill()
{
	if(GetTickCount() - dwLastFakeKill >= settings.uiFakeKillInterval)
	{
		int randkillerid = 0xFFFF + 1;
		int randreason = rand() % 46;

		while(!(randkillerid >= 0 && randkillerid < MAX_PLAYERS && randkillerid != g_myPlayerID && playerInfo[randkillerid].iIsConnected))
		{
			if(getPlayerCount() < 2)
			{
				randkillerid = 0xFFFF;
				break;
			}

			randkillerid = rand() % MAX_PLAYERS;
		}

		if(randkillerid != 0xFFFF + 1)
			SendWastedNotification(randreason, randkillerid);

		dwLastFakeKill = GetTickCount();
	}
}
Esempio n. 17
0
void CMapGenOptions::setTeamCount(si8 value)
{
	assert(getPlayerCount() == RANDOM_SIZE || (value >= 0 && value < getPlayerCount()) || value == RANDOM_SIZE);
	teamCount = value;
}
Esempio n. 18
0
bool
ServerRoom::rejoin( ClientConnection* clientConnection, const std::string& name )
{
    mLogger->trace( "rejoin room, client={}, name={}", (std::size_t)clientConnection, name );

    // Find the human by name.
    HumanPlayer* humanPlayer = getHumanPlayer( name );
    if( humanPlayer == nullptr )
    {
        mLogger->warn( "rejoin room error: player not found" );
        return false;
    }

    // Make sure the human was actually disconnected.
    const int chairIndex = humanPlayer->getChairIndex();
    if( mChairStateList[chairIndex] != CHAIR_STATE_DEPARTED )
    {
        mLogger->warn( "rejoin room error: player not disconnected" );
        return false;
    }

    // Update internals.
    humanPlayer->setClientConnection( clientConnection );
    mClientConnectionMap.insert( clientConnection, humanPlayer );
    mChairStateList[chairIndex] = CHAIR_STATE_ACTIVE;
    mLogger->debug( "rejoined human {} with connection {} to player map at index {}:",
            (std::size_t)humanPlayer, (std::size_t)clientConnection, chairIndex );
    for( int i = 0; i < mPlayerList.count(); ++i )
    {
        mLogger->debug( "  {}", (std::size_t)(mPlayerList[i]) );
    }

    // With at least one connection don't let the room expire.
    mRoomExpirationTimer->stop();

    // Send the user a room join success indication with the rejoin flag set.
    sendJoinRoomSuccessRspInd( clientConnection, mRoomId, true, chairIndex );

    emit playerCountChanged( getPlayerCount() );

    // Inform all occupants (including the new user) of user states.
    broadcastRoomOccupantsInfo();

    // Send the rejoining user their inventory of cards.
    humanPlayer->sendInventoryToClient();

    // Send user a room stage update indication.
    proto::ServerToClientMsg msg;
    proto::RoomStageInd* roomStageInd = msg.mutable_room_stage_ind();
    switch( mDraftPtr->getState() )
    {
        case DraftType::STATE_NEW:
            roomStageInd->set_stage( proto::RoomStageInd::STAGE_NEW );
            break;
        case DraftType::STATE_RUNNING:
            {
                roomStageInd->set_stage( proto::RoomStageInd::STAGE_RUNNING );
                proto::RoomStageInd::RoundInfo* roundInfo = roomStageInd->mutable_round_info();
                roundInfo->set_round( mDraftPtr->getCurrentRound() );
                if( mPostRoundTimerActive )
                {
                    const int millis = getPostRoundTimeRemainingMillis();
                    mLogger->debug( "RoomStageInd: post-round timer active, setting to {}", millis );
                    roundInfo->set_post_round_time_remaining_millis( millis );
                }
            }
            break;
        case DraftType::STATE_COMPLETE:
            roomStageInd->set_stage( proto::RoomStageInd::STAGE_COMPLETE );
            break;
        default:
            mLogger->error( "unhandled room state {}", mDraftPtr->getState() );
    }
    mLogger->debug( "sending RoomStageInd, size={} to client {}",
            msg.ByteSize(), (std::size_t)clientConnection );
    clientConnection->sendProtoMsg( msg );

    // Send current draft state information if draft is running.
    if( mDraftPtr->getState() == DraftType::STATE_RUNNING )
    {
        // Send user current pack, if any.
        humanPlayer->sendCurrentPackToClient();

        // Update the client's public state, if any.
        sendPublicState( { clientConnection } );
    }

    // Send all current hashes if the round is complete.
    if( mDraftPtr->getState() == DraftType::STATE_COMPLETE )
    {
        msg.Clear();
        proto::RoomChairsDeckInfoInd* deckInfoInd = msg.mutable_room_chairs_deck_info_ind();

        for( auto human : mHumanList )
        {
            proto::RoomChairsDeckInfoInd::Chair* chair = deckInfoInd->add_chairs();
            chair->set_chair_index( human->getChairIndex() );
            chair->set_cockatrice_hash( human->getCockatriceHash().toStdString() );
            chair->set_mws_hash( "" );
        }

        mLogger->debug( "sending deckInfoInd, size={} to client {}",
                msg.ByteSize(), (std::size_t)clientConnection );
        clientConnection->sendProtoMsg( msg );
    }

    return true;
}
Esempio n. 19
0
void Server_Game::doStartGameIfReady()
{
	Server_DatabaseInterface *databaseInterface = room->getServer()->getDatabaseInterface();
	QMutexLocker locker(&gameMutex);
	
	if (getPlayerCount() < maxPlayers)
		return;
	QMapIterator<int, Server_Player *> playerIterator(players);
	while (playerIterator.hasNext()) {
		Server_Player *p = playerIterator.next().value();
		if (!p->getReadyStart() && !p->getSpectator())
			return;
	}
	playerIterator.toFront();
	while (playerIterator.hasNext()) {
		Server_Player *p = playerIterator.next().value();
		if (!p->getSpectator())
			p->setupZones();
	}

	gameStarted = true;
	playerIterator.toFront();
	while (playerIterator.hasNext()) {
		Server_Player *player = playerIterator.next().value();
		player->setConceded(false);
		player->setReadyStart(false);
	}
	
	if (firstGameStarted) {
		currentReplay->set_duration_seconds(secondsElapsed - startTimeOfThisGame);
		replayList.append(currentReplay);
		currentReplay = new GameReplay;
		currentReplay->set_replay_id(databaseInterface->getNextReplayId());
		ServerInfo_Game *gameInfo = currentReplay->mutable_game_info();
		getInfo(*gameInfo);
		gameInfo->set_started(false);
		
		Event_GameStateChanged omniscientEvent;
		createGameStateChangedEvent(&omniscientEvent, 0, true, true);
		
		GameEventContainer *replayCont = prepareGameEvent(omniscientEvent, -1);
		replayCont->set_seconds_elapsed(0);
		replayCont->clear_game_id();
		currentReplay->add_event_list()->CopyFrom(*replayCont);
		delete replayCont;
		
		startTimeOfThisGame = secondsElapsed;
	} else
		firstGameStarted = true;
	
	sendGameStateToPlayers();
	
	activePlayer = -1;
	nextTurn();
	
	locker.unlock();
	
	ServerInfo_Game gameInfo;
	gameInfo.set_room_id(room->getId());
	gameInfo.set_game_id(gameId);
	gameInfo.set_started(true);
	emit gameInfoChanged(gameInfo);
}
Esempio n. 20
0
void CMapGenOptions::finalize(CRandomGenerator & rand)
{
	logGlobal->info("RMG settings: players %d, teams %d, computer players %d, computer teams %d, water %d, monsters %d",
		static_cast<int>(getPlayerCount()), static_cast<int>(getTeamCount()), static_cast<int>(getCompOnlyPlayerCount()),
		static_cast<int>(getCompOnlyTeamCount()), static_cast<int>(getWaterContent()), static_cast<int>(getMonsterStrength()));

	if(!mapTemplate)
	{
		mapTemplate = getPossibleTemplate(rand);
	}
	assert(mapTemplate);

	if (getPlayerCount() == RANDOM_SIZE)
	{
		auto possiblePlayers = mapTemplate->getPlayers().getNumbers();
		//ignore all non-randomized players, make sure these players will not be missing after roll
		possiblePlayers.erase(possiblePlayers.begin(), possiblePlayers.lower_bound(countHumanPlayers() + countCompOnlyPlayers()));
		assert(!possiblePlayers.empty());
		setPlayerCount (*RandomGeneratorUtil::nextItem(possiblePlayers, rand));
		updatePlayers();
	}
	if(teamCount == RANDOM_SIZE)
	{
		teamCount = rand.nextInt(getPlayerCount() - 1);
		if (teamCount == 1)
			teamCount = 0;
	}
	if(compOnlyPlayerCount == RANDOM_SIZE)
	{
		auto possiblePlayers = mapTemplate->getCpuPlayers().getNumbers();
		compOnlyPlayerCount = *RandomGeneratorUtil::nextItem(possiblePlayers, rand);
		updateCompOnlyPlayers();
	}
	if(compOnlyTeamCount == RANDOM_SIZE)
	{
		compOnlyTeamCount = rand.nextInt(std::max(compOnlyPlayerCount - 1, 0));
	}

	if(waterContent == EWaterContent::RANDOM)
	{
		waterContent = static_cast<EWaterContent::EWaterContent>(rand.nextInt(EWaterContent::NONE, EWaterContent::ISLANDS));
	}
	if(monsterStrength == EMonsterStrength::RANDOM)
	{
		monsterStrength = static_cast<EMonsterStrength::EMonsterStrength>(rand.nextInt(EMonsterStrength::GLOBAL_WEAK, EMonsterStrength::GLOBAL_STRONG));
	}

	assert (vstd::iswithin(waterContent, EWaterContent::NONE, EWaterContent::ISLANDS));
	assert (vstd::iswithin(monsterStrength, EMonsterStrength::GLOBAL_WEAK, EMonsterStrength::GLOBAL_STRONG));


	//rectangular maps are the future of gaming
	//setHeight(20);
	//setWidth(50);

	logGlobal->trace("Player config:");
	int humanPlayers = 0, cpuOnlyPlayers = 0, AIplayers = 0;
	for (auto player : players)
	{
		std::string playerType;
		switch (player.second.getPlayerType())
		{
		case EPlayerType::AI:
			playerType = "AI";
			AIplayers++;
			break;
		case EPlayerType::COMP_ONLY:
			playerType = "computer only";
			cpuOnlyPlayers++;
			break;
		case EPlayerType::HUMAN:
			playerType = "human only";
			humanPlayers++;
			break;
			default:
				assert(false);
		}
		logGlobal->trace("Player %d: %s", player.second.getColor(), playerType);
	}
	setCompOnlyPlayerCount(cpuOnlyPlayers); //human players are set automaticlaly (?)
	logGlobal->info("Final player config: %d total, %d cpu-only", players.size(), (int)getCompOnlyPlayerCount());
}
Esempio n. 21
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	srand((unsigned int)GetTickCount());

	// load up settings
	if(!LoadSettings())
	{
		Log("Failed to load settings");
		getchar();
		return 0;
	}

	if(settings.iConsole)
		SetUpConsole();
	else
	{
		SetUpWindow(hInstance);
		Sleep(500); // wait a bit for the dialog to create
	}

	// RCON mode
	if(settings.runMode == RUNMODE_RCON)
	{
		if(RCONReceiveLoop())
		{
			if(flLog != NULL)
			{
				fclose(flLog);
				flLog = NULL;
			}

			return 0;
		}
	}	

	// set up networking
	pRakClient = RakNetworkFactory::GetRakClientInterface();
	if(pRakClient == NULL)
		return 0;

	pRakClient->SetMTUSize(576);

	resetPools(1, 0);
	RegisterRPCs(pRakClient);

	SYSTEMTIME time;
	GetLocalTime(&time);
	if(settings.iConsole)
	{
		Log(" ");
		Log("* ===================================================== *");
		Log("  RakSAMP " RAKSAMP_VERSION " initialized on %02d/%02d/%02d %02d:%02d:%02d",
			time.wDay, time.wMonth, time.wYear, time.wHour, time.wMinute, time.wSecond);
		Log("  Authors: " AUTHOR "");
		Log("* ===================================================== *");
		Log(" ");
	}

	char szInfo[400];
	char szLastInfo[400];
	
	int iLastMoney = iMoney;
	int iLastDrunkLevel = iDrunkLevel;

	int iLastStatsUpdate = GetTickCount();
	
	while(1)
	{
		UpdateNetwork(pRakClient);

		if(settings.bSpam)
			sampSpam();

		if (settings.bFakeKill)
			sampFakeKill();

		if (settings.bLag)
			sampLag();

		if (settings.bJoinFlood)
			sampJoinFlood();

		if (settings.bChatFlood)
			sampChatFlood();

		if (settings.bClassFlood)
			sampClassFlood();

		processPulsator();
		processBulletFlood();

		if (!iConnectionRequested)
		{
			if(!iGettingNewName)
				sampConnect(settings.server.szAddr, settings.server.iPort, settings.server.szNickname, settings.server.szPassword, pRakClient);
			else
				sampConnect(settings.server.szAddr, settings.server.iPort, g_szNickName, settings.server.szPassword, pRakClient);

			iConnectionRequested = 1;
		}

		if (iAreWeConnected && iGameInited)
		{
			static DWORD dwLastInfoUpdate = GetTickCount();
			if(dwLastInfoUpdate && dwLastInfoUpdate < (GetTickCount() - 1000))
			{
				char szHealthText[16], szArmourText[16];

				if(settings.fPlayerHealth > 200.0f)
					sprintf_s(szHealthText, sizeof(szHealthText), "N/A");
				else
					sprintf_s(szHealthText, sizeof(szHealthText), "%.2f", settings.fPlayerHealth);

				if(settings.fPlayerArmour > 200.0f)
					sprintf_s(szArmourText, sizeof(szArmourText), "N/A");
				else
					sprintf_s(szArmourText, sizeof(szArmourText), "%.2f", settings.fPlayerArmour);

				sprintf_s(szInfo, 400, "Hostname: %s     Players: %d     Ping: %d     Authors: %s\nHealth: %s     Armour: %s     Skin: %d     X: %.4f     Y: %.4f     Z: %.4f     Rotation: %.4f",
				g_szHostName, getPlayerCount(), playerInfo[g_myPlayerID].dwPing, AUTHOR, szHealthText, szArmourText, iLocalPlayerSkin, settings.fNormalModePos[0], settings.fNormalModePos[1], settings.fNormalModePos[2], settings.fNormalModeRot);
				
				if(strcmp(szInfo, szLastInfo) != 0)
				{
					SetWindowText(texthwnd, szInfo);
					sprintf_s(szLastInfo, szInfo);
				}
			}

			if (settings.iUpdateStats)
			{
				if((GetTickCount() - iLastStatsUpdate >= 1000) || iMoney != iLastMoney || iDrunkLevel != iLastDrunkLevel)
				{
					RakNet::BitStream bsSend;

					bsSend.Write((BYTE)ID_STATS_UPDATE);

					iDrunkLevel -= (rand() % settings.iMaxFPS + settings.iMinFPS);

					if(iDrunkLevel < 0)
						iDrunkLevel = 0;

					bsSend.Write(iMoney);
					bsSend.Write(iDrunkLevel);

					pRakClient->Send(&bsSend, HIGH_PRIORITY, RELIABLE, 0);

					iLastMoney = iMoney;
					iLastDrunkLevel = iDrunkLevel;

					iLastStatsUpdate = GetTickCount();
				}
			}

			if(settings.runMode == RUNMODE_BARE)
				goto bare;

			if(!iSpawned)
			{
				if(settings.iManualSpawn != 0)
				{
					if(!iNotificationDisplayedBeforeSpawn)
					{
						sampRequestClass(settings.iClassID);
						
						Log("Please write !spawn into the console when you're ready to spawn.");

						iNotificationDisplayedBeforeSpawn = 1;
					}
				}
				else
				{
					sampRequestClass(settings.iClassID);
					sampSpawn();

					iSpawned = 1;
					iNotificationDisplayedBeforeSpawn = 1;
				}
			}
			else
			{
				if(settings.runMode == RUNMODE_STILL)
				{
					// Nothing left to do. :-)
				}

				if(settings.runMode == RUNMODE_NORMAL)
				{
					if(settings.AutoGotoCP && settings.CurrentCheckpoint.bActive)
					{
						settings.fNormalModePos[0] = settings.CurrentCheckpoint.fPosition[0];
						settings.fNormalModePos[1] = settings.CurrentCheckpoint.fPosition[1];
						settings.fNormalModePos[2] = settings.CurrentCheckpoint.fPosition[2];
					}

					onFootUpdateAtNormalPos();
				}

				// Run autorun commands
				if(settings.iAutorun)
				{
					if(dwAutoRunTick && dwAutoRunTick < (GetTickCount() - 2000))
					{
						static int autorun;
						if(!autorun)
						{
							Log("Loading autorun...");
							for(int i = 0; i < MAX_AUTORUN_CMDS; i++)
								if(settings.autoRunCMDs[i].iExists)
									RunCommand(settings.autoRunCMDs[i].szCMD, 1);

							autorun = 1;
						}
					}
				}

				// Following player mode.
				if(settings.runMode == RUNMODE_FOLLOWPLAYER)
				{
					PLAYERID copyingID = getPlayerIDFromPlayerName(settings.szFollowingPlayerName);
					if(copyingID != (PLAYERID)-1)
						onFootUpdateFollow(copyingID);
				}

				// Following a player with a vehicle mode.
				if(settings.runMode == RUNMODE_FOLLOWPLAYERSVEHICLE)
				{
					PLAYERID copyingID = getPlayerIDFromPlayerName(settings.szFollowingPlayerName);
					if(copyingID != (PLAYERID)-1)
						inCarUpdateFollow(copyingID, (VEHICLEID)settings.iFollowingWithVehicleID);
				}

			}
		}

bare:;
		Sleep(30);
	}

	if(flLog != NULL)
	{
		fclose(flLog);
		flLog = NULL;
	}

	if(flTextDrawsLog != NULL)
	{
		fclose(flTextDrawsLog);
		flTextDrawsLog = NULL;
	}

	return 0;
}
Esempio n. 22
0
bool BaseAI::startTurn()
{
  static bool initialized = false;
  int count = 0;
  count = getPlayerCount(c);
  players.clear();
  players.resize(count);
  for(int i = 0; i < count; i++)
  {
    players[i] = Player(getPlayer(c, i));
  }

  count = getMappableCount(c);
  mappables.clear();
  mappables.resize(count);
  for(int i = 0; i < count; i++)
  {
    mappables[i] = Mappable(getMappable(c, i));
  }

  count = getTileCount(c);
  tiles.clear();
  tiles.resize(count);
  for(int i = 0; i < count; i++)
  {
    tiles[i] = Tile(getTile(c, i));
  }

  count = getTrapCount(c);
  traps.clear();
  traps.resize(count);
  for(int i = 0; i < count; i++)
  {
    traps[i] = Trap(getTrap(c, i));
  }

  count = getThiefCount(c);
  thiefs.clear();
  thiefs.resize(count);
  for(int i = 0; i < count; i++)
  {
    thiefs[i] = Thief(getThief(c, i));
  }

  count = getThiefTypeCount(c);
  thiefTypes.clear();
  thiefTypes.resize(count);
  for(int i = 0; i < count; i++)
  {
    thiefTypes[i] = ThiefType(getThiefType(c, i));
  }

  count = getTrapTypeCount(c);
  trapTypes.clear();
  trapTypes.resize(count);
  for(int i = 0; i < count; i++)
  {
    trapTypes[i] = TrapType(getTrapType(c, i));
  }

  if(!initialized)
  {
    initialized = true;
    init();
  }
  return run();
}
Esempio n. 23
0
void cheat_killflood()
{
	if (cheat_state->_generic.killflood)
		g_RakClient->SendDeath(rand() % getPlayerCount(), rand() % 46);
}
Esempio n. 24
0
void
ServerRoom::initialize()
{
    if( (mChairCount <= 0) )
    {
        mLogger->error( "invalid room configuration!" );
        emit roomExpired();
        return;
    }

    for( unsigned int i = 0; i < mChairCount; ++i )
    {
        mPlayerList.append( 0 );
        mChairStateList.append( CHAIR_STATE_EMPTY );
    }

    mDraftPtr = new DraftType( mRoomConfig.draft_config(), mDispensers );
    mDraftPtr->addObserver( this );

    mRoomExpirationTimer = new QTimer( this );
    connect( mRoomExpirationTimer, &QTimer::timeout, this, &ServerRoom::roomExpired );

    // Start the room expiration timer immediately.  Normally the creating
    // client will join it immediately, but if that doesn't happen the room
    // needs to be cleaned up.
    mRoomExpirationTimer->start( CREATED_ROOM_EXPIRATION_SECONDS * 1000 );

    mDraftTimer = new QTimer( this );
    connect(mDraftTimer, SIGNAL(timeout()), this, SLOT(handleDraftTimerTick()));

    // Add in the bots.
    unsigned int botPlayerCount = mBotPlayerCount;
    if( botPlayerCount > mChairCount )
    {
        mLogger->warn( "more bots than chairs!" );
        botPlayerCount = mChairCount;
    }
    Logging::Config stupidBotLoggingConfig = mLoggingConfig.createChildConfig( "stupidbot" );

    unsigned int chairIndex = 0;
    for( unsigned int i = 0; i < botPlayerCount; ++i )
    {
        mLogger->debug( "Placing bot in chair {}", chairIndex );
        BotPlayer* bot = new StupidBotPlayer( chairIndex, stupidBotLoggingConfig );
        mBotList.append( bot );
        mPlayerList[chairIndex] = bot;
        mChairStateList[ chairIndex ] = CHAIR_STATE_READY;

        // The bot must observe the draft to get the observation callbacks.
        mDraftPtr->addObserver( bot );

        // Slot the bots into every other chair to be as fair as possible
        // to the real players.
        chairIndex += 2;
        if( chairIndex >= mChairCount )
        {
            // Wrap back around starting with chair 1.
            chairIndex = 1;
        }

    }

    if( botPlayerCount > 0 )
    {
        emit playerCountChanged( getPlayerCount() );
    }
}