void CreateBot(BotUpdate* update) { GameClient* client = update->GetClient(); auto effectComponent = std::make_unique<EffectComponent>(client->GetDispatcher()); update->AddComponent(std::move(effectComponent)); auto jump = std::make_unique<JumpComponent>(client->GetWorld(), 200); update->AddComponent(std::move(jump)); auto targeting = std::make_unique<TargetingComponent>(); update->AddComponent(std::move(targeting)); auto targetPlayer = std::make_shared<TargetPlayerAction>(client); std::shared_ptr<DecisionTreeNode> pathfindDecision = std::make_shared<RangeDecision<bool>>( targetPlayer, std::make_shared<WanderAction>(client), std::bind(&TargetPlayerAction::HasTarget, targetPlayer), true, true ); auto meleeAction = std::make_shared<MeleeAction>(client); auto tree = std::make_shared<RangeDecision<double>>( meleeAction, pathfindDecision, std::bind(&MeleeAction::DistanceToTarget, meleeAction), 0.0, 2.0 ); update->SetDecisionTree(tree); }
void GameHandler::completeServerChange(int id, const std::string &token, const std::string &address, int port) { for (NetComputers::const_iterator i = clients.begin(), i_end = clients.end(); i != i_end; ++i) { GameClient *c = static_cast< GameClient * >(*i); if (c->status == CLIENT_CHANGE_SERVER && c->character->getComponent<CharacterComponent>() ->getDatabaseID() == id) { MessageOut msg(GPMSG_PLAYER_SERVER_CHANGE); msg.writeString(token, MAGIC_TOKEN_LENGTH); msg.writeString(address); msg.writeInt16(port); c->send(msg); c->character->getComponent<CharacterComponent>()->disconnected( *c->character); delete c->character; c->character = nullptr; c->status = CLIENT_LOGIN; return; } } }
bool SelectItem(s32 id) { mc::inventory::Inventory* inventory = m_Client->GetInventory(); if (!inventory) return false; auto& hotbar = m_Client->GetHotbar(); auto slot = hotbar.GetCurrentItem(); if (slot.GetItemId() != id) { s32 itemIndex = inventory->FindItemById(id); std::cout << "Selecting item id " << id << std::endl; if (itemIndex == -1) { std::cout << "Not carrying item with id of " << id << std::endl; return false; } else { std::cout << "Item is in index " << itemIndex << std::endl; } s32 hotbarIndex = itemIndex - mc::inventory::Inventory::HOTBAR_SLOT_START; if (hotbarIndex >= 0) hotbar.SelectSlot(hotbarIndex); } return true; }
void GameSocket::OnRawData( const char *pData,size_t len,struct sockaddr *sa_from,socklen_t sa_len ) { struct sockaddr_in inc_addr; memcpy(&inc_addr,sa_from,sa_len); Ipv4Address theAddr(inc_addr); if (theAddr.IsValid() == false) return; string IPStr = theAddr.Convert(true); GClientList::iterator it = m_clients.find(IPStr); if (it != m_clients.end()) { GameClient *Client = it->second; if (Client->IsValid() == false) { DEBUG_LOG( format("Removing dead client [%1%]") % IPStr ); m_clients.erase(it); delete Client; } else { Client->HandlePacket(pData, len); } } else { m_clients[IPStr] = new GameClient(inc_addr, this); DEBUG_LOG(format ("Client connected [%1%], now have [%2%] clients") % IPStr % Clients_Connected()); m_clients[IPStr]->HandlePacket(pData, len); m_clients[IPStr]->InitializeWorld () ; } }
void CleanupBot(BotUpdate* update) { GameClient* client = update->GetClient(); client->RemoveComponent(Component::GetIdFromName(EffectComponent::name)); client->RemoveComponent(Component::GetIdFromName(JumpComponent::name)); client->RemoveComponent(Component::GetIdFromName(TargetingComponent::name)); }
int main(int argc, char** argv) { //MemoryDebug::isEnabled = true; try { GameClient gc; GASimulation gas; Mode mode = Mode_GA_Simulation; for(int i=0; i<argc; i++) { printf("arg\t%i:\t%s\n", i, argv[i]); } for(int i=0; i<argc; i++) { if( strcmp(argv[i], "/network") == 0 ) { mode = Mode_Network; } else if( strcmp(argv[i], "/targetIP") == 0 ) { i++; gc.targetIP = argv[i]; } else if( strcmp(argv[i], "/targetPort") == 0 ) { i++; gc.targetPort = argv[i]; } } switch( mode) { case Mode_Default: gc.run(); break; case Mode_Network: gc.run2(); break; case Mode_GA_Simulation: gas.run(); break; } } catch( char* ex ) { printf( "%s\n", ex ); getchar(); } //memoryDebug.debugPrint(); //MemoryDebug::isEnabled = false; return 1337; }
void GameHandler::handleTradeRequest(GameClient &client, MessageIn &message) { const int id = message.readInt16(); auto *characterComponent = client.character->getComponent<CharacterComponent>(); if (Trade *t = characterComponent->getTrading()) if (t->request(client.character, id)) return; Entity *q = findCharacterNear(client.character, id); if (!q || characterComponent->isBusy()) { client.send(MessageOut(GPMSG_TRADE_CANCEL)); return; } new Trade(client.character, q); // log transaction std::string str; str = "User requested trade with " + q->getComponent<BeingComponent>() ->getName(); accountHandler->sendTransaction(characterComponent->getDatabaseID(), TRANS_TRADE_REQUEST, str); }
void GameHandler::handleRaiseAttribute(GameClient &client, MessageIn &message) { auto *characterComponent = client.character->getComponent<CharacterComponent>(); const int attribute = message.readInt16(); AttribmodResponseCode retCode; retCode = characterComponent->useCharacterPoint(*client.character, attribute); MessageOut result(GPMSG_RAISE_ATTRIBUTE_RESPONSE); result.writeInt8(retCode); result.writeInt16(attribute); client.send(result); if (retCode == ATTRIBMOD_OK) { accountHandler->updateCharacterPoints( characterComponent->getDatabaseID(), characterComponent->getCharacterPoints(), characterComponent->getCorrectionPoints()); // log transaction std::stringstream str; str << "User increased attribute " << attribute; accountHandler->sendTransaction(characterComponent->getDatabaseID(), TRANS_ATTR_INCREASE, str.str()); } }
bool HasTarget() { mc::core::PlayerPtr targetPlayer = m_Client->GetPlayerManager()->GetPlayerByName(TargetPlayer); if (!targetPlayer) return false; mc::entity::EntityPtr entity = targetPlayer->GetEntity(); return entity != nullptr; }
void GameHandler::handleDisconnect(GameClient &client, MessageIn &message) { const bool reconnectAccount = (bool) message.readInt8(); MessageOut result(GPMSG_DISCONNECT_RESPONSE); result.writeInt8(ERRMSG_OK); // It is, when control reaches here if (reconnectAccount) { std::string magic_token(utils::getMagicToken()); result.writeString(magic_token, MAGIC_TOKEN_LENGTH); // No accountserver data, the client should remember that accountHandler->playerReconnectAccount( client.character->getDatabaseID(), magic_token); } accountHandler->sendCharacterData(client.character); // Done with the character, also handle possible respawn case client.character->disconnected(); delete client.character; client.character = 0; client.status = CLIENT_LOGIN; client.send(result); }
void GameHandler::handleLowerAttribute(GameClient &client, MessageIn &message) { const int attribute = message.readInt32(); AttribmodResponseCode retCode; retCode = client.character->useCorrectionPoint(attribute); MessageOut result(GPMSG_LOWER_ATTRIBUTE_RESPONSE); result.writeInt8(retCode); result.writeInt16(attribute); client.send(result); if (retCode == ATTRIBMOD_OK) { accountHandler->updateCharacterPoints( client.character->getDatabaseID(), client.character->getCharacterPoints(), client.character->getCorrectionPoints()); // log transaction std::stringstream str; str << "User decreased attribute " << attribute; accountHandler->sendTransaction(client.character->getDatabaseID(), TRANS_ATTR_DECREASE, str.str()); } }
void GameHandler::sendNpcError(GameClient &client, int id, const std::string &errorMsg) { MessageOut msg(GPMSG_NPC_ERROR); msg.writeInt16(id); msg.writeString(errorMsg, errorMsg.size()); client.send(msg); }
/// GameClient main function int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int /*nCmdShow*/) { CrashReporter::Init(_T("gameclient"), Filesystem().UserFolder() + c_pszCrashdumpFoldername); try { GameClient gc; gc.Start(); } catch (Exception& ex) { CString cszText; cszText.Format(_T("Arena ended with exception: %s"), ex.Message().GetString()); MessageBox(GetActiveWindow(), cszText, _T("Arena"), MB_OK); } return 0; }
void Act() override { mc::core::PlayerPtr targetPlayer = m_Client->GetPlayerManager()->GetPlayerByName(TargetPlayer); auto entity = targetPlayer->GetEntity(); auto targeting = GetActorComponent(m_Client, TargetingComponent); if (!targeting) return; targeting->SetTargetEntity(entity->GetEntityId()); targeting->SetTarget(mc::ToVector3i(entity->GetPosition())); }
void GameHandler::handleUnequip(GameClient &client, MessageIn &message) { const int itemInstance = message.readInt16(); if (!Inventory(client.character).unequip(itemInstance)) { MessageOut msg(GPMSG_SAY); msg.writeInt16(0); // From the server msg.writeString("Unable to unequip."); client.send(msg); } }
void GameCore::initializePlayers() { teamDM=(gmc->getCurrentRoom()->getGameType()==0?false:true); unsigned char clientTeam=(teamDM?gmc->getLocalClient()->getTeam():(gmc->getLocalClient()->getColor()==0?0:1)); std::map<unsigned int,GameClient*> clientMap=gmc->getCurrentRoom()->getClientMap(); std::map<unsigned int,GameClient*>::iterator iter=clientMap.begin(); GameClient* client; while(iter!=clientMap.end()) { client=iter->second; if(client!=gmc->getLocalClient()) createPlayer(client); iter++; } client=gmc->getLocalClient(); localPlayer=new Player(client->getID(),client->getName(),true,true,clientTeam,sceneManager); localPlayer->createVisual("SpaceMarine.mesh", Quaternion::IDENTITY, Ogre::Vector3(2, 2, 2), Ogre::Vector3(-100, -100, -500)); localPlayer->enablePhysics(dynamics); localPlayer->changePlayerColor(clientTeam); localPlayer->getAnimationController()->enableAnimation("Idle"); localPlayer->getAnimationController()->addIdleAnimation("Run","Idle"); localPlayer->getAnimationController()->enableAnimation("Run"); cameraController->setTarget(localPlayer->getSceneNode()); float cameraShift =-reader->getFieldValueAsDouble("CameraSettings", "camera-shift"); cameraController->moveCamera(cameraShift,0); cameraController->rotateCamera(90, 0); cameraController->rotateCamera(0, 15); gmc->requestNextSpawnPoint(); soundController->setListener(localPlayer->getSceneNode()); //ingameGUI->setGameType(InGameGUIHandler::TEAM_MATCH); this->ingameGUI->showItem(ItemType::IMMORTALITY); this->ingameGUI->showItem(ItemType::EAGLE_EYE); this->ingameGUI->showItem(ItemType::ONE_SHOT); }
bool GameWorld::canMoveTo( int x, int y, const GameClient& client, bool doMove ) { int x_map = x / MAP_OBJECT_WIDTH; int y_map = y / MAP_OBJECT_HEIGHT; std::cout <<abs( client.getCurrentCharacter()->position().x - x )<< "-" <<abs( client.getCurrentCharacter()->position().y - y )<< "-" <<_mapData( x_map, y_map ) << "\n"; bool canMove = ( abs( client.getCurrentCharacter()->position().x - x ) <= MAP_OBJECT_WIDTH && abs( client.getCurrentCharacter()->position().y - y ) <= MAP_OBJECT_HEIGHT && _mapData( x_map, y_map ) == WALKABLE ); // save new position if ( canMove == true && doMove == true ) { _mapData( client.getCurrentCharacter()->position().x / MAP_OBJECT_WIDTH , client.getCurrentCharacter()->position().y / MAP_OBJECT_HEIGHT ) = WALKABLE; _mapData( x_map , y_map ) = CHARACTER; } return canMove; }
void GameHandler::handlePartyInvite(GameClient &client, MessageIn &message) { MapComposite *map = client.character->getMap(); const int visualRange = Configuration::getValue("game_visualRange", 448); std::string invitee = message.readString(); if (invitee == client.character->getComponent<BeingComponent>()->getName()) return; for (CharacterIterator it(map->getWholeMapIterator()); it; ++it) { if ((*it)->getComponent<BeingComponent>()->getName() == invitee) { // calculate if the invitee is within the visual range auto *inviterComponent = client.character->getComponent<ActorComponent>(); auto *inviteeComponent = (*it)->getComponent<ActorComponent>(); const Point &inviterPosition = inviterComponent->getPosition(); const Point &inviteePosition = inviteeComponent->getPosition(); const int dx = std::abs(inviterPosition.x - inviteePosition.x); const int dy = std::abs(inviterPosition.y - inviteePosition.y); if (visualRange > std::max(dx, dy)) { MessageOut out(GCMSG_PARTY_INVITE); out.writeString(client.character ->getComponent<BeingComponent>()->getName()); out.writeString(invitee); accountHandler->send(out); return; } break; } } // Invitee was not found or is too far away MessageOut out(GPMSG_PARTY_INVITE_ERROR); out.writeString(invitee); client.send(out); }
void Act() override { mc::core::PlayerPtr targetPlayer = m_Client->GetPlayerManager()->GetPlayerByName(TargetPlayer); auto entity = targetPlayer->GetEntity(); auto physics = GetActorComponent(m_Client, PhysicsComponent); auto targeting = GetActorComponent(m_Client, TargetingComponent); ai::FaceSteering align(m_Client, entity->GetPosition(), 0.1, 1, 1); physics->ApplyRotation(align.GetSteering().rotation); //physics->ClearHorizontalVelocity(); Vector3d entityHeading = util::OrientationToVector(entity->GetYaw()); Vector3d target = entity->GetPosition() - entityHeading * 2; targeting->SetTarget(ToVector3i(target)); s64 time = util::GetTime(); if (time >= m_LastAttack + m_AttackCooldown) { Attack(entity); m_LastAttack = time; } }
void GameSocket::PruneDeadClients() { m_currTime = getTime(); // Do client cleanup for (GClientList::iterator it=m_clients.begin();it!=m_clients.end();) { GameClient *Client = it->second; if (!Client->IsValid() || (m_currTime - Client->LastActive()) >= 20) { if (!Client->IsValid()) DEBUG_LOG( format("Removing invalidated client [%1%]") % Client->Address() ); else DEBUG_LOG( format("Removing client due to time-out [%1%]") % Client->Address() ); m_clients.erase(it++); delete Client; } else { ++it; } } if ((m_currTime - m_lastCleanupTime) >= 5) { // Update player count if (m_lastPlayerCount != this->Clients_Connected()) { sDatabase.Execute(format("UPDATE `worlds` SET `numPlayers`='%1%' WHERE `name`='%2%' LIMIT 1") % this->Clients_Connected() % sGame.GetName() ); m_lastPlayerCount = this->Clients_Connected(); } m_lastCleanupTime = m_currTime; } }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QString serverAddr = ""; int serverPort = 0; ServerThread *server; StartupPage page; page.show(); page.exec(); if (page.exit) return 0; var isServer = page.isServer; qDebug() << (isServer ? "server" : "client"); if (isServer) { int timeLimit = defaultTimeLimit; QString initStatus = defaultInitStatus; bool whiteFirst = false; CustomBoard board; board.show(); board.exec(); initStatus = board.res; timeLimit = board.tl; whiteFirst = board.whiteFirst; ServerSettings settings; settings.show(); settings.exec(); serverPort = settings.portSelected; if (!~serverPort) return 0; server = new ServerThread(serverPort, timeLimit, initStatus, whiteFirst); server->start(); server->moveToThread(server); client.connectToServer(getCurrentInterfaceAddress().ip(), serverPort); Waiting waitingPage; QObject::connect(server, SIGNAL(onClientsConnected()), &waitingPage, SLOT(close())); waitingPage.show(); waitingPage.exec(); serverAddr = getCurrentInterfaceAddress().ip().toString(); } else { ConnectToServer conn; conn.show(); conn.exec(); serverAddr = conn.serverIp; serverPort = conn.serverPort; if (!~serverPort) return 0; client.connectToServer(QHostAddress(serverAddr), serverPort); Waiting waitingPage; QObject::connect(&client, SIGNAL(onConnected()), &waitingPage, SLOT(close())); waitingPage.show(); waitingPage.exec(); } MainWindow mw(&client); mw.show(); int rv = app.exec(); client.sock->disconnectFromHost(); return rv; }
//============================================================================ int main( int argc, char *argv[] ) { // I can't live without my precious printf's #ifdef WIN32 # ifndef NDEBUG AllocConsole(); SetConsoleTitle( L"ld15_cavern CONSOLE" ); freopen("CONOUT$", "w", stdout ); # endif #endif // make sure no vesion mismatch for protobuf GOOGLE_PROTOBUF_VERIFY_VERSION; // Initialize SDL if (SDL_Init( SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO ) < 0 ) { errorMessage( string("Unable to init SDL:") + SDL_GetError() ); exit(1); } // cheezy check for fullscreen Uint32 mode_flags = SDL_OPENGL; for (int i=1; i < argc; i++) { if (!stricmp( argv[i], "-fullscreen")) { mode_flags |= SDL_FULLSCREEN; } } if (SDL_SetVideoMode( 800, 600, 32, mode_flags ) == 0 ) { errorMessage( string("Unable to set video mode: ") + SDL_GetError() ) ; exit(1); } SDL_WM_SetCaption( "Spaceships in a Cave", NULL ); // seed rand srand( time(0) ); // initialize DevIL ilInit(); ilutRenderer( ILUT_OPENGL ); // Initialize enet if (enet_initialize() != 0) { errorMessage( "Unable to initialize networking." ); exit(1); } // clean up net stuff at exit atexit( enet_deinitialize ); // init game object GameClient *game = new GameClient(); //=====[ Main loop ]====== Uint32 ticks = SDL_GetTicks(), ticks_elapsed, sim_ticks = 0; while(!game->done()) { SDL_Event event; while (SDL_PollEvent( &event ) ) { switch (event.type ) { case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: game->done( true ); break; } // let the game handle it game->keypress( event.key ); break; case SDL_MOUSEMOTION: break; case SDL_MOUSEBUTTONDOWN: game->mouse( event.button ); break; case SDL_MOUSEBUTTONUP: game->mouse( event.button ); break; case SDL_QUIT: game->done( true ); break; } } // Timing ticks_elapsed = SDL_GetTicks() - ticks; ticks += ticks_elapsed; // fixed sim update sim_ticks += ticks_elapsed; while (sim_ticks > STEPTIME) { sim_ticks -= STEPTIME; //printf("update sim_ticks %d ticks_elapsed %d\n", sim_ticks, ticks_elapsed ); game->updateSim( (float)STEPTIME / 1000.0f ); } // redraw as fast as possible float dtRaw = (float)(ticks_elapsed) / 1000.0f; game->update( dtRaw ); game->redraw(); SDL_GL_SwapBuffers(); ReloadChangedTweakableValues(); } delete game; return 1; }
void ButtonContact::setButton( Noun * pNoun ) { ASSERT( pNoun != NULL ); m_Flags |= NOCLIP; m_Style = HAS_BACK | EFFECT_HIGHLIGHT | SMOOTH_LL; //m_Alpha = 0.75f; // set the window name to the same as our contact setName( pNoun->name() ); // set the noun m_Noun = pNoun; if ( WidgetCast<NounShip>( pNoun ) ) setIcon( WidgetCast<Material>( resource( NounShip::typeText( ((NounShip *)pNoun)->type() ) ) ) ); else if ( WidgetCast<NounPlanet>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "PLANET" ) ) ); else if ( WidgetCast<NounStar>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "STAR" ) ) ); else if ( WidgetCast<NounNebula>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "NEBULA" ) ) ); else if ( WidgetCast<NounAsteroid>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "ASTEROID" ) ) ); else if ( WidgetCast<NounTarget>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "TARGET" ) ) ); else if ( WidgetCast<NounJumpGate>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "JUMPGATE" ) ) ); else if ( WidgetCast<NounProjectile>( pNoun ) ) setIcon( WidgetCast<Material>( resource( "PROJECTILE" ) ) ); else setIcon( WidgetCast<Material>( resource( "UNKNOWN" ) ) ); // determine if this contact is an objective! GameDocument * pDoc = (GameDocument *)document(); ASSERT( pDoc ); GameContext * pContext = pDoc->context(); ASSERT( pContext ); GameClient * pClient = pDoc->client(); ASSERT( pClient ); int myFaction = pDoc->factionId(); m_IsObjective = false; for(int i=0;i<pContext->conditionCount();i++) { const GameContext::Condition & condition = pContext->conditionN( i ); for(int j=0;j<condition.objectives.size();j++) if ( condition.objectives[j].noun == m_Noun->key() && condition.objectives[j].factionId == myFaction ) { m_IsObjective = true; m_Objective = (ObjectiveType)condition.objectives[j].type; break; } if ( m_IsObjective ) break; } if ( pNoun->userId() != 0 ) { Group * pGroup = pClient->group(); if ( pGroup != NULL ) { m_bGroupLeader = pGroup->isLeader( pNoun->userId() ); m_bGroupPending = pGroup->isPending( pNoun->userId() ); } } // set the tool tip CharString tip( pNoun->name() ); if ( m_IsObjective ) tip += CharString().format(" / Objective: %s", GameContext::objectiveText( m_Objective ) ); setTip( tip ); }
void GameHandler::sendTo(Character *beingPtr, MessageOut &msg) { GameClient *client = beingPtr->getClient(); assert(client && client->status == CLIENT_CONNECTED); client->send(msg); }