bool ClientLobbyRoomProtocol::notifyEventAsynchronous(Event* event) { assert(m_setup); // assert that the setup exists if (event->getType() == EVENT_TYPE_MESSAGE) { const NetworkString &data = event->data(); assert(data.size()); // assert that data isn't empty uint8_t message_type = data[0]; if (message_type == 0x03 || message_type == 0x06) return false; // don't treat the event event->removeFront(1); Log::info("ClientLobbyRoomProtocol", "Asynchronous message of type %d", message_type); if (message_type == 0x01) // new player connected newPlayer(event); else if (message_type == 0x02) // player disconnected disconnectedPlayer(event); else if (message_type == 0x04) // start race startGame(event); else if (message_type == 0x05) // start selection phase startSelection(event); else if (message_type == 0x80) // connection refused connectionRefused(event); else if (message_type == 0x81) // connection accepted connectionAccepted(event); else if (message_type == 0x82) // kart selection refused kartSelectionRefused(event); else if (message_type == 0xc0) // vote for major mode playerMajorVote(event); else if (message_type == 0xc1) // vote for race count playerRaceCountVote(event); else if (message_type == 0xc2) // vote for minor mode playerMinorVote(event); else if (message_type == 0xc3) // vote for track playerTrackVote(event); else if (message_type == 0xc4) // vote for reversed mode playerReversedVote(event); else if (message_type == 0xc5) // vote for laps playerLapsVote(event); return true; } // message else if (event->getType() == EVENT_TYPE_CONNECTED) { return true; } // connection else if (event->getType() == EVENT_TYPE_DISCONNECTED) // means we left essentially { NetworkManager::getInstance()->removePeer(m_server); m_server = NULL; NetworkManager::getInstance()->disconnected(); m_listener->requestTerminate(this); NetworkManager::getInstance()->reset(); // probably the same as m_server NetworkManager::getInstance()->removePeer(event->getPeer()); return true; } // disconnection return false; } // notifyEventAsynchronous
void acceptPlayer() { int fd; Player * p; Message mes; if ((fd = accept(srv.ld, NULL, NULL)) == -1) { merror("accept"); endWork(EXIT_FAILURE); } p = newPlayer(fd); p->pid = srv.nextPid++; addNilPlayer(p); mes.sndr_t = O_PLAYER; mes.sndr.player = p; mes.rcvr_t = O_SERVER; mes.type = MEST_PLAYER_JOIN_SERVER; mes.len = 0; mes.data = NULL; sendMessage(&mes); mes.sndr_t = O_SERVER; mes.rcvr_t = O_PLAYER; mes.rcvr.player = p; mes.type = MEST_PLAYER_PID; mes.len = 0; mes.data = NULL; sendMessage(&mes); }
void create(uint16_t x, uint16_t y) { map_width = x; map_height = y; Terrain::create(x, y); Terrain::addWater(); FogOfWar::create(x, y); for(auto& p: _players) { if(p != nullptr) p->resetVision(); } //add camera camera.reset(new Camera(h3dFindResource(H3DResTypes::Pipeline, "general_p.xml"))); camera->center(8.0, 0.0, 8.0); //add a light //FogOfWar::insertLightSource(8., 8., 6.); _time_lapsed = 0; FogOfWar::clear(); //minor internals _next_player = 1; newPlayer(); _active = false; }
void AI_Manager::newAI(string brName, int AIType) { if(newPlayer(brName, AIType)) { for(int i = getNumDiv(); i >= -1; i--) { int round; if(i != FINALS) { round = getMaxRounds(); } else { round = getFinalRounds(); } for(int j = round; j > 0; j--) { int games = 1 << (j-1); for(int k = 0; k < games; k++) { selectTeamInBracket(i,k,j); if(selectedTeam) { Team *team1 = selectedTeam; selectOpponentInBracket(i,k,j); Team *team2 = selectedTeam; double prob; switch(AIType) { case 1: prob = compute->computeProbDif(team1, team2); break; case 2: prob = compute->computeProb(team1, team2); break; case 3: prob = compute->computeProbTeam(team1, team2); break; default: prob = .5; } int cutoff = (int)(prob * MARGIN +.5); int decision = (int)((double)MARGIN*rand()/(RAND_MAX + 1.0)); if(decision < cutoff) { makePick(i,k,j,true); } else { makePick(i,k,j,false); } } } } } } selectedTeam = NULL; }
void Server::newConnectionHandler() { qDebug() << "New connection!"; QSharedPointer<PlayerSocket> newPlayer(new PlayerSocket(QSharedPointer<QTcpSocket>(server.nextPendingConnection()), this)); players.insert(newPlayer->getKey(), newPlayer); }
void Simulation::newPlayer(std::string name, Agent *agent) { const double safety = 0.1; std::uniform_real_distribution<double> x(rules.arena_size.x * safety, rules.arena_size.x * (1 - safety)); std::uniform_real_distribution<double> y(rules.arena_size.y * safety, rules.arena_size.y * (1 - safety)); std::uniform_real_distribution<double> rot(0, 2 * M_PI); newPlayer(name, agent, {x(generator), y(generator)}, rot(generator)); }
void DownloadManager::downloadFinished( QNetworkReply *reply ) { QMutexLocker locker( &mutex ); QUrl url = reply->url(); if (reply->error()) { //emit critical( QString::fromUtf8( "ページ(" ) + url.toEncoded().constData() + //QString::fromUtf8( ")を取得できませんでした: " ) + qPrintable( reply->errorString() ) ); } else { QString urlStr = url.toString(); if ( !reread && urlStr.startsWith( "http://www.google.co.jp/" ) ) { QString page = QString::fromUtf8( reply->readAll().constData() ); QString rx = "http://cgi2.nhk.or.jp/e-news/swfp/video_player(?:_wide)?.swf.type=real&m_name=([^\"]*)"; QRegExp regexp( rx, Qt::CaseInsensitive ); QList<QString> tempList; int pos = 0; while ( ( pos = regexp.indexIn( page, pos ) ) != -1) { if ( !flvList.contains( regexp.cap( 1 ) ) ) tempList << regexp.cap( 1 ); pos += regexp.matchedLength(); } QRegExp newPlayer( VIDEO_PLAYER_WIDE ); if ( newPlayer.indexIn( urlStr, 0 ) != -1 ) flvList << tempList; else flvListBefore20100323 << tempList; if ( tempList.count() >= SEARCH_AT_ONCE ) { QRegExp prefix( "^(.*&start=)(\\d+)$", Qt::CaseInsensitive ); if ( prefix.indexIn( urlStr, 0 ) != -1 ) { QString cap1 = prefix.cap( 1 ); int cap2 = prefix.cap( 2 ).toInt(); QUrl url( cap1 + QString::number( cap2 + SEARCH_AT_ONCE ) ); QNetworkRequest request( url ); QNetworkReply* reply = manager.get( request ); currentDownloads.append( reply ); } } } else { QString page( reply->readAll() ); QString rx = reread ? "mp3player.swf.type=real&m_name=([^&\"]*)" : "video_player_wide.swf.type=real&m_name=([^\"]*)"; QRegExp regexp( rx, Qt::CaseInsensitive ); if ( regexp.indexIn( page ) > -1 && !flvList.contains( regexp.cap( 1 ) ) ) flvList << regexp.cap( 1 ); } } currentDownloads.removeAll(reply); reply->deleteLater(); if (currentDownloads.isEmpty()) { manager.disconnect(); eventLoop.exit(); } }
foreach (PollingPlayerFactory* factory, m_polledFactories) { if (factory->exists()) { Player::Ptr player = factory->create(); if (!player.isNull()) { m_players.insert(player); m_polledFactories.remove(factory); m_usedFactories.insert(factory); emit newPlayer(player); } else { kWarning() << "Failed to create a player"; } } }
void PlayerSetupDialog::setPlayerList(PlayerConnectionList *list) { m_playerList = list; ui->playerListview->setModel(list); if(list->size() > 0) { ui->playerListview->setCurrentIndex(list->index(0,0)); setCurrentPlayer(list->at(0)); } else newPlayer(); }
void Configuring::Impl::playerAdded( const Message<MessageType::playerAdded>& netMessage ) { RemotePlayer newPlayer(netMessage.payload()); bool inserted = remotePlayers().insert(newPlayer).second; if (!inserted) { parent_->context<Machine>().messageHandler().message( utility::Verbosity::error, "duplicate player added" ); } refreshRemotePlayers(); }
/// Requests to join the game are handled here. /// inputData - Command data /// Return - Whether we did anything here (T/F) bool ParlourBBGame::CmdJoin(QueueData &inputData) { std::ostringstream sout; /// Streeeeeeam~ /// Iterate through our playes, and see if they haven't already joined. for (QVector<BBPlayerData>::iterator readList = players.begin(); readList != players.end(); readList++) { if (readList->Name() == inputData.getNick()) { /// We found that this player already joined; don't let them join again. sout << (*readList) << "\0034, you've already joined!"; AddToSendQueue(sout); return false; } } /// This game takes a maximum of ten players. Don't allow any more than that. if (players.size() == 10) { sout << "\00308,01" << inputData.getNick() << "\0034, the game is full!"; AddToSendQueue(sout); return false; } /// Let's create a player and pop them onto the player vector. { BBPlayerData newPlayer(inputData.getNick()); players.push_back(newPlayer); sout << players.back() << " has joined the game!"; AddToSendQueue(sout); } /// If we have four players, let the owner know privately that the game can start. if (players.size() == 4) { AddToSendQueue("Game is ready. You may now \002start\002 the game, or wait for more players (max 10).", MSG_NOTICE, owner); } /// If we have ten players, let the channel know the game is full. if (players.size() == 10) { sout << "\0034The game is now full. \0038,1" << owner << "\003, \002start\002 the game!"; AddToSendQueue(sout); } return true; }
void PlayerSetupDialog::setupUI() { connect(ui->addPlayerBtn, SIGNAL(clicked()), this, SLOT(newPlayer())); connect(ui->removePlayerBtn, SIGNAL(clicked()), this, SLOT(removePlayer())); connect(ui->newSubviewBtn, SIGNAL(clicked()), this, SLOT(newSubview())); connect(ui->delSubviewBtn, SIGNAL(clicked()), this, SLOT(removeSubview())); connect(ui->testConnectionBtn, SIGNAL(clicked()), this, SLOT(testConnection())); connect(ui->connectBtn, SIGNAL(clicked()), this, SLOT(connectPlayer())); connect(ui->autoconnectBox, SIGNAL(toggled(bool)), this, SLOT(autoconBoxChanged(bool))); connect(ui->playerListview, SIGNAL(activated(const QModelIndex &)), this, SLOT(playerSelected(const QModelIndex &))); connect(ui->playerListview, SIGNAL(clicked(const QModelIndex &)), this, SLOT(playerSelected(const QModelIndex &))); connect(ui->subviewListview, SIGNAL(activated(const QModelIndex &)), this, SLOT(subviewSelected(const QModelIndex &))); connect(ui->subviewListview, SIGNAL(clicked(const QModelIndex &)), this, SLOT(subviewSelected(const QModelIndex &))); connect(ui->aphaMaskBrowseBtn, SIGNAL(clicked()), this, SLOT(alphamaskBrowse())); connect(ui->keyTLx, SIGNAL(valueChanged(int)), this, SLOT(subviewTopLeftXChanged(int))); connect(ui->keyTLy, SIGNAL(valueChanged(int)), this, SLOT(subviewTopLeftYChanged(int))); connect(ui->keyTRx, SIGNAL(valueChanged(int)), this, SLOT(subviewTopRightXChanged(int))); connect(ui->keyTRy, SIGNAL(valueChanged(int)), this, SLOT(subviewTopRightYChanged(int))); connect(ui->keyBLx, SIGNAL(valueChanged(int)), this, SLOT(subviewBottomLeftXChanged(int))); connect(ui->keyBLy, SIGNAL(valueChanged(int)), this, SLOT(subviewBottomLeftYChanged(int))); connect(ui->keyBRx, SIGNAL(valueChanged(int)), this, SLOT(subviewBottomRightXChanged(int))); connect(ui->keyBRy, SIGNAL(valueChanged(int)), this, SLOT(subviewBottomRightYChanged(int))); connect(ui->outputX, SIGNAL(valueChanged(int)), this, SLOT(screenXChanged(int))); connect(ui->outputY, SIGNAL(valueChanged(int)), this, SLOT(screenYChanged(int))); connect(ui->outputWidth, SIGNAL(valueChanged(int)), this, SLOT(screenWChanged(int))); connect(ui->outputHeight, SIGNAL(valueChanged(int)), this, SLOT(screenHChanged(int))); connect(ui->viewportX, SIGNAL(valueChanged(int)), this, SLOT(viewportXChanged(int))); connect(ui->viewportY, SIGNAL(valueChanged(int)), this, SLOT(viewportYChanged(int))); connect(ui->viewportWidth, SIGNAL(valueChanged(int)), this, SLOT(viewportWChanged(int))); connect(ui->viewportHeight, SIGNAL(valueChanged(int)), this, SLOT(viewportHChanged(int))); connect(ui->optIgnoreAR, SIGNAL(toggled(bool)), this, SLOT(ignoreArBoxChanged(bool))); connect(ui->aphaMaskBrowseBtn, SIGNAL(clicked()), this, SLOT(alphamaskBrowse())); connect(ui->alphaMaskFile, SIGNAL(textChanged(QString)), this, SLOT(showAlphaMaskPreview(QString))); connect(ui->brightnessResetBtn, SIGNAL(clicked()), this, SLOT(brightReset())); connect(ui->contrastResetBtn, SIGNAL(clicked()), this, SLOT(contReset())); connect(ui->hueResetBtn, SIGNAL(clicked()), this, SLOT(hueReset())); connect(ui->saturationResetBtn, SIGNAL(clicked()), this, SLOT(satReset())); }
//the standard main method, for the blackjack game void main() { srand(time(NULL)); card * deckOfCards = initializeGame(); player * p = newPlayer(); dealer * d = malloc(sizeof(dealer)); // char * keepPlaying; // while () { playNewHand(p, d, deckOfCards); // } // cashOut(); // //free deck and player // return 1; }
bool ClientLobbyRoomProtocol::notifyEventAsynchronous(Event* event) { assert(m_setup); // assert that the setup exists if (event->getType() == EVENT_TYPE_MESSAGE) { NetworkString &data = event->data(); assert(data.size()); // assert that data isn't empty uint8_t message_type = data.getUInt8(); Log::info("ClientLobbyRoomProtocol", "Asynchronous message of type %d", message_type); switch(message_type) { case LE_NEW_PLAYER_CONNECTED: newPlayer(event); break; case LE_PLAYER_DISCONNECTED : disconnectedPlayer(event); break; case LE_START_RACE: startGame(event); break; case LE_START_SELECTION: startSelection(event); break; case LE_CONNECTION_REFUSED: connectionRefused(event); break; case LE_CONNECTION_ACCEPTED: connectionAccepted(event); break; case LE_KART_SELECTION_REFUSED: kartSelectionRefused(event); break; case LE_VOTE_MAJOR : playerMajorVote(event); break; case LE_VOTE_RACE_COUNT: playerRaceCountVote(event); break; case LE_VOTE_MINOR: playerMinorVote(event); break; case LE_VOTE_TRACK: playerTrackVote(event); break; case LE_VOTE_REVERSE: playerReversedVote(event); break; case LE_VOTE_LAPS: playerLapsVote(event); break; } // switch return true; } // message else if (event->getType() == EVENT_TYPE_DISCONNECTED) { // This means we left essentially. // We can't delete STKHost from this thread, since the main // thread might still test if STKHost exists and then call // the ProtocolManager, which might already have been deleted. // So only signal that STKHost should exit, which will be tested // from the main thread. STKHost::get()->requestShutdown(); return true; } // disconnection return false; } // notifyEventAsynchronous
void newGame() { game.jackpot = 0; printf("Choose your game mode :\n1 - Chararacter mode\n2 - Symbole mode\n"); game.mode = getIntegerLesserThan(2); clearScreen(); newPlayer(); while(game.player.wantToPlay == 1) { betting(); clearScreen(); if(game.isGodMode == 1) { game.player.profit = getProfitFromResult(0); } else { launchGambling(); game.player.profit = getProfitFromResult(getResult()); } updatePlayerBalance(); printResult(); replay(); } }
void PollingWatcher::addFactory(PollingPlayerFactory* factory) { if (factory->exists()) { Player::Ptr player = factory->create(); if (!player.isNull()) { m_players.insert(player); m_usedFactories.insert(factory); emit newPlayer(player); } else { kWarning() << "Failed to create a player"; m_polledFactories.insert(factory); } } else { m_polledFactories.insert(factory); } if (!m_timer) { m_timer = new QTimer(this); m_timer->setInterval(5000); connect(m_timer, SIGNAL(timeout()), this, SLOT(checkPlayers())); m_timer->start(); } }
void receiveMessage(int mss) { int type = mss & 0x03; int id_player = ((mss & 0xe0) >> 5)+1; int status = 0; int dpl = 0; switch(type) { case MOVE: dpl = (mss & 0x0c) >> 2; movePlayer(id_player,dpl); break; case CONNECT: status = (mss & 0x04) >> 3; if(status) leavePlayer(id_player); else newPlayer(id_player); break; default: break; } }
/*notice the default arguments for main. SDL expects main to look like that, so don't change it*/ int main(int argc, char *argv[]) { // SDL_Surface *temp = NULL; int done;// the player const Uint8 *keys;// the player /* This section starts by loading the BG as a surface and converting it to a texture This will have to change if I can manage to scroll the trexture arond the player*/ SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_RESIZABLE, &mainWindow, &renderer); SDL_SetWindowTitle(mainWindow, "Nitro Hotness"); if( TTF_Init() == -1 ) { return false; } if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 ) { return false; } InitSpriteSystem(); InitEntitySystem(entityMax); map mymap = setWorld(); ObstacleList ol = newObstacleList(); mew = newPlayer(); Obstacle Doh = newObstacle(0); Road_M Path = initRoad(); AI rival = new_AI(); GUI HUD = InitGUI(); mew.position=0; done = 0; //The music that will be played Mix_Music *music = NULL; Mix_Chunk *buzz = NULL; buzz = Mix_LoadWAV( "sfx/buzz.wav" ); readSave(&mew); showTitle(); showMain(); oldTime = 0; currentTime = 0; mytime = 0; do { oldTime = 0; currentTime = 0; mytime = 0; if( Mix_PlayingMusic() == 0 ) { //Play the music if( Mix_PlayMusic( level_music, -1 ) == -1 ) { return 1; } } SDL_Event e; SDL_PollEvent( &e ); if(&e) { //User requests quit if( e.type == SDL_QUIT ) { done = 1; } //user presses enter to go to next menu //User presses a key else if( e.type == SDL_KEYDOWN ) { //Select surfaces based on key press switch( e.key.keysym.sym ) { case SDLK_LEFT: // slog("left is down"); mew.playerX += 3; mew.accel = (mew.accel - .000001); break; case SDLK_RIGHT: // slog("right is down"); mew.playerX -= 3; mew.accel = (mew.accel - .000001); break; case SDLK_UP: // slog("up is down"); mew.accel = (mew.accel + .00007); Mix_PlayChannel( 1, buzz, 0 ); break; case SDLK_DOWN: // slog("down is down"); mew.accel = (mew.accel - .00008); break; } } else if( e.type == SDL_KEYUP ) { //Select surfaces based on key press switch( e.key.keysym.sym ) { case SDLK_RETURN : if(mew.done ==1) { Mix_HaltMusic(); if(GP == 1) { mew.done=0; lvl++; //slog("new level is %i",lvl); mew.position = 0; rival.position =0; setWorld(); Results(mew.rank,lvl); } else if (GP == 0) { mew.done=0; mew.position = 0; rival.position =0; levelSelect(); } } else { slog("too soon"); } case SDLK_LEFT: // slog("left is up"); e.type = SDLK_CLEAR; break; case SDLK_RIGHT: // slog("right is up"); e.type = SDLK_CLEAR; break; case SDLK_UP: // slog("up is up"); mew.accel = (mew.accel - .001); Mix_HaltChannel(1); e.type = SDLK_CLEAR; break; case SDLK_DOWN: // slog("down is up"); mew.accel = 0; e.type = SDLK_CLEAR; break; default: //slog("simple decel"); mew.accel = (mew.accel-0.00001); break; } } if(mew.position > rival.position) { mew.rank = 1 ; } else if( rival.position > mew.position ) { mew.rank = 2 ; } SDL_RenderClear(renderer); DrawBG(BG1,BG2); roadUpdate(Path,mymap,mew); roadDraw(Path,mymap,&mew); roadFetch(Path,mymap,&mew); checkForObstacles(ol , &mew, Doh); update_AI(&rival, &mew); UpdatePlayer(&mew); DrawGui(HUD,mew); NextFrame(); keys = SDL_GetKeyboardState(NULL); if(keys[SDL_SCANCODE_ESCAPE]) { done = 1; } } }while(!done); //Free the sound effects //Free the music Mix_FreeMusic( music ); CloseEntitySystem(); CloseSpriteSystem(); exit(0); /*technically this will end the program, but the compiler likes all functions that can return a value TO return a value*/ return 0; }
/** *\fn int main(int argc, char *argv[]) * Main *\param[in,out] argc argc *\param[in,out] argv argv */ int main(int argc, char *argv[]) { SDL_Surface *screen = NULL; int go = 1; int ret,ret1, ret2 = 0, ret3, ret4; char level_name[MAX_SIZE_FILE_NAME]; char player_name[MAX_SIZE_FILE_NAME]; int nb_lvl; /*sound*/ Sound *sound_system; sound_system = createSound(); /*keyboard config*/ SDLKey kc[NB_KEY-1]; /*input*/ Input in; SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_JOYSTICK); Player *current_player; current_player = (Player *)malloc(sizeof(Player)); /*screen initialization*/ screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); initInput(&in); /*configurations loading */ loadSoundOptions("configuration/sound.conf",sound_system); SDL_WM_SetCaption("Super Martin", NULL); //window name SDL_ShowCursor(SDL_DISABLE); //delete the mouse while (go) //main loop { if(titleMenu(screen,&go,sound_system, &in)) { while( (ret3 = menuPlayers(screen, player_name, &go, sound_system, &in)) != -1 && go) { switch(ret3) { case -1: break; case 2 : ret2 = newPlayer(screen, player_name, sound_system, &go); if(ret2 == 1) { current_player->levelMax = 1; current_player->nbCoins = 0; current_player->nbLifes = 3; current_player->nbProjectile = 5; savePlayer("save/.save", player_name, current_player); loadInputOptions("default",kc,&in); saveInputOptions(player_name, kc, &in); } else break; case 1 : loadPlayer("save/.save", player_name, current_player); loadInputOptions(player_name,kc,&in); while(go && (ret1 = mainMenu(screen,&go,sound_system, player_name, &in)) != -1) { switch(ret1) { case -1: break; case 0: while( (ret4 = menuLevel(screen,level_name,sound_system, player_name, current_player, &go, &nb_lvl, &in)) != -1 && go) { while(play(screen,level_name,sound_system,&go,kc, &in, current_player, player_name, ret4+1, nb_lvl) && go); } break; case 1 : save(screen, "save/.save", player_name, current_player, &go); loadPlayer("save/.save", player_name, current_player); break; case 2 : while((ret = optionMenu(screen,&go,sound_system,kc, &in)) != -1 && go) { switch(ret) { case -1: break; case 0: soundOptions(screen,&go,sound_system, &in); break; case 1: keyBoardOptions(screen,&go,kc,&in,player_name); break; default:; } } break; case 3 : deletePlayer(screen, "save/players", player_name); go = 0; break; default: ; } } go = 1; break; default : ; } } } SDL_FillRect(screen,NULL,SDL_MapRGB(screen->format,255,255,255)); //clear screen SDL_Flip(screen); } freeSound(sound_system); free((void*)current_player); freeInput(&in); SDL_Quit(); return EXIT_SUCCESS; }
void launchGame() { if (RUNUI) { // On charge le systeme d'affichage et le systeme de son if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) { fprintf(stderr, "Erreur dans le chargement de la SDL\n"); SDL_Quit(); // On arrete la SDL pthread_exit(NULL); } atexit(SDL_Quit); SDL_Event event; // On cree notre screen de 640x360 en 32bit couleur charge sur la carte graphiqe en mode double buffering SDL_Surface* screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF ); if (screen == NULL) { fprintf(stderr, "Impossible de charger le mode video : %s\n", SDL_GetError()); SDL_Quit(); // On arrete la SDL pthread_exit(NULL); } // On titre notre fenetre SDL_WM_SetCaption("Super Unicorn Run", NULL); // On active la repetition de touches. On attend 10ms avant d'activer la repetition et on renouvelle l'event toutes les 10ms SDL_EnableKeyRepeat(10, 10); /* serveur est le nom (ou l'adresse IP) auquel le client va acceder */ /* service le numero de port sur le serveur correspondant au */ /* service desire par le client */ /* protocole le protocole qui sera utilise pour la communication */ if (init(id_client,nbr_player,screen) == EXIT_FAILURE) { printf("Fail to init game\n"); SDL_Quit(); // On arrete la SDL pthread_exit(NULL); } while(run) { // Gestionnaire d'evenements SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: //mutex pour run run = 0; // envoie du message au autres client que celui-ci se ferme sendMessage(getIdPlayer(),UP,CONNECT); break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_UP: // On appuie sur la touche haut movePlayer(getIdPlayer(),UP); sendMessage(getIdPlayer(),UP,MOVE); break; case SDLK_DOWN: // On appuie sur la touche bas movePlayer(getIdPlayer(),DOWN); sendMessage(getIdPlayer(),DOWN,MOVE); break; case SDLK_RIGHT: // On appuie sur la touche droite movePlayer(getIdPlayer(),RIGHT); sendMessage(getIdPlayer(),RIGHT,MOVE); break; case SDLK_LEFT: // On appuie sur la touche gauche movePlayer(getIdPlayer(),LEFT); sendMessage(getIdPlayer(),LEFT,MOVE); break; // Event de test pour l'ajout et la suppression de joueur. case SDLK_a: leavePlayer(2); break; case SDLK_z: newPlayer(2); break; } break; } // On efface l'ecran SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 255, 0)); // On place les joueurs visible sur l'ecran int i; Player **linkedPlayer = getLinkedPlayer(); for(i=0;i<getNbrPlayer();i++) { if (linkedPlayer[i]->visible == 1) { SDL_BlitSurface(linkedPlayer[i]->image, NULL, screen, linkedPlayer[i]->position); } } // On met a jour l'affichage SDL_Flip(screen); } SDL_Quit(); // On arrete la SDL pthread_exit(NULL); } return EXIT_SUCCESS; }
void Session::attachSignals() { // zoneManager -> group Manager connect(m_zoneMgr, SIGNAL(playerProfile(const charProfileStruct*)), m_groupMgr, SLOT(player(const charProfileStruct*))); // spawnShell -> group Manager connect(m_spawnShell, SIGNAL(addItem(const Item*)), m_groupMgr, SLOT(addItem(const Item*))); connect(m_spawnShell, SIGNAL(delItem(const Item*)), m_groupMgr, SLOT(delItem(const Item*))); connect(m_spawnShell, SIGNAL(killSpawn(const Item*, const Item*, uint16_t)), m_groupMgr, SLOT(killSpawn(const Item*))); // zone Manager -> filter Manager connect(m_zoneMgr, SIGNAL(zoneBegin(const QString&)), m_filterMgr, SLOT(loadZone(const QString&))); connect(m_zoneMgr, SIGNAL(zoneEnd(const QString&)), m_filterMgr, SLOT(loadZone(const QString&))); connect(m_zoneMgr, SIGNAL(zoneChanged(const QString&)), m_filterMgr, SLOT(loadZone(const QString&))); connect(m_zoneMgr, SIGNAL(zoneBegin(const ClientZoneEntryStruct*, size_t, uint8_t)), m_messageShell, SLOT(zoneEntryClient(const ClientZoneEntryStruct*))); connect(m_zoneMgr, SIGNAL(zoneChanged(const zoneChangeStruct*, size_t, uint8_t)), m_messageShell, SLOT(zoneChanged(const zoneChangeStruct*, size_t, uint8_t))); connect(m_zoneMgr, SIGNAL(zoneBegin(const QString&)), m_messageShell, SLOT(zoneBegin(const QString&))); connect(m_zoneMgr, SIGNAL(zoneEnd(const QString&, const QString&)), m_messageShell, SLOT(zoneEnd(const QString&, const QString&))); connect(m_zoneMgr, SIGNAL(zoneChanged(const QString&)), m_messageShell, SLOT(zoneChanged(const QString&))); connect(m_zoneMgr, SIGNAL(playerProfile(const charProfileStruct*)), m_messageShell, SLOT(player(const charProfileStruct*))); connect(m_player, SIGNAL(setExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)), m_messageShell, SLOT(setExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))); connect(m_player, SIGNAL(newExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)), m_messageShell, SLOT(newExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))); connect(m_player, SIGNAL(setAltExp(uint32_t, uint32_t, uint32_t, uint32_t)), m_messageShell, SLOT(setAltExp(uint32_t, uint32_t, uint32_t, uint32_t))); connect(m_player, SIGNAL(newAltExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)), m_messageShell, SLOT(newAltExp(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))); connect(m_spawnShell, SIGNAL(addItem(const Item*)), m_messageShell, SLOT(addItem(const Item*))); connect(m_spawnShell, SIGNAL(delItem(const Item*)), m_messageShell, SLOT(delItem(const Item*))); connect(m_spawnShell, SIGNAL(killSpawn(const Item*, const Item*, uint16_t)), m_messageShell, SLOT(killSpawn(const Item*))); // connect the SpellShell slots to ZoneMgr signals connect(m_zoneMgr, SIGNAL(zoneChanged(const QString&)), m_spellShell, SLOT(zoneChanged())); // connect the SpellShell slots to SpawnShell signals connect(m_spawnShell, SIGNAL(killSpawn(const Item*, const Item*, uint16_t)), m_spellShell, SLOT(killSpawn(const Item*))); // connect the SpellShell slots to Player signals connect(m_player, SIGNAL(newPlayer()), m_spellShell, SLOT(clear())); connect(m_player, SIGNAL(buffLoad(const spellBuff *)), m_spellShell, SLOT(buffLoad(const spellBuff *))); connect(m_zoneMgr, SIGNAL(playerProfile(const charProfileStruct*)), m_player, SLOT(player(const charProfileStruct*))); }
/** * @brief Starts the game, connecting libraries and UI */ int cruceGameLogic() { setlocale(LC_ALL, ""); initscr(); cbreak(); if (has_colors() == FALSE) { endwin(); printf("Your terminal does not support colors!"); return 0; } start_color(); init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_YELLOW, COLOR_BLACK); init_pair(4, COLOR_BLUE, COLOR_BLACK); init_pair(5, COLOR_MAGENTA, COLOR_BLACK); init_pair(7, COLOR_WHITE, COLOR_BLACK); refresh(); welcomeMessage(); int limitScore = getScoreLimit(); int noOfPlayers = getNoOfPlayers(); struct Game *game = game_createGame(limitScore); for (int i = 0; i < noOfPlayers; i++) { int err; while ((err = game_addPlayer(newPlayer(i + 1), game)) == DUPLICATE_NAME) printw("The player's name have to be unique\n"); if (err != 0) printw("ERROR: game_addPlayer() %d\n", err); } formTeams(game); for (int i = 0; !game_winningTeam(game); i++) { game_arrangePlayersRound(game, i % MAX_GAME_PLAYERS); struct Deck *deck = deck_createDeck(); deck_deckShuffle(deck); round_distributeDeck(deck, game->round); clear(); refresh(); for (int i = 0; i < game->numberPlayers; i++) { getBid(game, i); clear(); refresh(); } displayBids(game, game->numberPlayers); refresh(); sleep(2); clear(); refresh(); struct Player *bidWinner = round_getBidWinner(game->round); int first = round_findPlayerIndexRound(bidWinner, game->round); for (int i = 0; team_hasCards(game->players[0]); i++) { round_arrangePlayersHand(game->round, first); for (int j = 0; j < game->numberPlayers; j++) { WINDOW *scoreTableWindow = newwin(11, 49, 0, 30); #ifdef BORDERS box(scoreTableWindow, 0, 0); #endif printScore(game, game->round, scoreTableWindow); wrefresh(scoreTableWindow); delwin(scoreTableWindow); displayCardsAndPickCard(game, j); clear(); refresh(); } struct Player *handWinner = round_handWinner(game->round->hands[i], game->round); first = round_findPlayerIndexRound(handWinner, game->round); if (deck_cardsNumber(deck) > 0) round_distributeCard(deck, game->round); } int oldScore[MAX_GAME_PLAYERS]; for(int i = 0; i < MAX_GAME_TEAMS; i++) { if(game->teams[i] != NULL) { oldScore[i] = game->teams[i]->score; } } game_updateScore(game, bidWinner); printRoundTerminationMessage(game, oldScore); getch(); deck_deleteDeck(&deck); round_deleteRound(&game->round); } clear(); refresh(); gameEndingMessage(game_winningTeam(game)); for (int i = 0; i < MAX_GAME_PLAYERS; i++) if (game->players[i]) team_deletePlayer(&game->players[i]); for (int i = 0; i < MAX_GAME_TEAMS; i++) if (game->teams[i]) team_deleteTeam(&game->teams[i]); game_deleteGame(&game); getch(); endwin(); return EXIT_SUCCESS; }
int main() { Board board = newBoard(); Player player = newPlayer(1, PLAYER, board), current; AI ai = newAI(board); WINDOW *status; bool isRunning = TRUE; int key; initscr(); /* Start curses mode */ start_color(); /* Color mode */ cbreak(); /* Disable line-break mode */ keypad(stdscr, TRUE); /* Enable getch for function keys */ curs_set(0); /* Remove cursor */ noecho(); /* Disable echo */ init_pair(1, COLOR_YELLOW, COLOR_BLACK); init_pair(2, COLOR_RED, COLOR_BLACK); init_pair(3, COLOR_YELLOW, COLOR_YELLOW); init_pair(4, COLOR_RED, COLOR_RED); status = newwin(25, 20, 0, 0); current = player; boardDraw(board); statusDraw(status, current, ai); ungetch('a'); /* Skip first getch() */ while(isRunning) { if((key = getch()) == KEY_F(1)) { isRunning = FALSE; break; } if(current == player) { if(player->doMove(player, key)) { /* Pass turn to AI */ current = ai->player; ungetch('a'); /* Skip the next keystroke and instantly go to the AI */ } } else { ai->doAIMove(ai); if(ai->player->doMove(ai->player, key)) { /* Pass turn to AI */ current = player; ungetch('a'); /* Skip the next keystroke and instantly go to the AI */ } } boardDraw(board); statusDraw(status, current, ai); if(board->isBoardFull(board)) { getch(); wmove(status, 13, 1); wclrtoeol(status); wattron(status, A_BOLD); wprintw(status, "Draw Game!"); wattroff(status, A_BOLD); wrefresh(status); isRunning = FALSE; getch(); } if(board->checkForWin(board, current->getID(current))) { int pid = current->getID(current); getch(); wmove(status, 13, 1); wclrtoeol(status); wattron(status, A_BOLD | COLOR_PAIR(pid)); wprintw(status, "%s", (pid == 1)?"Player":"AI"); wattroff(status, A_BOLD | COLOR_PAIR(pid)); wprintw(status, " won!"); wrefresh(status); isRunning = FALSE; getch(); } } board->destroyBoard(board); free(player); free(ai); endwin(); return 0; }