// Player discards a card void Player::discard (Card card) { currentHand_.removeCard( card ); // Remove card from hand discardedHand_.addCard( card ); // Add card to discarded pile addScore( card.getScore() ); // Add score std::cout << "Player " << id_ << " discards " << card << "." << std::endl; }
void Pacman::onTick() { // Cambiar dirección deseada de Pacman if(m_input->getKeyPress()->Up.value) { m_player.DesiredDirection = ViewDirection::Up; } else if(m_input->getKeyPress()->Right.value) { m_player.DesiredDirection = ViewDirection::Right; } else if(m_input->getKeyPress()->Left.value) { m_player.DesiredDirection = ViewDirection::Left; } else if(m_input->getKeyPress()->Down.value) { m_player.DesiredDirection = ViewDirection::Down; } if(m_readyTimer.getTicks() > 0) { if(m_readyTimer.getTicks() >= 2000) { m_readyTimer.stop(); m_gameTimer.start(); m_frameTimer.start(); } return; } if(m_pauseTimer.getTicks() > 0) { if(m_pauseTimer.getTicks() >= 500) { m_pauseTimer.stop(); m_gameTimer.resume(); m_frameTimer.resume(); if(m_ghostKillTimer.isPaused()) { m_ghostKillTimer.resume(); } if(m_player.IsDead) { resetGame(); } } return; } // Animar Pacman y Fantasmas (Cambio de Frames) if(m_frameTimer.getTicks() > 50) { if(m_player.Moving) { m_player.CurrentFrame++; if(m_player.CurrentFrame > 3) { m_player.CurrentFrame = 0; } } else { m_player.CurrentFrame = 1; } for(unsigned int x = 0; x < m_ghostCount; ++x) { m_ghost[x].CurrentFrame++; if(m_ghost[x].CurrentFrame > 1) { m_ghost[x].CurrentFrame = 0; } } m_frameTimer.start(); } // Mover Pacman moveEntity(&m_player.CurrentCellIndex, &m_player.PositionOffset, &m_player.Direction, &m_player.DesiredDirection, &m_player.Moving, m_player.MoveSpeed, true); bool ghostForceRefresh = false; sf::Vector2i findCoin = sf::Vector2i(m_player.CurrentCellIndex % m_mapSize.x, floor(m_player.CurrentCellIndex / m_mapSize.x)); // Comer bolas (Pacman) y actualizar mapa for(unsigned int x = 0; x < m_ballPosition.size(); ++x) { if(m_ballPosition[x] == findCoin) { mapSetCell(m_player.CurrentCellIndex, CellType::Nothing); m_ballPosition.erase(m_ballPosition.begin() + x); addScore(10); m_sound.setBuffer(m_ballSound); m_sound.play(); if(m_ballPosition.empty() && m_ballBigPosition.empty()) { resetGame(); return; } } } for(unsigned int x = 0; x < m_ballBigPosition.size(); ++x) { if(m_ballBigPosition[x] == findCoin) { mapSetCell(m_player.CurrentCellIndex, CellType::Nothing); m_ballBigPosition.erase(m_ballBigPosition.begin() + x); m_powerupKillCounter = 0; m_ghostKillTimer.start(); ghostForceRefresh = true; m_sound.setBuffer(m_powerupSound); m_sound.play(); for(unsigned int x = 0; x < m_ghostCount; ++x) { m_ghost[x].Invulnerable = false; } addScore(50); if(m_ballPosition.empty() && m_ballBigPosition.empty()) { resetGame(); return; } } } if(m_ghostKillTimer.getTicks() > 7000) { m_ghostKillTimer.stop(); for(unsigned int x = 0; x < m_ghostCount; ++x) { m_ghost[x].Invulnerable = false; m_ghost[x].LastStateChange = m_gameTimer.getTicks(); m_ghost[x].StateDuration = 3000; m_ghost[x].IsInChase = true; } ghostForceRefresh = true; } // IA Fantasmas for(unsigned int x = 0; x < m_ghostCount; ++x) { if(m_ghost[x].TimeToRelease >= m_gameTimer.getTicks()) { break; } unsigned int ignoreCell; if(m_ghost[x].Direction == ViewDirection::Left) { ignoreCell = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Right); } else if(m_ghost[x].Direction == ViewDirection::Right) { ignoreCell = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Left); } else if(m_ghost[x].Direction == ViewDirection::Up) { ignoreCell = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Down); } else { ignoreCell = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Up); } float ghostMoveSpeed = m_ghostKillTimer.isStarted() && (m_ghost[x].IsDead ? false : !m_ghost[x].Invulnerable) ? (m_ghost[x].MoveSpeed / 2) : (m_ghost[x].IsDead ? m_ghost[x].MoveSpeed * 1.5: m_ghost[x].MoveSpeed); if(m_ghost[x].CurrentCellIndex == m_ghost[x].HomeIndex) { m_ghost[x].IsDead = false; if(m_ghostKillTimer.isStarted()) { m_ghost[x].Invulnerable = true; } m_ghost[x].LastStateChange = m_gameTimer.getTicks(); m_ghost[x].StateDuration = 1000; m_ghost[x].IsInChase = true; } if(m_gameTimer.getTicks() >= (m_ghost[x].LastStateChange + m_ghost[x].StateDuration)) { if(!m_ghostKillTimer.isStarted()) { ghostForceRefresh = true; } m_ghost[x].LastStateChange = m_gameTimer.getTicks(); if(m_ghost[x].IsInChase) { m_ghost[x].IsInChase = false; m_ghost[x].StateDuration = (3000 + (rand() % 3000)); } else { m_ghost[x].IsInChase = true; m_ghost[x].StateDuration = (5000 + (rand() % 3000)); } } if(m_ghost[x].LastCellChecked != m_ghost[x].CurrentCellIndex || ghostForceRefresh) { if(m_ghost[x].IsDead) { m_ghost[x].DesiredDirection = getNextDirection(m_ghost[x].CurrentCellIndex, m_ghost[x].HomeIndex, ignoreCell); } else if(m_ghost[x].IsInChase && (!m_ghostKillTimer.isStarted() || m_ghost[x].Invulnerable)) { if(m_ghost[x].CurrentCellIndex != m_player.CurrentCellIndex) { m_ghost[x].DesiredDirection = getNextDirection(m_ghost[x].CurrentCellIndex, m_player.CurrentCellIndex, ignoreCell); } } else { unsigned int tempIndex; std::vector<unsigned int> possibleCells; if(m_ghost[x].Direction != ViewDirection::Left) { tempIndex = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Left); if(tempIndex != ignoreCell && m_mapInfo[tempIndex] != CellType::Wall) { possibleCells.push_back(tempIndex); } } if(m_ghost[x].Direction != ViewDirection::Right) { tempIndex = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Right); if(tempIndex != ignoreCell && m_mapInfo[tempIndex] != CellType::Wall) { possibleCells.push_back(tempIndex); } } if(m_ghost[x].Direction != ViewDirection::Up) { tempIndex = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Up); if(tempIndex != ignoreCell && m_mapInfo[tempIndex] != CellType::Wall) { possibleCells.push_back(tempIndex); } } if(m_ghost[x].Direction != ViewDirection::Down) { tempIndex = getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Down); if(tempIndex != ignoreCell && m_mapInfo[tempIndex] != CellType::Wall) { possibleCells.push_back(tempIndex); } } // Si hay caminos alternativos a seguir (Que no sea ni a donde se dirige ni la casilla anterior) o es un callejón sin salida... if(possibleCells.size() > 0 || getMapInfo(m_ghost[x].CurrentCellIndex, m_ghost[x].Direction) == CellType::Wall) { m_ghost[x].DesiredDirection = getRandomDirection(m_ghost[x].CurrentCellIndex, ignoreCell); } } m_ghost[x].LastCellChecked = m_ghost[x].CurrentCellIndex; } moveEntity(&m_ghost[x].CurrentCellIndex, &m_ghost[x].PositionOffset, &m_ghost[x].Direction, &m_ghost[x].DesiredDirection, &m_ghost[x].Moving, ghostMoveSpeed, false); if(!m_ghost[x].IsDead) { // Calcular colisión con Pacman if(m_ghost[x].CurrentCellIndex == m_player.CurrentCellIndex) { ghostCollide(x); } else if(getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Left) == m_player.CurrentCellIndex) { if((m_player.PositionOffset.x + (m_tileSize.x / 2)) - (m_ghost[x].PositionOffset.x + (m_tileSize.x / 2)) >= 0) { ghostCollide(x); } } else if(getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Right) == m_player.CurrentCellIndex) { if((m_ghost[x].PositionOffset.x + (m_tileSize.x / 2)) - (m_player.PositionOffset.x + (m_tileSize.x / 2)) >= 0) { ghostCollide(x); } } else if(getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Up) == m_player.CurrentCellIndex) { if((m_player.PositionOffset.y + (m_tileSize.y / 2)) - (m_ghost[x].PositionOffset.y + (m_tileSize.y / 2)) >= 0) { ghostCollide(x); } } else if(getMapIndex(m_ghost[x].CurrentCellIndex, ViewDirection::Down) == m_player.CurrentCellIndex) { if((m_ghost[x].PositionOffset.y + (m_tileSize.y / 2)) - (m_player.PositionOffset.y + (m_tileSize.y / 2)) >= 0) { ghostCollide(x); } } } } }
/** * This function is called when one of the mission's UFOs arrives at it's current destination. * It takes care of sending the UFO to the next waypoint, landing UFOs and * marking them for removal as required. It must set the game data in a way that the rest of the code * understands what to do. * @param ufo The UFO that reached it's waypoint. * @param engine The game engine, required to get access to game data and game rules. * @param globe The earth globe, required to get access to land checks. */ void AlienMission::ufoReachedWaypoint(Ufo &ufo, Game &engine, const Globe &globe) { const Ruleset &rules = *engine.getRuleset(); SavedGame &game = *engine.getSavedGame(); const size_t curWaypoint = ufo.getTrajectoryPoint(); const size_t nextWaypoint = curWaypoint + 1; const UfoTrajectory &trajectory = ufo.getTrajectory(); int waveNumber = _nextWave - 1; if (waveNumber < 0) { waveNumber = _rule.getWaveCount() - 1; } const MissionWave &wave = _rule.getWave(waveNumber); if (nextWaypoint >= trajectory.getWaypointCount()) { ufo.setDetected(false); ufo.setStatus(Ufo::DESTROYED); return; } ufo.setAltitude(trajectory.getAltitude(nextWaypoint)); ufo.setTrajectoryPoint(nextWaypoint); const RuleRegion ®ionRules = *rules.getRegion(_region); std::pair<double, double> pos = getWaypoint(trajectory, nextWaypoint, globe, regionRules); Waypoint *wp = new Waypoint(); wp->setLongitude(pos.first); wp->setLatitude(pos.second); ufo.setDestination(wp); if (ufo.getAltitude() != "STR_GROUND") { if (ufo.getLandId() != 0) { ufo.setLandId(0); } // Set next waypoint. ufo.setSpeed((int)(ufo.getRules()->getMaxSpeed() * trajectory.getSpeedPercentage(nextWaypoint))); } else { // UFO landed. if (wave.objective && trajectory.getZone(curWaypoint) == (size_t)(_rule.getSpawnZone())) { // Remove UFO, replace with MissionSite. addScore(ufo.getLongitude(), ufo.getLatitude(), game); ufo.setStatus(Ufo::DESTROYED); MissionArea area = regionRules.getMissionPoint(trajectory.getZone(curWaypoint), &ufo); Texture *texture = rules.getGlobe()->getTexture(area.texture); AlienDeployment *deployment = rules.getDeployment(texture->getDeployment()); MissionSite *missionSite = new MissionSite(&_rule, deployment); missionSite->setLongitude(ufo.getLongitude()); missionSite->setLatitude(ufo.getLatitude()); missionSite->setId(game.getId(deployment->getMarkerName())); missionSite->setSecondsRemaining(RNG::generate(deployment->getDurationMin(), deployment->getDurationMax()) * 3600); missionSite->setAlienRace(_race); missionSite->setTexture(area.texture); missionSite->setCity(area.name); game.getMissionSites()->push_back(missionSite); for (std::vector<Target*>::iterator t = ufo.getFollowers()->begin(); t != ufo.getFollowers()->end();) { Craft* c = dynamic_cast<Craft*>(*t); if (c && c->getNumSoldiers() != 0) { c->setDestination(missionSite); t = ufo.getFollowers()->begin(); } else { ++t; } } } else if (trajectory.getID() == "__RETALIATION_ASSAULT_RUN") { // Ignore what the trajectory might say, this is a base assault. // Remove UFO, replace with Base defense. ufo.setDetected(false); std::vector<Base *>::const_iterator found = std::find_if (game.getBases()->begin(), game.getBases()->end(), MatchBaseCoordinates(ufo.getLongitude(), ufo.getLatitude())); if (found == game.getBases()->end()) { ufo.setStatus(Ufo::DESTROYED); // Only spawn mission if the base is still there. return; } ufo.setDestination(*found); } else { // Set timer for UFO on the ground. ufo.setSecondsRemaining(trajectory.groundTimer()*5); if (ufo.getDetected() && ufo.getLandId() == 0) { ufo.setLandId(engine.getSavedGame()->getId("STR_LANDING_SITE")); } } } }
// // INStatsManager::recordStats // // Add stats for a particular level. // void INStatsManager::recordStats(const wbstartstruct_t *wbstats) { qstring levelkey; int scores[INSTAT_NUMTYPES]; int maxscores[INSTAT_NUMTYPES]; const wbplayerstruct_t *playerData = &wbstats->plyr[wbstats->pnum]; getLevelKey(levelkey); // really shouldn't happen if(levelkey == "") return; // not playing?? if(!playerData->in) return; // cheated? if(players[wbstats->pnum].cheats & CF_CHEATED) return; // demo? if(demoplayback) return; // copy data from wbstats/playerData to scores array scores[INSTAT_KILLS ] = playerData->skills; scores[INSTAT_ITEMS ] = playerData->sitems; scores[INSTAT_SECRETS] = playerData->ssecret; scores[INSTAT_TIME ] = playerData->stime; scores[INSTAT_FRAGS ] = players[wbstats->pnum].totalfrags; // Setup the maxscores array too maxscores[INSTAT_KILLS ] = wbstats->maxkills; maxscores[INSTAT_ITEMS ] = wbstats->maxitems; maxscores[INSTAT_SECRETS] = wbstats->maxsecret; maxscores[INSTAT_TIME ] = wbstats->partime; // Actually a minimum, of sorts. maxscores[INSTAT_FRAGS ] = -1; // There's no max for frags. for(int i = 0; i < INSTAT_NUMTYPES; i++) { in_stat_t *instat; if((instat = findScore(levelkey, i))) { // If we're not playing on the same or a better skill level, this // score can't replace the old one. if(gameskill < instat->skill) continue; // * For most categories, a higher score wins. Time is an exception. // * A tie wins if it is achieved on a higher skill level. if((gameskill > instat->skill && scores[i] == instat->value) || (i == INSTAT_TIME ? scores[i] < instat->value : scores[i] > instat->value)) { // This player has the new high score! instat->skill = gameskill; instat->value = scores[i]; instat->maxValue = maxscores[i]; E_ReplaceString(instat->playername, estrdup(players[wbstats->pnum].name)); } } else addScore(levelkey.constPtr(), scores[i], maxscores[i], i, wbstats->pnum); } }
void Pony48Engine::updateBoard(float32 dt) { m_fArrowAdd += dt * ARROW_SPEED; if(m_fArrowAdd >= ARROW_RESET) m_fArrowAdd -= ARROW_RESET; //Check slide-and-join animations for(list<TilePiece*>::iterator i = m_lSlideJoinAnimations.begin(); i != m_lSlideJoinAnimations.end();) { if((*i)->drawSlide.y < 0) { (*i)->drawSlide.y += dt * PIECE_MOVE_SPEED; if((*i)->drawSlide.y > 0) (*i)->drawSlide.y = 0; } else if((*i)->drawSlide.y > 0) { (*i)->drawSlide.y -= dt * PIECE_MOVE_SPEED; if((*i)->drawSlide.y < 0) (*i)->drawSlide.y = 0; } if((*i)->drawSlide.x < 0) { (*i)->drawSlide.x += dt * PIECE_MOVE_SPEED; if((*i)->drawSlide.x > 0) (*i)->drawSlide.x = 0; } else if((*i)->drawSlide.x > 0) { (*i)->drawSlide.x -= dt * PIECE_MOVE_SPEED; if((*i)->drawSlide.x < 0) (*i)->drawSlide.x = 0; } if((*i)->drawSlide.x == 0 && (*i)->drawSlide.y == 0) { if((*i)->destx >= 0 && (*i)->desty >= 0) { //Hit the end; join with destination tile if(m_Board[(*i)->destx][(*i)->desty] != NULL) { addScore((*i)->value * 2); float32 xPos = ((float32)(*i)->destx - 2.0f); if(xPos >= 0) xPos++; xPos /= SOUND_DIV_FAC; playSound("jointile", m_fSoundVolume, xPos); if(m_highestTile == m_Board[(*i)->destx][(*i)->desty]) m_highestTile = NULL; rumbleController(0.2, 0.1); delete m_Board[(*i)->destx][(*i)->desty]; ostringstream oss; oss << "res/tiles/" << min((*i)->value * 2, MAX_TILE_VALUE) << ".xml"; //"Duh, muffins" is highest possible tile m_Board[(*i)->destx][(*i)->desty] = loadTile(oss.str()); m_Board[(*i)->destx][(*i)->desty]->drawSize.Set(TILE_WIDTH+0.001, TILE_HEIGHT+0.001); //Start bounce animation m_Board[(*i)->destx][(*i)->desty]->iAnimDir = 1; if(!(m_highestTile) || m_highestTile->value < m_Board[(*i)->destx][(*i)->desty]->value) { m_highestTile = m_Board[(*i)->destx][(*i)->desty]; m_newHighTile->firing = true; if(m_highestTile->value == 2048) achievementGet("wutup"); else if(m_highestTile->value == 4096) achievementGet("ermahgerd"); } } else errlog << "Err board[x][y] == NULL" << (*i)->destx << "," << (*i)->desty << endl; } else errlog << "Err destx/y < 0: " << (*i)->destx << "," << (*i)->desty << endl; delete (*i); i = m_lSlideJoinAnimations.erase(i); continue; } i++; } for(int i = 0; i < BOARD_HEIGHT; i++) { for(int j = 0; j < BOARD_WIDTH; j++) { if(m_Board[j][i] == NULL) continue; //Check sliding animations if(m_Board[j][i]->drawSlide.y < 0) { m_Board[j][i]->drawSlide.y += dt * PIECE_MOVE_SPEED; if(m_Board[j][i]->drawSlide.y > 0) m_Board[j][i]->drawSlide.y = 0; } if(m_Board[j][i]->drawSlide.y > 0) { m_Board[j][i]->drawSlide.y -= dt * PIECE_MOVE_SPEED; if(m_Board[j][i]->drawSlide.y < 0) m_Board[j][i]->drawSlide.y = 0; } if(m_Board[j][i]->drawSlide.x < 0) { m_Board[j][i]->drawSlide.x += dt * PIECE_MOVE_SPEED; if(m_Board[j][i]->drawSlide.x > 0) m_Board[j][i]->drawSlide.x = 0; } if(m_Board[j][i]->drawSlide.x > 0) { m_Board[j][i]->drawSlide.x -= dt * PIECE_MOVE_SPEED; if(m_Board[j][i]->drawSlide.x < 0) m_Board[j][i]->drawSlide.x = 0; } //Check appearing animations if(m_Board[j][i]->drawSize.x < TILE_WIDTH) { m_Board[j][i]->drawSize.x += PIECE_APPEAR_SPEED * dt; if(m_Board[j][i]->drawSize.x > TILE_WIDTH) m_Board[j][i]->drawSize.x = TILE_WIDTH; } else if(m_Board[j][i]->drawSize.x > TILE_WIDTH) //And bouncing animations { m_Board[j][i]->drawSize.x += m_Board[j][i]->iAnimDir * PIECE_BOUNCE_SPEED * dt; if(m_Board[j][i]->drawSize.x > PIECE_BOUNCE_SIZE) m_Board[j][i]->iAnimDir = -1; //Reverse animation direction else if(m_Board[j][i]->drawSize.x < TILE_WIDTH) m_Board[j][i]->drawSize.x = TILE_WIDTH; //This also stops bouncing } if(m_Board[j][i]->drawSize.y < TILE_HEIGHT) { m_Board[j][i]->drawSize.y += PIECE_APPEAR_SPEED * dt; if(m_Board[j][i]->drawSize.y > TILE_HEIGHT) m_Board[j][i]->drawSize.y = TILE_HEIGHT; } else if(m_Board[j][i]->drawSize.y > TILE_HEIGHT) { m_Board[j][i]->drawSize.y += m_Board[j][i]->iAnimDir * PIECE_BOUNCE_SPEED * dt; if(m_Board[j][i]->drawSize.y > PIECE_BOUNCE_SIZE) m_Board[j][i]->iAnimDir = -1; else if(m_Board[j][i]->drawSize.y < TILE_HEIGHT) m_Board[j][i]->drawSize.y = TILE_HEIGHT; } } } }
/*********************************************************** synopsis: do all of the initialisation for a new game: build the screen get a random word and generate anagrams (must get less than 66 anagrams to display on screen) initialise all the game control flags inputs: head - first node in the answers list (in/out) dblHead - first node in the dictionary list screen - the SDL_Surface to display the image letters - first node in the letter sprites (in/out) outputs: n/a ***********************************************************/ static void newGame(struct node** head, struct dlb_node* dlbHead, SDL_Surface* screen, struct sprite** letters) { char guess[9]; char remain[9]; int happy = 0; /* we don't want any more than ones with 66 answers */ /* - that's all we can show... */ int i; /* show background */ strcpy(txt, language); ShowBMP(strcat(txt,"images/background.bmp"),screen, 0,0); destroyLetters(letters); assert(*letters == NULL); while (!happy) { char buffer[9]; getRandomWord(buffer, sizeof(buffer)); strcpy(guess,""); strcpy(rootWord, buffer); bigWordLen = strlen(rootWord)-1; strcpy(remain, rootWord); rootWord[bigWordLen] = '\0'; /* destroy answers list */ destroyAnswers(head); /* generate anagrams from random word */ ag(head, dlbHead, guess, remain); answersSought = Length(*head); happy = ((answersSought <= 77) && (answersSought >= 6)); #ifdef DEBUG if (!happy) { Debug("Too Many Answers! word: %s, answers: %i", rootWord, answersSought); } #endif } #ifdef DEBUG Debug("Selected word: %s, answers: %i", rootWord, answersSought); #endif /* now we have a good set of words - sort them alphabetically */ sort(head); for (i = bigWordLen; i < 7; i++){ remain[i] = SPACE_CHAR; } remain[7] = '\0'; remain[bigWordLen]='\0'; shuffleWord(remain); strcpy(shuffle, remain); strcpy(answer, SPACE_FILLED_STRING); /* build up the letter sprites */ assert(*letters == NULL && screen != NULL); buildLetters(letters, screen); addClock(letters, screen); addScore(letters, screen); /* display all answer boxes */ displayAnswerBoxes(*head, screen); gotBigWord = 0; score = 0; updateTheScore = 1; gamePaused = 0; winGame = 0; answersGot = 0; gameStart = time(0); gameTime = 0; stopTheClock = 0; }
void updateSnake(SnakeHead * snake) { drawSpaceSnake(snake); snake->lastPos = snake->pos; snake->lastDirection = snake->direction; /* This function will get the next position, check if is a hit, score or move, and call the right function */ switch (snake->direction) { case NORTH: snake->pos.Y -= 1; break; case SOUTH: snake->pos.Y += 1; break; case EAST: snake->pos.X += 1; break; case WEST: snake->pos.X -= 1; break; } /* Update the snake body */ SnakeBody * tmp = snake->next; if (tmp != NULL) { tmp->lastPos = tmp->pos; tmp->lastDirection = tmp->direction; tmp = tmp->next; while (tmp != NULL) { /* LastPosition of every block */ tmp->lastPos = tmp->pos; tmp->lastDirection = tmp->direction; tmp = tmp->next; } /* Updates the body positions */ tmp = snake->next; tmp->pos = snake->lastPos; tmp->direction = snake->lastDirection; if (tmp->next != NULL) { tmp = tmp->next; while (tmp != NULL) { tmp->pos = tmp->prev->lastPos; tmp->direction = tmp->prev->lastDirection; tmp = tmp->next; } } } if ((snake->nextPosSymbol != ' ') && (snake->nextPosSymbol != FRUIT)) { // Implement Death Functions DeathScreen(snake); while (!_kbhit()) { continue; } exit(0); } if (snake->nextPosSymbol == FRUIT) { addScore(snake); snake->digesting = true; } drawSnake(snake); }
int main( int argc, char *argv[] ) { struct highscoreItem *highscore = loadHighscore(); res.width = 1280; res.height = 720; // Load a font if (TTF_Init() != 0) { printf("TTF_Init() Failed: %s\n", TTF_GetError()); SDL_Quit(); exit(1); } fontBig = TTF_OpenFont("resources/fonts/DejaVuSans.ttf", FONT_SIZE_BIG); fontSmall = TTF_OpenFont("resources/fonts/DejaVuSans.ttf", FONT_SIZE_SMALL); TTF_SetFontStyle(fontSmall, TTF_STYLE_BOLD); font = fontBig; if (fontBig == NULL || fontSmall == NULL) { printf("TTF_OpenFont() Failed: %s\n", TTF_GetError()); TTF_Quit(); SDL_Quit(); exit(1); } // Initialisiere SDL if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0 ) { fprintf( stderr, "SDL konnte nicht initialisiert werden: %s\n", SDL_GetError() ); return 1; } // Initialisiere SDL_Image IMG_Init(IMG_INIT_PNG); // Timer einrichten SDL_AddTimer (16, generate_userevent, NULL); // Event-System initialisieren SDL_Event event; SDL_WM_SetCaption("Jump and Run", "Jump and Run"); SDL_Surface *icon = IMG_Load("resources/images/icon.png"); if (icon != NULL) SDL_WM_SetIcon(icon, NULL); // Erstelle die Bildschirmfläche SDL_Surface *screen = NULL; screen = SDL_SetVideoMode( res.width, res.height, SCREEN_BPP, SDL_HWSURFACE | SDL_DOUBLEBUF); SDL_ShowCursor(0); initializeSounds(); startMusic(); initializeClouds(); int returnValue = drawMenu(screen, event); while (1) { switch (returnValue) { case MENU: returnValue = drawMenu(screen, event); break; case START_GAME: returnValue = LEVEL_OFFSET; break; case HIGHSCORES: drawHighscore(screen, font, event, highscore); returnValue = MENU; break; default: if (returnValue >= LEVEL_OFFSET && returnValue < LEVEL_OFFSET + MAX_LEVEL) { returnValue = addScore(screen, startGame (screen, event, res, returnValue - LEVEL_OFFSET), event, &highscore); } else if (returnValue <= EXIT_GAME) { printf("Spiel beenden\n"); freeHighscore(highscore); freeAudio(); TTF_CloseFont(fontBig); TTF_CloseFont(fontSmall); TTF_Quit(); SDL_Quit(); exit(returnValue - EXIT_GAME); } else returnValue = MENU; } } return 0; }
void Game::idle() { struct timeb now; ftime(&now); ellapsed=(now.time-last.time)*1000.0+now.millitm-last.millitm; last=now; if(state==IGame::Running) { for(unsigned int i=0;i<gluts.size();i++) { gluts.at(i)->idle(*this); } for(unsigned int i=0;i<ghosts.size();i++) { IGhost *g=ghosts.at(i); if(!i){g->speed(getStressPercent()*getPacman()->speed()*1.5);} int x=(int)(pacman->X()/map->width())-(int)(g->X()/map->width()); int y=(int)(pacman->Y()/map->height())-(int)(g->Y()/map->height()); if(!x) if(!y) { if(g->scared()) { addScore(100); g->scared(false); g->setDirection(0,0); g->X((map->cols()/2.0+0.5)*map->width()); g->Y((map->rows()/2.0-1+0.5)*map->height()); } else { lives--; if(lives<=0) { state=IGame::GameOver; } else { getPacman()->X((map->cols()/2+0.5)*map->width()); getPacman()->Y(1.5*map->height()); } } } } bool food=false; for(int y=0;y<map->rows();y++) for(int x=0;x<map->cols();x++) if(map->matrix()[x][y]==IMap::TileFood) food=true; if(food==false) { state=Game::Win; } } else if(state==IGame::GameOver) { if(getController()->button()) { state=IGame::Reset; } } else if(state==IGame::Win) { if(getController()->button()) { state=IGame::Start; } } else if(state==IGame::Reset) { state=IGame::Start; lives=3; score=0; levels.clear(); levels.push_back(new Level(15+8,11+8,3,new MiniMaxArtificialIntelligence())); levels.push_back(new Level(15+8,11+8,3,new DistanceArtificialIntelligence())); levels.push_back(new Level(15+8,11+8,3,new FakeArtificialIntelligence())); levels.push_back(new Level(15+8,11+8,3,new AleatoryArtificialIntelligence())); levels.push_back(new Level(15+4,11+4,3,new MiniMaxArtificialIntelligence())); levels.push_back(new Level(15+4,11+4,3,new DistanceArtificialIntelligence())); levels.push_back(new Level(15+4,11+4,3,new FakeArtificialIntelligence())); levels.push_back(new Level(15+4,11+4,3,new AleatoryArtificialIntelligence())); levels.push_back(new Level(15,11,3,new MiniMaxArtificialIntelligence())); levels.push_back(new Level(15,11,3,new DistanceArtificialIntelligence())); levels.push_back(new Level(15,11,3,new FakeArtificialIntelligence())); levels.push_back(new Level(15,11,3,new AleatoryArtificialIntelligence())); ftime(&last); } else if(state==IGame::Start) { if(levels.size()==0) { state=IGame::GameOver; } else { Level* level=levels.back(); levels.pop_back(); // AI if(ai) { gluts.erase(std::remove(gluts.begin(), gluts.end(), ai), gluts.end()); // delete ai; } ai=level->ai; gluts.push_back(ai); // Controller if(controller) { gluts.erase(std::remove(gluts.begin(), gluts.end(), controller), gluts.end()); // delete controller; } #ifdef USE_QT controller=new ArduinoController(); #else controller=new KeyboardController(); #endif gluts.push_back(controller); map->setup(*this,level->cols,level->rows,level->width,level->height); state=IGame::Running; heuris = new HeuristicFunction(map); } } glutPostRedisplay(); }
void menu(SDL_Surface *ecran, Sprites &sprites, Boutons &boutons, int &modeMenu, int &modeJeu, SourisEvent &sourisEvent, Time &time, Message msgs[], Partie &partie, Chien &chien) { bool sortir = false; int lastKeyPressed; int lastKeyPressedBis; int lastMenu = 1; bool keyPressed = false; bool keyPressedBis = false; bool defilTouche = false; for (int i=0; i<LONGUEUR_MAX_PSEUDO; i++) { partie.pseudoT[i] = 0; } getScore("scoresClassic", partie.highScore); int carActif = 0; Uint8 *keystate = SDL_GetKeyState(NULL); time.currentTime = SDL_GetTicks(); time.timeMenu = time.currentTime; time.timeKey = time.currentTime; time.timeDefKey = time.currentTime; while (!sortir && modeMenu!=0) { if (getEvents(sourisEvent, 1)) { modeMenu = 0; modeJeu = 0; } time.currentTime = SDL_GetTicks(); switch (modeMenu) { case 0: sortir = true; break; case 1 : boutons.bouton[BOUTON_PLAY].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_PLAY].position.y = 100; boutons.bouton[BOUTON_SCORE].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_SCORE].position.y = 250; boutons.bouton[BOUTON_OPTIONS].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_OPTIONS].position.y = 400; boutons.bouton[BOUTON_QUIT].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_QUIT].position.y = 550; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_QUIT], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 0; modeJeu = 0; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_PLAY], boutons.lecture[0]))&&sourisEvent.clicGauche) { time.currentTime = SDL_GetTicks(); time.timeMenu = time.currentTime; modeJeu = 1; modeMenu = 6; initChien(chien); sprites.canardActifs = 2; for (int i = 0 ; i < sprites.canardActifs ; i++) { sprites.canard[i].type = alea(0, 3); initCanard(sprites.canard[i], partie); } partie.niveau = 0; partie.score = 0; initPartie(partie, sprites.canardActifs); initTableau(partie.tableauChasse, sprites); } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_SCORE], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 7; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OPTIONS], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 2; } break; case 2: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; boutons.bouton[BOUTON_THEME_CLASSIQUE].position.x = ((LARGEUR/2) - (boutons.lecture[0].w/2))/2; boutons.bouton[BOUTON_THEME_CLASSIQUE].position.y = 200; boutons.bouton[BOUTON_THEME_ISLAND].position.x = (((LARGEUR/2) - (boutons.lecture[0].w/2))/2)+((LARGEUR/2) - (boutons.lecture[0].w/2)); boutons.bouton[BOUTON_THEME_ISLAND].position.y = 200; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = lastMenu; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_THEME_CLASSIQUE], boutons.lecture[0]))&&sourisEvent.clicGauche) { boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = true; boutons.bouton[BOUTON_THEME_ISLAND].actif = false; libererImages(sprites, chien, boutons); chargerImages(sprites, chien, boutons, "classique"); } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_THEME_ISLAND], boutons.lecture[0]))&&sourisEvent.clicGauche) { boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = false; boutons.bouton[BOUTON_THEME_ISLAND].actif = true; libererImages(sprites, chien, boutons); chargerImages(sprites, chien, boutons, "island"); } break; case 5 : boutons.bouton[BOUTON_REPRENDRE].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_REPRENDRE].position.y = 200; boutons.bouton[BOUTON_OPTIONS].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_OPTIONS].position.y = 400; boutons.bouton[BOUTON_QUIT].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_QUIT].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_QUIT], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; lastMenu = 1; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_REPRENDRE], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 0; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OPTIONS], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 2; lastMenu = 5; } break; case 6: if (time.currentTime >= time.menuTime + time.timeMenu) { modeMenu = 0; time.timeMenu = time.currentTime; } break; case 7: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; } break; case 8: boutons.bouton[BOUTON_OK].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_OK].position.y = 600; lastKeyPressedBis = lastKeyPressed; keyPressedBis = keyPressed; keyPressed = false; if (carActif < LONGUEUR_MAX_PSEUDO-1) { for (int i=97; i<123; i++) { if (keystate[i]) { lastKeyPressed = i; keyPressed = true; } } } if ((carActif > 0)&&keystate[SDLK_BACKSPACE]) { lastKeyPressed = -1; keyPressed = true; } if ((lastKeyPressedBis !=lastKeyPressed)||(defilTouche&&(time.currentTime >= time.timeDefKey + time.defKeyTime))||(keyPressedBis!=keyPressed)) { if (keyPressedBis!=keyPressed) { defilTouche = false; } if (carActif < LONGUEUR_MAX_PSEUDO-1) { for (int i=97; i<123; i++) { if (keystate[i]) { partie.pseudoT[carActif]=(i-32); carActif++; time.timeKey = time.currentTime; } } } if ((carActif > 0)&&keystate[SDLK_BACKSPACE]) { partie.pseudoT[carActif-1]=0; carActif--; time.timeKey = time.currentTime; } if (defilTouche) { time.timeDefKey = time.currentTime; } } else { if ((time.currentTime >= time.timeKey + time.keyTime)&&keyPressed) { defilTouche = true; } } partie.pseudo = std::string(partie.pseudoT); if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OK], boutons.lecture[0]))&&sourisEvent.clicGauche) { addScore("scoresClassic", partie.pseudo, partie.score, partie.highScore); modeMenu = 7; } break; case 9: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; } break; default: break; } if (time.currentTime >= time.timeFps + time.fpsTime) { showMenu(ecran, sprites, boutons, modeMenu, msgs, partie, sourisEvent.sx, sourisEvent.sy); time.timeFps = time.currentTime; } SDL_Flip(ecran); } }
ScorePage::ScorePage(int _width, int _height, NetworkEvent &_netEvent) : netEvent(_netEvent) { width = _width; height = _height; back = false; currentFocus = ""; sf::Texture *textureScore = new sf::Texture; if (!textureScore->loadFromFile("resources/scorePage.png")) std::cerr << "scorePage.png is not found" << std::endl; scorePages.setTexture(*textureScore); scorePages.setColor(sf::Color(255, 255, 255, 200)); defaultPos.x = 0.17 * width; defaultPos.y = 0.15 * height; scorePages.setPosition(defaultPos); sf::Texture *textureButtonBack = new sf::Texture(); if (!textureButtonBack->loadFromFile("resources/back_button.png")) std::cerr << "back_button.png is not found" << std::endl; backButton.setTexture(*textureButtonBack); backButton.setPosition(sf::Vector2f((float)width * 0.2f, (float)height/ 1.35)); backButton.setScale(1.5f, 1.5f); sf::Vector2f backPos(backButton.getPosition().x , backButton.getPosition().y); sf::Vector2f backSize(textureButtonBack->getSize().x * 1.5f, textureButtonBack->getSize().y * 1.5f); mouseBox["back"] = new MouseOnBox(NULL, backPos, backSize, "back"); if (!fontScore.loadFromFile("imagine_font.ttf")) { std::cerr << "Typo not found" << std::endl; } textScore[0].setFont(fontScore); textScore[0].setColor(sf::Color::White); textScore[0].setString("1 - "); textScore[0].setPosition(sf::Vector2f((float)width * 0.33f, (float)height * 0.36f)); textScore[1].setFont(fontScore); textScore[1].setColor(sf::Color::White); textScore[1].setString("2 - "); textScore[1].setPosition(sf::Vector2f((float)width * 0.33f, (float)height * 0.43f)); textScore[2].setFont(fontScore); textScore[2].setColor(sf::Color::White); textScore[2].setString("3 - "); textScore[2].setPosition(sf::Vector2f((float)width * 0.33f, (float)height * 0.50f)); textScore[3].setFont(fontScore); textScore[3].setColor(sf::Color::White); textScore[3].setString("4 - "); textScore[3].setPosition(sf::Vector2f((float)width * 0.33f, (float)height * 0.57f)); textScore[4].setFont(fontScore); textScore[4].setColor(sf::Color::White); textScore[4].setString("5 - "); textScore[4].setPosition(sf::Vector2f((float)width * 0.33f, (float)height * 0.64f)); textScore[5].setFont(fontScore); textScore[5].setColor(sf::Color::White); textScore[5].setString("6 - "); textScore[5].setPosition(sf::Vector2f((float)width * 0.57f, (float)height * 0.36f)); textScore[6].setFont(fontScore); textScore[6].setColor(sf::Color::White); textScore[6].setString("7 - "); textScore[6].setPosition(sf::Vector2f((float)width * 0.57f, (float)height * 0.43f)); textScore[7].setFont(fontScore); textScore[7].setColor(sf::Color::White); textScore[7].setString("8 - "); textScore[7].setPosition(sf::Vector2f((float)width * 0.57f, (float)height * 0.50f)); textScore[8].setFont(fontScore); textScore[8].setColor(sf::Color::White); textScore[8].setString("9 - "); textScore[8].setPosition(sf::Vector2f((float)width * 0.57f, (float)height * 0.57f)); textScore[9].setFont(fontScore); textScore[9].setColor(sf::Color::White); textScore[9].setString("10 - "); textScore[9].setPosition(sf::Vector2f((float)width * 0.57f, (float)height * 0.64f)); addScore("sophie 32"); addScore("titi 32"); addScore("toto 32"); addScore("tata 32"); addScore("ttutu 32"); addScore("soso 32"); addScore("sophiez 32"); addScore("titiz 32"); addScore("totoz 32"); addScore("tataz 32"); addScore("ttutuz 32"); addScore("sosoz 32"); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } mbirdstr.push_back("birdblue"); mbirdstr.push_back("birdred"); mbirdstr.push_back("birdyellow"); mbirdclolor=rand()%100%3; // EFFECT_PLAY(true,MUSIC_SWOOSHING); //播放背景音乐 // CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_JUMP, true); //////////////////////////////////////////////////// // 下面添加创建自己的Sprite的代码 //////////////////////////////////////////////////// mScreenSize = CCDirector::sharedDirector()->getWinSize(); mFPS=CCDirector::sharedDirector()->getAnimationInterval(); mfac=CCDirector::sharedDirector()->getContentScaleFactor(); mfax = 320.f/mScreenSize.width; //gBardis = 5.f*gUpVelocity/mfac; gBardis = mScreenSize.height*2.f/9.0f-5; //m_addbartime=mScreenSize.width*mFPS*mfax*1.f/2.f/MOVESPEED-10; //m_addbartime=3; initWorld(); for (int i = 0; i<GBACKGROUNDNUM; i++) { addBackGround(i); } int imaxgroundnum=1; for (int i = 0; i<imaxgroundnum; i++) { imaxgroundnum=addGround(i); } m_ilastground=imaxgroundnum-1; CCLOG("m_pLastGround->boundingBox() first x:%f,:%f ", (m_pGroundVec[m_ilastground])->boundingBox().getMaxX(), (m_pGroundVec[m_ilastground])->boundingBox().size.width); addStart(); addTop(); //addRate(); //addFlappyBird(); addBird(); addScore(); addGameOver(); m_pScore->setVisible(false); m_pGameOver->setVisible(false); this->goReady(); addBarContainer(); setTouchEnabled(true); myflag=0; m_istatus=GETREADY; m_bhitbar=false; //scheduleOnce(schedule_selector(HelloWorld::startGame), 1); this->scheduleUpdate(); //创建动画 initAction(); myangle=0.f; return true; }
void addLeftBonus() { nextExtend = 999999999; addScore(left*100000); }
static void getBonus() { addScore(bonusScore); if ( bonusScore < 1000 ) bonusScore += 10; }
void drawGameScreen() { clear(); //draw exterior of game drawBox(10, 3, 44, 34, 0); //draw path walls drawBox(10, 7, 11, 3, 0); drawBox(18, 7, 4, 14, 0); drawBox(18, 18, 16, 3, 0); drawBox(31, 7, 4, 14, 0); drawBox(31, 7, 18, 3, 0); drawBox(46, 7, 4, 24, 0); drawBox(19, 28, 30, 3, 0); drawBox(19, 28, 4, 9, 0); //fix up the corners clearPath(); fixCorners(); //add beginning and ending chars mvaddch(8, 8, '>'); mvaddch(37, 21, ACS_DARROW); //draw and fill the purchase portion of the screen attron(COLOR_PAIR(0)); drawPurchaseArea(); basicSetupScreen(1); updateScore(0); attroff(COLOR_PAIR(0)); drawTowerExplain(); //load arrays for drawing TowerArray* theTowerList = getTowerArray("assets/towersLevel1.txt"); Path* thePath = getPathArray("assets/path.txt"); UnitListHeader * unitList = malloc(sizeof(UnitListHeader)); int moneyAmount = STARTINGMONEY; initializeList(unitList); drawUnitTypes(unitList); int theScore = 0; drawTowers(theTowerList); //go to entering unit purchases (gives control back to user) selectUnitsInterface(thePath,unitList,&moneyAmount,theTowerList,&theScore); //get lowest score of highscores ScoreHead scores; scores.size = 0; scores.first = NULL; ScoreNode * currScore = NULL; readScores(&scores); currScore = scores.first; int numScores = 1; int highestScore = 0; while ((currScore->next != NULL) && (numScores < 9)) { numScores += 1; currScore = currScore->next; } highestScore = -1; if (numScores > 8 && currScore != NULL) { highestScore = currScore->score; } char * enterName; if (theScore > highestScore) { enterName = drawScore(theScore,1); if (enterName != NULL) { addScore(&scores, enterName, theScore); writeScores(&scores); } } else { drawScore(theScore,0); } if (scores.size > 0) destroyScores(&scores); }
// Main function game called every frame void Game::update() { // Read player input mPlatform->processEvents(); // Update game state if (mIsOver) { if ((mEvents & EVENT_RESTART) != 0) { mIsOver = false; start(); } } else { // Always handle restart event if ((mEvents & EVENT_RESTART) != 0) { start(); return; } long currentTime = mPlatform->getSystemTime(); // Process delayed autoshift int timeDelta = (int)(currentTime - mSystemTime); if (mDelayDown > 0) { mDelayDown -= timeDelta; if (mDelayDown <= 0) { mDelayDown = DAS_MOVE_TIMER; mEvents |= EVENT_MOVE_DOWN; } } if (mDelayLeft > 0) { mDelayLeft -= timeDelta; if (mDelayLeft <= 0) { mDelayLeft = DAS_MOVE_TIMER; mEvents |= EVENT_MOVE_LEFT; } } else if (mDelayRight > 0) { mDelayRight -= timeDelta; if (mDelayRight <= 0) { mDelayRight = DAS_MOVE_TIMER; mEvents |= EVENT_MOVE_RIGHT; } } #ifdef STC_AUTO_ROTATION if (mDelayRotation > 0) { mDelayRotation -= timeDelta; if (mDelayRotation <= 0) { mDelayRotation = ROTATION_AUTOREPEAT_TIMER; mEvents |= EVENT_ROTATE_CW; } } #endif // STC_AUTO_ROTATION // Always handle pause event if ((mEvents & EVENT_PAUSE) != 0) { mIsPaused = !mIsPaused; mEvents = EVENT_NONE; } // Check if the game is paused if (mIsPaused) { // We achieve the effect of pausing the game // adding the last frame duration to lastFallTime mLastFallTime += (currentTime - mSystemTime); } else { if (mEvents != EVENT_NONE) { if ((mEvents & EVENT_SHOW_NEXT) != 0) { mShowPreview = !mShowPreview; mStateChanged = true; } #ifdef STC_SHOW_GHOST_PIECE if ((mEvents & EVENT_SHOW_SHADOW) != 0) { mShowShadow = !mShowShadow; mStateChanged = true; } #endif if ((mEvents & EVENT_DROP) != 0) { dropTetromino(); } if ((mEvents & EVENT_ROTATE_CW) != 0) { rotateTetromino(true); } if ((mEvents & EVENT_ROTATE_CCW) != 0) { rotateTetromino(false); } if ((mEvents & EVENT_MOVE_RIGHT) != 0) { moveTetromino(1, 0); } else if ((mEvents & EVENT_MOVE_LEFT) != 0) { moveTetromino(-1, 0); } if ((mEvents & EVENT_MOVE_DOWN) != 0) { // Update score if the player accelerates downfall addScore((long)(SCORE_2_FILLED_ROW * (mStats.level + 1) / SCORE_MOVE_DOWN_DIVISOR)); moveTetromino(0, 1); } mEvents = EVENT_NONE; } // Check if it's time to move downwards the falling tetromino if (currentTime - mLastFallTime >= mFallingDelay) { moveTetromino(0, 1); mLastFallTime = currentTime; } } // Save current time for next game update mSystemTime = currentTime; } // Draw game state mPlatform->renderGame(); }
void T2::checkMove(int dir_guester) { if(dir_guester== DIR_RIGHT){ //≈ì√ö‚Äù‚Ä? if (move_state == MOVE_YD1) //¬µ‚ÅÑ‚Äú¬™‚⧌©‚Äú‚àÜ‚àÇ√? { for (int i=0;i<MAX_ROW;i++) { for (int j = MAX_COL-2; j >=0 ; --j) { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i][j+1]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = j+1; while (arr_Num[i][index]==-1) { count++; if(index<MAX_COL-1) index++; else break; } nodeMove(dir_guester,i,j,count); change2number(arr_Num[i][j],arr_Num[i][j+count]); } } } logcat_chessArr("move-yd1"); if(bemoved_yd1){ CCLog("can move yd1"); move_state = MOVE_NONE; }else{ CCLog("can not move yd1"); move_state = MOVE_HETI; } } else if(move_state == MOVE_HETI)//¬µ‚Å?‚⧌©‚à´≈ì‚â•‚Ä? { CCLog("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); update_moveyd1(); for (int i=0;i<MAX_ROW;i++) { for (int j=MAX_COL-1;j>0;j--) { if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i][j-1]&&arr_Num[i][j]==arr_Num[i][j-2]&&arr_Num[i][j]==arr_Num[i][j-3]) { CCLog("ppppppppppppppp"); becomposed = true; arr_Num[i][j]++; arr_Num[i][j-1]= -1; addScore(arr_Num[i][j]); change(dir_guester,i,j,arr_Num[i][j]); removeChessnode(dir_guester,i,j-1); MyCCLog::verbose("score---"); break; } else if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i][j-1]) { CCLog("qqqqqqqqqqqqqq"); becomposed = true; arr_Num[i][j]++; arr_Num[i][j-1]= -1; addScore(arr_Num[i][j]); change(dir_guester,i,j,arr_Num[i][j]); removeChessnode(dir_guester,i,j-1); } } } CCLog("tttttttttttttttttttttttttttttttttttttttttttttttttttttttt"); logcat_chessArr("right-move-heti1"); if(bemoved_yd1&&!becomposed) { CCLog("can move and can not heti"); move_state = MOVE_OVER; return; } move_state = MOVE_NONE; } else if(move_state == MOVE_YD2) { CCLog("MOVE_YD2MOVE_YD2"); for (int i=0;i<MAX_ROW;i++) { for (int j = MAX_COL-2; j >=0 ; --j) { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i][j+1]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { index = j+1; while (arr_Num[i][index]==-1) { count++; if(index<MAX_COL-1) index++; else break; } nodeMove(dir_guester,i,j,count); change2number(arr_Num[i][j],arr_Num[i][j+count]); } } } logcat_chessArr("move-yd2"); move_state = MOVE_OVER; } else if(move_state == MOVE_OVER) { CCLog("right-----------move-over---over"); addNewChess(); move_state = MOVE_NONE; if(checkFull()) { bool rightover = checkGameOver(); CCLog("rightover = %d",rightover); } } } else if(dir_guester== DIR_LEFT){ //≈ì√ö‚Äù‚Ä? if (move_state == MOVE_YD1) //¬µ‚ÅÑ‚Äú¬™‚⧌©‚Äú‚àÜ‚àÇ√? { for (int i=0;i<MAX_ROW;i++) { for (int j =1; j < MAX_COL ; j++) { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i][j-1]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = j-1; while (arr_Num[i][index]==-1) { count++; if(index>0) index--; else break; } nodeMove(dir_guester,i,j,count); change2number(arr_Num[i][j],arr_Num[i][j-count]); } } } logcat_chessArr("left-move-yd1"); if(bemoved_yd1){ CCLog("can move left yd1"); move_state = MOVE_NONE; }else{ CCLog("can not move left yd1"); move_state = MOVE_HETI; } } else if(move_state == MOVE_HETI)//¬µ‚Å?‚⧌©‚à´≈ì‚â•‚Ä? { update_moveyd1(); for (int i=0;i<MAX_ROW;i++) { for (int j=0;j<MAX_COL-1;j++) { if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i][j+1]&&arr_Num[i][j]==arr_Num[i][j+2]&&arr_Num[i][j]==arr_Num[i][j+3]) { CCLog("wdddddddsssssss"); becomposed = true; arr_Num[i][j]++; arr_Num[i][j+1]= -1; addScore(arr_Num[i][j]); change(dir_guester,i,j,arr_Num[i][j]); removeChessnode(dir_guester,i,j+1); break; } if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i][j+1]) { CCLog("ssssdwww"); becomposed = true; arr_Num[i][j]++; arr_Num[i][j+1]= -1; addScore(arr_Num[i][j]); change(dir_guester,i,j,arr_Num[i][j]); removeChessnode(dir_guester,i,j+1); } } } CCLog("tttttttttttttttttttttttttttttttttttttttttttttttttttttttt"); logcat_chessArr("left-move-heti1"); if(bemoved_yd1&&!becomposed) { CCLog("can move and can not heti"); move_state = MOVE_OVER; return; } move_state = MOVE_NONE; } else if(move_state == MOVE_YD2) { CCLog("MOVE_YD2MOVE_YD2"); for (int i=0;i<MAX_ROW;i++) { for (int j =1; j < MAX_COL ; j++) { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i][j-1]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = j-1; while (arr_Num[i][index]==-1) { count++; if(index>0) index--; else break; } nodeMove(dir_guester,i,j,count); change2number(arr_Num[i][j],arr_Num[i][j-count]); } } } logcat_chessArr("move-yd2"); move_state = MOVE_OVER; } else if(move_state == MOVE_OVER) { CCLog("left-----------move-over---over"); addNewChess(); if(checkFull()) { bool leftover = checkGameOver(); CCLog("leftover = %d",leftover); } move_state = MOVE_NONE; } } else if(dir_guester == DIR_UP){ //≈ì√ö‚Ķ≈? if (move_state == MOVE_YD1) //¬µ‚ÅÑ‚Äú¬™‚⧌©‚Äú‚àÜ‚àÇ√? { for (int j =0; j < MAX_COL ; j++)//lie { for (int i= MAX_ROW-2;i>=0;i--)//hang { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i+1][j]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = i+1; while (arr_Num[index][j]==-1) { count++; if(index<MAX_ROW-1) index++; else break; } CCLog("j = %d i= %d COUNT = %d",j,i,count); nodeMove(dir_guester,j,i,count); change2number(arr_Num[i][j],arr_Num[i+count][j]); } } } logcat_chessArr("up-move-yd1"); if(bemoved_yd1){ CCLog("up -can move yd1"); move_state = MOVE_NONE; }else{ CCLog("up-can not move yd1"); move_state = MOVE_HETI; } } else if(move_state == MOVE_HETI)//¬µ‚Å?‚⧌©‚à´≈ì‚â•‚Ä? { CCLog("mmmmmmmmmmmmmmmmmm"); update_moveyd1(); for (int j=0;j<MAX_COL;j++) { for (int i=MAX_ROW-1;i>0;i--) { if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i-1][j]&&arr_Num[i][j]==arr_Num[i-2][j]&&arr_Num[i][j]==arr_Num[i-3][j]) { CCLog("ppppppppppppppp"); becomposed = true; arr_Num[i][j]++; arr_Num[i-1][j]= -1; addScore(arr_Num[i][j]); change(dir_guester,j,i,arr_Num[i][j]); removeChessnode(dir_guester,j,i-1); break; } else if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i-1][j]) { CCLog("qqqqqqqqqqqqqq"); becomposed = true; arr_Num[i][j]++; arr_Num[i-1][j]= -1; addScore(arr_Num[i][j]); change(dir_guester,j,i,arr_Num[i][j]); removeChessnode(dir_guester,j,i-1); } } } CCLog("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); logcat_chessArr("up------move-heti1"); if(bemoved_yd1&&!becomposed) { CCLog("can move and can not heti"); move_state = MOVE_OVER; return; } move_state = MOVE_NONE; } else if(move_state == MOVE_YD2) { for (int j =0; j < MAX_COL ; j++)//lie { for (int i= MAX_ROW-2;i>=0;i--)//hang { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i+1][j]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = i+1; while (arr_Num[index][j]==-1) { count++; if(index<MAX_ROW-1) index++; else break; } CCLog("j = %d i= %d COUNT = %d",j,i,count); nodeMove(dir_guester,j,i,count); change2number(arr_Num[i][j],arr_Num[i+count][j]); } } } logcat_chessArr("move-yd2"); move_state = MOVE_OVER; } else if(move_state == MOVE_OVER) { CCLog("up-----------move-over---over"); addNewChess(); if(checkFull()) { bool upover = checkGameOver(); CCLog("upover = %d",upover); } move_state = MOVE_NONE; } } else if(dir_guester == DIR_DOWN){ if (move_state == MOVE_YD1) //¬µ‚ÅÑ‚Äú¬™‚⧌©‚Äú‚àÜ‚àÇ√? { for (int j =0; j < MAX_COL ; j++)//lie { for (int i= 1;i< MAX_ROW;i++)//hang { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i-1][j]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = i-1; while (arr_Num[index][j]==-1) { count++; if(index>0) index--; else break; } CCLog("j = %d i= %d COUNT = %d",j,i,count); nodeMove(dir_guester,j,i,count); change2number(arr_Num[i][j],arr_Num[i-count][j]); } } } logcat_chessArr("down-move-yd1"); if(bemoved_yd1){ CCLog("down -can move yd1"); move_state = MOVE_NONE; }else{ CCLog("down-can not move yd1"); move_state = MOVE_HETI; } } else if(move_state == MOVE_HETI)//¬µ‚Å?‚⧌©‚à´≈ì‚â•‚Ä? { CCLog("mmmmmmmmmmmmmmmmmm"); update_moveyd1(); for (int j=0;j<MAX_COL;j++) { for (int i=0;i<MAX_ROW-1;i++) { if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i+1][j]&&arr_Num[i][j]==arr_Num[i+2][j]&&arr_Num[i][j]==arr_Num[i+3][j]) { CCLog("ppppppppppppppp"); becomposed = true; arr_Num[i][j]++; arr_Num[i+1][j]= -1; addScore(arr_Num[i][j]); change(dir_guester,j,i,arr_Num[i][j]); removeChessnode(dir_guester,j,i+1); break; } else if(arr_Num[i][j]>=0&&arr_Num[i][j]==arr_Num[i+1][j]) { CCLog("qqqqqqqqqqqqqq"); becomposed = true; arr_Num[i][j]++; arr_Num[i+1][j]= -1; addScore(arr_Num[i][j]); change(dir_guester,j,i,arr_Num[i][j]); removeChessnode(dir_guester,j,i+1); } } } CCLog("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); logcat_chessArr("down------move-heti1"); if(bemoved_yd1&&!becomposed) { CCLog("can move and can not heti"); move_state = MOVE_OVER; return; } move_state = MOVE_NONE; } else if(move_state == MOVE_YD2) { for (int j =0; j < MAX_COL ; j++)//lie { for (int i= 1;i< MAX_ROW;i++)//hang { int index = -1; int count = 0; if(arr_Num[i][j]>-1&&arr_Num[i-1][j]==-1)//¬ª√ÅœÄÀö‚Äù‚Äú¬±Ô¨Ç¬†¬´√∏‚Äô¬µ∆? { bemoved_yd1 = true; index = i-1; while (arr_Num[index][j]==-1) { count++; if(index>0) index--; else break; } CCLog("j = %d i= %d COUNT = %d",j,i,count); nodeMove(dir_guester,j,i,count); change2number(arr_Num[i][j],arr_Num[i-count][j]); } } } logcat_chessArr("move-yd2"); move_state = MOVE_OVER; } else if(move_state == MOVE_OVER) { CCLog("down-----------move-over---over"); addNewChess(); if(checkFull()) { bool downover = checkGameOver(); CCLog("downover = %d",downover); } move_state = MOVE_NONE; } } }
BuffEffect::BuffEffect(int score) { this->score = score; counter = 0; addScore(); }