int Env::_keyHook(void) { int ch; int moved = 0; while ((ch = getch())) { if (ch == ERR) break ; if ((ch == K_UP || ch == K_DOWN || ch == K_LEFT || ch == K_RIGHT) && moved == 0) { if (ch == K_UP) this->_player->incPosXY(0, -1); else if (ch == K_DOWN) this->_player->incPosXY(0, 1); else if (ch == K_LEFT) this->_player->incPosXY(-1, 0); else if (ch == K_RIGHT) this->_player->incPosXY(1, 0); moved = 1; } else if (ch == K_SPACE) { GameEntity *bullet = new GameEntity(this->_player->getPosX()+1, this->_player->getPosY()); bullet->setMaxMinXY(MAP_LIMITS); bullet->setDirXY(1, 0); addBullet(*bullet); this->_player->shoots++; } else if (ch == ECHAP) return (-1); } return (0); }
tr1::shared_ptr<BulletActor> BulletActorPool::addBullet(BulletMLParser* parser, BulletMLRunner* runner, float x, float y, float deg, float speed, float rank, float speedRank, int shape, int color, float size, float xReverse) { tr1::shared_ptr<BulletActor> ba = addBullet(runner, x, y, deg, speed, rank, speedRank, shape, color, size, xReverse); if (!ba) { tr1::shared_ptr<BulletActor> null; return null; } ba->setTop(parser); return ba; }
void BWSlot::updateBullet(float dt) { _fBulletGroupTime += dt; if(_fBulletGroupTime <= _slotData.fFireTime) { _fBulletSpaceTime += dt; if(_fBulletSpaceTime >= _slotData.fBulletSpaceTime) { _fBulletSpaceTime = 0; addBullet(); } } else if(_fBulletGroupTime >= _slotData.fFireTime + _slotData.fFreeTime) { _fBulletGroupTime = 0; } }
void updateTowers(SubGame *subGame){ printf("update tower start\n"); //Loop through each tower Tower *curTower = subGame->towers; while(curTower != NULL){ curTower->ticksSinceFired++; //shoot things if(curTower->ticksSinceFired >= curTower->fireRate){ Enemy *gonnaGetShot = findEnemyInRange(curTower->x, curTower->y, curTower->range, subGame->enemies); if(gonnaGetShot != NULL){ towerShoot(gonnaGetShot, curTower); addBullet(subGame, curTower, gonnaGetShot); curTower->ticksSinceFired = 0; } } curTower = curTower->next; } printf("update tower end\n"); };
void Player::keyDown(int x) { switch(x) { case ARROW_UP: player_Y_Velocity += 10; break; case ARROW_DOWN: player_Y_Velocity -= 10; break; case ARROW_RIGHT: player_X_Velocity += 10; break; case ARROW_LEFT: player_X_Velocity -= 10; break; case SPACE: addBullet(); break; } }
void HeartGame::handleEvents() { sf::Event eve; while(m_win.pollEvent(eve)) { switch(eve.type) { case sf::Event::Closed: m_win.close(); break; case sf::Event::KeyPressed: if(eve.key.code == sf::Keyboard::Space) addBullet(); if(eve.key.code == sf::Keyboard::Escape) m_win.close(); break; }//switch eve type }//while m win poll event eve }
void Env::_updateEnemies( void ) { static int frame = 0; int vecx = 0; frame++; if (frame == 6) vecx = -1; for (int i = 0, j = 0; this->_enemies[i]; i++) { // Reload if (_enemies[i]->reload() == true) { GameEntity & bullet = _enemies[i]->shoot(MAP_LIMITS); bullet.setMaxMinXY(MAP_LIMITS); addBullet(bullet); } // enemy in player if (this->_enemies[i]->getPosX() == this->_player->getPosX() && this->_enemies[i]->getPosY() == this->_player->getPosY()) this->_player->getKilled(); // inc vec if (this->_enemies[i]->incPosXY(vecx, 0) == -1) { delete this->_enemies[i]; this->_enemies[i] = NULL; for (j = i; this->_enemies[j+1]; j++) { this->_enemies[j] = this->_enemies[j+1]; } this->_enemies[j] = NULL; } } if (frame == 6) { frame = 0; vecx = 0; } }
void updateShips() { for (int i=0; i<MAX_CLIENTS; i++) { if (ships[i].acceleration) { ships[i].yVel-=sin(getRadians(ships[i].angle))*0.1; ships[i].xVel-=cos(getRadians(ships[i].angle))*0.1; } if (ships[i].shooting) { if (ships[i].bulletCooldown ==0) { addBullet(&ships[i]); ships[i].bulletCooldown = ships[i].bulletIntervall; } } ships[i].xPos += ships[i].xVel; ships[i].yPos += ships[i].yVel; if (ships[i].xPos > STAGE_WIDTH) ships[i].xPos=0; if (ships[i].xPos <0) ships[i].xPos=STAGE_WIDTH; if (ships[i].yPos > STAGE_HEIGHT) ships[i].yPos=0; if (ships[i].yPos <0) ships[i].yPos=STAGE_HEIGHT; ships[i].angle += ships[i].angleVel; if (ships[i].angle > 360) ships[i].angle-=360; if (ships[i].angle < 0) ships[i].angle+=360; if (ships[i].bulletCooldown>0) ships[i].bulletCooldown--; } }
//Update plants void Gameboard::UpdatePlants() { //for each squarelist for (int i = 0; i < squaresList.size(); i++) { Plant* plant = squaresList.at(i).getPlant(); //if there is a plant if (plant != nullptr) { //if the plant is a Peashooter if (plant->getType() == "PEASHOOTER"){ //if there are zombies if (!zombiesList.empty()) //shoot ! addBullet(((PeaShooter*)plant)->shoot()); } //if the plant is a Sunplant if (plant->getType() == "SUNPLANT") { //add a sun addSun(((SunPlant*)plant)->produceSun()); } } } }
void Character::loadBulletsXML() { if(directory=="chars/Iguro/") { addBullet(sonido,painter,receiver, /*name*/"lazor", /*sprites_amount*/3, /*hitbox_x*/-120, /*hitbox_y*/-10, /*hitbox_w*/240, /*hitbox_h*/20, /*hitbox_angle*/0, /*damage*/10); addBullet(sonido,painter,receiver, /*name*/"machinegun", /*sprites_amount*/3, /*hitbox_x*/-10, /*hitbox_y*/-10, /*hitbox_w*/20, /*hitbox_h*/20, /*hitbox_angle*/0, /*damage*/2); sonido->addSound("bullet.lazor",directory+string("sounds/lazor.ogg")); //sonido->addSound("bullet.machinegun",directory+string("sounds/machinegun.ogg")); }else { addBullet(sonido,painter,receiver, /*name*/"Eye Lazor", /*sprites_amount*/3, /*hitbox_x*/-40, /*hitbox_y*/0, /*hitbox_w*/80, /*hitbox_h*/6, /*hitbox_angle*/0, /*damage*/20); sonido->addSound("bullet.Eye Lazor",directory+string("sounds/Eye Lazor.ogg")); addBullet(sonido,painter,receiver, /*name*/"Feminist Laser startup", /*sprites_amount*/11, /*hitbox_x*/-1, /*hitbox_y*/-1, /*hitbox_w*/-1, /*hitbox_h*/-1, /*hitbox_angle*/0, /*damage*/0); addBullet(sonido,painter,receiver, /*name*/"Feminist Laser cooldown", /*sprites_amount*/11, /*hitbox_x*/-1, /*hitbox_y*/-1, /*hitbox_w*/-1, /*hitbox_h*/-1, /*hitbox_angle*/0, /*damage*/0); addBullet(sonido,painter,receiver, /*name*/"Feminist Laser active", /*sprites_amount*/4, /*hitbox_x*/-800, /*hitbox_y*/-120, /*hitbox_w*/1600, /*hitbox_h*/240, /*hitbox_angle*/0, /*damage*/60); addBullet(sonido,painter,receiver, /*name*/"Rocket", /*sprites_amount*/2, /*hitbox_x*/-8, /*hitbox_y*/-8, /*hitbox_w*/16, /*hitbox_h*/16, /*hitbox_angle*/0, /*damage*/20); sonido->addSound("bullet.Rocket",directory+string("sounds/Rocket.ogg")); } }
void doPlayer() { int collision; player.thinkTime--; if (player.thinkTime <= 0) { player.thinkTime = 0; } if (input.up == 1) { /* Don't allow the player to move through walls or fences */ collision = doPlayerCollisions(); if (collision != ERROR) { doPlayerWalkAnimation(&walkUpAnimation); } /* set directional player sprite */ player.sprite = getSprite(PLAYER_UP_SPRITE); /* Don't allow the player to move off the screen */ if (player.y < 0) { player.y = 0; } } if (input.down == 1) { /* Don't allow the player to move through walls or fences */ collision = doPlayerCollisions(); if (collision != ERROR) { doPlayerWalkAnimation(&walkDownAnimation); } /* set directional player sprite */ player.sprite = getSprite(PLAYER_DOWN_SPRITE); /* Don't allow the player to move off the screen */ if (player.y + player.sprite->h >= SCREEN_HEIGHT) { player.y = SCREEN_HEIGHT - (player.sprite->h + 1); } } if (input.left == 1) { /* Don't allow the player to move through walls or fences */ collision = doPlayerCollisions(); if (collision != ERROR) { doPlayerWalkAnimation(&walkLeftAnimation); } /* set directional player sprite */ player.sprite = getSprite(PLAYER_LEFT_SPRITE); /* Don't allow the player to move off the screen */ if (player.x < 0) { player.x = 0; } } if (input.right == 1) { /* Don't allow the player to move through walls or fences */ int collision = doPlayerCollisions(); if (collision != ERROR) { doPlayerWalkAnimation(&walkRightAnimation); } /* set directional player sprite */ player.sprite = getSprite(PLAYER_RIGHT_SPRITE); /* Don't allow the player to move off the screen */ if (player.x + player.sprite->w >= SCREEN_WIDTH) { player.x = SCREEN_WIDTH - (player.sprite->w + 1); } } if (input.fire == 1) { /* You can only fire when the thinkTime is 0 or less */ if (player.thinkTime <= 0) { addBullet(player.x + player.sprite->w, player.y + (player.sprite->h / 2)); player.thinkTime = MAX_RELOAD_TIME; } } }
INTERNAL void gameUpdate(GameState *state, Memory *memory, f32 dt) { GameWorldState *world = GET_STATE_DATA(state, &state->persistentArena, GameWorldState); if (!common_isSet(world->flags, gameworldstateflags_init)) { #ifdef DENGINE_DEBUG { u8 *data = (u8 *)world; for (i32 i = 0; i < sizeof(GameWorldState); i++) ASSERT(data[i] == 0); } #endif world->pixelsPerMeter = 70.0f; MemoryIndex entityArenaSize = (MemoryIndex)((f32)memory->transientSize * 0.5f); u8 *arenaBase = state->transientArena.base + state->transientArena.size; memory_arenaInit(&world->entityArena, arenaBase, entityArenaSize); world->camera.min = V2(0, 0); world->camera.max = state->renderer.size; world->size = state->renderer.size; world->entityListSize = 1024; world->entityList = MEMORY_PUSH_ARRAY(&world->entityArena, world->entityListSize, Entity); { // Init null entity Entity *nullEntity = &world->entityList[world->entityIndex++]; nullEntity->id = world->entityIdCounter++; } { // Init asteroid entities world->numAsteroids = 15; } { // Init audio renderer world->numAudioRenderers = 8; world->audioRenderer = MEMORY_PUSH_ARRAY( &world->entityArena, world->numAudioRenderers, AudioRenderer); } { // Global Collision Rules setCollisionRule(world, entitytype_ship, entitytype_asteroid_small, TRUE); setCollisionRule(world, entitytype_ship, entitytype_asteroid_medium, TRUE); setCollisionRule(world, entitytype_ship, entitytype_asteroid_large, TRUE); setCollisionRule(world, entitytype_bullet, entitytype_asteroid_small, TRUE); setCollisionRule(world, entitytype_bullet, entitytype_asteroid_medium, TRUE); setCollisionRule(world, entitytype_bullet, entitytype_asteroid_large, TRUE); } world->numStarP = 100; world->starPList = MEMORY_PUSH_ARRAY(&world->entityArena, world->numStarP, v2); world->starMinOpacity = 0.25f; for (i32 i = 0; i < world->numStarP; i++) { i32 randX = rand() % (i32)world->size.x; i32 randY = rand() % (i32)world->size.y; world->starPList[i] = V2i(randX, randY); } world->flags |= gameworldstateflags_init; world->scoreMultiplier = 5; world->scoreMultiplierBarTimer = 0.0f; world->scoreMultiplierBarThresholdInS = 2.0f; } if (common_isSet(world->flags, gameworldstateflags_level_started)) { Font *arial40 = asset_fontGet(&state->assetManager, "Arial", 40); Renderer *renderer = &state->renderer; /* Render scores onto screen */ v2 stringP = V2((renderer->size.w * 0.5f), renderer->size.h - arial40->size); char gamePointsString[COMMON_ITOA_MAX_BUFFER_32BIT] = {0}; common_itoa(world->score, gamePointsString, ARRAY_COUNT(gamePointsString)); renderer_stringFixedCentered(renderer, &state->transientArena, arial40, gamePointsString, stringP, V2(0, 0), 0, V4(1.0f, 1.0f, 1.0f, 1.0f), 1, 0); /* Render multiplier accumulator bar onto screen */ v2 stringDim = asset_fontStringDimInPixels(arial40, gamePointsString); v2 multiplierOutlineSize = V2(renderer->size.w * 0.5f, stringDim.h * 0.25f); v2 multiplierOutlineP = V2(renderer->size.w * 0.5f, stringP.h); multiplierOutlineP.x -= (multiplierOutlineSize.w * 0.5f); multiplierOutlineP.y -= stringDim.h * 1.5f; renderer_rectFixedOutline( renderer, multiplierOutlineP, multiplierOutlineSize, V2(0, 0), 2, 0, NULL, V4(0.2f, 0.3f, 0.8f, 1.0f), 2, renderflag_no_texture); f32 progressNormalised = world->scoreMultiplierBarTimer / world->scoreMultiplierBarThresholdInS; renderer_rectFixed(renderer, multiplierOutlineP, V2(multiplierOutlineSize.w * progressNormalised, multiplierOutlineSize.h), V2(0, 0), 0, NULL, V4(0.2f, 0.3f, 0.8f, 1.0f), 1, renderflag_no_texture); /* Render multiplier counter hud onto screen */ v2 multiplierHudP = V2(0, 0.05f * renderer->size.h); v2 multiplierHudSize = V2((arial40->maxSize.w * 3.5f), arial40->fontHeight * 1.2f); renderer_rectFixed(renderer, multiplierHudP, multiplierHudSize, V2(0, 0), 0, NULL, V4(1, 1, 1, 0.1f), 2, renderflag_no_texture); /* Render multiplier counter string to hud */ char multiplierToString[COMMON_ITOA_MAX_BUFFER_32BIT + 1] = {0}; common_itoa(world->scoreMultiplier, multiplierToString + 1, ARRAY_COUNT(multiplierToString) - 1); multiplierToString[0] = 'x'; v2 multiplierToStringP = multiplierHudP; multiplierToStringP = v2_add(multiplierToStringP, v2_scale(multiplierHudSize, 0.5f)); renderer_stringFixedCentered( renderer, &state->transientArena, arial40, multiplierToString, multiplierToStringP, V2(0, 0), 0, V4(1.0f, 1.0f, 1.0f, 1.0f), 3, 0); /* Process multiplier bar updates */ if (!common_isSet(world->flags, gameworldstateflags_player_lost)) { f32 barTimerPenalty = 1.0f; if (world->timeSinceLastShot < 1.5f) { barTimerPenalty = 0.1f; } world->scoreMultiplierBarTimer += (barTimerPenalty * dt); world->timeSinceLastShot += dt; if (world->scoreMultiplierBarTimer > world->scoreMultiplierBarThresholdInS) { world->scoreMultiplierBarTimer = 0; world->scoreMultiplier++; if (world->scoreMultiplier > 9999) world->scoreMultiplier = 9999; } } } if (common_isSet(world->flags, gameworldstateflags_player_lost)) { Font *arial40 = asset_fontGet(&state->assetManager, "Arial", 40); char *gameOver = "Game Over"; v2 gameOverP = v2_scale(state->renderer.size, 0.5f); renderer_stringFixedCentered( &state->renderer, &state->transientArena, arial40, "Game Over", gameOverP, V2(0, 0), 0, V4(1, 1, 1, 1), 0, 0); v2 gameOverSize = asset_fontStringDimInPixels(arial40, gameOver); v2 replayP = V2(gameOverP.x, gameOverP.y - (gameOverSize.h * 1.2f)); renderer_stringFixedCentered( &state->renderer, &state->transientArena, arial40, "Press enter to play again or backspace to return to menu", replayP, V2(0, 0), 0, V4(1, 1, 1, 1), 0, 0); if (platform_queryKey(&state->input.keys[keycode_enter], readkeytype_one_shot, 0.0f)) { // TODO(doyle): Extract score init default values to some game // definitions file world->score = 0; world->scoreMultiplier = 5; world->scoreMultiplierBarTimer = 0.0f; world->scoreMultiplierBarThresholdInS = 2.0f; addPlayer(world); world->flags ^= gameworldstateflags_player_lost; } else if (platform_queryKey(&state->input.keys[keycode_backspace], readkeytype_one_shot, 0.0f)) { common_memset((u8 *)world, 0, sizeof(*world)); state->currState = appstate_StartMenuState; return; } } for (u32 i = world->asteroidCounter; i < world->numAsteroids; i++) addAsteroid(world, (rand() % asteroidsize_count)); Radians starRotation = DEGREES_TO_RADIANS(45.0f); v2 starSize = V2(2, 2); ASSERT(world->starMinOpacity >= 0.0f && world->starMinOpacity <= 1.0f); f32 opacityFadeRateInS = 0.5f; if (world->starFadeAway) { opacityFadeRateInS *= -1.0f; } if (world->starOpacity > 1.0f) { world->starOpacity = 1.0f; world->starFadeAway = TRUE; } else if (world->starOpacity < world->starMinOpacity) { world->starOpacity = world->starMinOpacity; world->starFadeAway = FALSE; } world->starOpacity += (opacityFadeRateInS * dt); DEBUG_PUSH_VAR("Star Opacity: %5.2f", world->starOpacity, "f32"); for (i32 i = 0; i < world->numStarP; i++) { world->starPList[i] = v2_add(world->starPList[i], V2(4.0f * dt, 0)); world->starPList[i] = wrapPAroundBounds( world->starPList[i], math_rectCreate(V2(0, 0), world->size)); renderer_rect(&state->renderer, world->camera, world->starPList[i], starSize, V2(0, 0), starRotation, NULL, V4(0.8f, 0.8f, 0.8f, world->starOpacity), 0, renderflag_no_texture | renderflag_wireframe); } #ifdef DENGINE_DEBUG if (platform_queryKey(&state->input.keys[keycode_left_square_bracket], readkeytype_repeat, 0.2f)) { addAsteroid(world, (rand() % asteroidsize_count)); } #endif ASSERT(world->entityList[0].id == NULL_ENTITY_ID); for (i32 i = 1; i < world->entityIndex; i++) { Entity *entity = &world->entityList[i]; ASSERT(entity->type != entitytype_invalid); v2 pivotPoint = {0}; f32 ddPSpeedInMs = 0; v2 ddP = {0}; if (entity->type == entitytype_ship) { if (platform_queryKey(&state->input.keys[keycode_up], readkeytype_repeat, 0.0f)) { // TODO(doyle): Renderer creates upfacing triangles by default, // but we need to offset rotation so that our base "0 degrees" // is right facing for trig to work Radians rotation = DEGREES_TO_RADIANS((entity->rotation + 90.0f)); v2 direction = V2(math_cosf(rotation), math_sinf(rotation)); ddP = direction; AudioVorbis *thrust = asset_vorbisGet(&state->assetManager, "thrust"); AudioRenderer *audioRenderer = getFreeAudioRenderer(world, thrust, 3); if (audioRenderer) { audio_vorbisPlay(&state->transientArena, &state->audioManager, audioRenderer, thrust, 1); } } if (platform_queryKey(&state->input.keys[keycode_space], readkeytype_one_shot, KEY_DELAY_NONE)) { addBullet(world, entity); if (world->timeSinceLastShot >= 0) { world->timeSinceLastShot = 0; f32 multiplierPenalty = -2.0f; world->timeSinceLastShot += multiplierPenalty; } AudioVorbis *fire = asset_vorbisGet(&state->assetManager, "fire"); AudioRenderer *audioRenderer = getFreeAudioRenderer(world, fire, 2); if (audioRenderer) { // TODO(doyle): Atm transient arena is not used, this is // just to fill out the arguments audio_vorbisPlay(&state->transientArena, &state->audioManager, audioRenderer, fire, 1); } } Degrees rotationsPerSecond = 180.0f; if (platform_queryKey(&state->input.keys[keycode_left], readkeytype_repeat, 0.0f)) { entity->rotation += (rotationsPerSecond)*dt; } if (platform_queryKey(&state->input.keys[keycode_right], readkeytype_repeat, 0.0f)) { entity->rotation -= (rotationsPerSecond)*dt; } entity->rotation = (f32)((i32)entity->rotation); ddPSpeedInMs = 25; DEBUG_PUSH_VAR("Pos: %5.2f, %5.2f", entity->pos, "v2"); DEBUG_PUSH_VAR("Velocity: %5.2f, %5.2f", entity->dP, "v2"); DEBUG_PUSH_VAR("Rotation: %5.2f", entity->rotation, "f32"); DEBUG_PUSH_VAR("TimeSinceLastShot: %5.2f", world->timeSinceLastShot, "f32"); renderer_rect(&state->renderer, world->camera, entity->pos, V2(5, 5), V2(0, 0), DEGREES_TO_RADIANS(entity->rotation), NULL, V4(1.0f, 1.0f, 1.0f, 1.0f), 0, renderflag_no_texture); } else if (entity->type >= entitytype_asteroid_small && entity->type <= entitytype_asteroid_large) { i32 randValue = rand(); // NOTE(doyle): If it is a new asteroid with no dp set, we need to // set a initial dp for it to move from. v2 localDp = {0}; if ((i32)entity->dP.x == 0 && (i32)entity->dP.y == 0) { enum Direction direction = randValue % direction_count; switch (direction) { case direction_north: case direction_northwest: { localDp.x = 1.0f; localDp.y = 1.0f; } break; case direction_west: case direction_southwest: { localDp.x = -1.0f; localDp.y = -1.0f; } break; case direction_south: case direction_southeast: { localDp.x = 1.0f; localDp.y = -1.0f; } break; case direction_east: case direction_northeast: { localDp.x = 1.0f; localDp.y = 1.0f; } break; default: { ASSERT(INVALID_CODE_PATH); } break; } } // NOTE(doyle): Otherwise, if it has pre-existing dp, maintain our // direction by extrapolating from it's current dp else { if (entity->dP.x >= 0) localDp.x = 1.0f; else localDp.x = -1.0f; if (entity->dP.y >= 0) localDp.y = 1.0f; else localDp.y = -1.0f; } /* NOTE(doyle): We compare current dP with the calculated dP. In the event we want to artificially boost the asteroid, we set a higher dP on creation, which will have a higher dP than the default dP we calculate. So here we choose to keep it until it decays enough that the default dP of the asteroid is accepted. */ v2 newDp = v2_scale(localDp, world->pixelsPerMeter * 1.5f); f32 newDpSum = ABS(newDp.x) + ABS(newDp.y); f32 oldDpSum = ABS(entity->dP.x) + ABS(entity->dP.y); if (newDpSum > oldDpSum) { entity->dP = newDp; } } else if (entity->type == entitytype_bullet) { if (!math_rectContainsP(world->camera, entity->pos)) { deleteEntity(world, i--); continue; } Radians rotation = DEGREES_TO_RADIANS((entity->rotation + 90.0f)); v2 localDp = V2(math_cosf(rotation), math_sinf(rotation)); entity->dP = v2_scale(localDp, world->pixelsPerMeter * 5); } else if (entity->type == entitytype_particle) { f32 diff = entity->color.a - 0.1f; if (diff < 0.01f) { deleteEntity(world, i--); continue; } f32 divisor = MAX(entity->particleInitDp.x, entity->particleInitDp.y); f32 maxDp = MAX(entity->dP.x, entity->dP.y); entity->color.a = maxDp / divisor; } entity->pos = wrapPAroundBounds(entity->pos, math_rectCreate(V2(0, 0), world->size)); /* Loop entity around world */ i32 collisionIndex = moveEntity(world, &state->transientArena, entity, i, ddP, dt, ddPSpeedInMs); v4 collideColor = {0}; if (collisionIndex != -1) { ASSERT(collisionIndex < world->entityIndex); Entity *collideEntity = &world->entityList[collisionIndex]; Entity *colliderA; Entity *colliderB; if (collideEntity->type < entity->type) { colliderA = collideEntity; colliderB = entity; } else { colliderA = entity; colliderB = collideEntity; } // Assumptions made that the collision detect system relies on ASSERT(entitytype_ship < entitytype_asteroid_small); ASSERT(entitytype_asteroid_small < entitytype_asteroid_medium); ASSERT(entitytype_asteroid_medium < entitytype_asteroid_large); ASSERT(entitytype_asteroid_large < entitytype_bullet); ASSERT(entitytype_asteroid_small + 1 == entitytype_asteroid_medium); ASSERT(entitytype_asteroid_medium + 1 == entitytype_asteroid_large); if (colliderA->type >= entitytype_asteroid_small && colliderA->type <= entitytype_asteroid_large) { f32 numParticles = 4; if (colliderA->type == entitytype_asteroid_medium) { AsteroidSpec spec = {0}; spec.pos = colliderA->pos; spec.dP = v2_scale(colliderA->dP, -2.0f); addAsteroidWithSpec(world, asteroidsize_small, &spec); numParticles = 8; world->score += (10 * world->scoreMultiplier); } else if (colliderA->type == entitytype_asteroid_large) { AsteroidSpec spec = {0}; spec.pos = colliderA->pos; spec.dP = v2_scale(colliderA->dP, -4.0f); addAsteroidWithSpec(world, asteroidsize_medium, &spec); spec.dP = v2_perpendicular(spec.dP); addAsteroidWithSpec(world, asteroidsize_small, &spec); spec.dP = v2_perpendicular(colliderA->dP); addAsteroidWithSpec(world, asteroidsize_small, &spec); numParticles = 16; world->score += (20 * world->scoreMultiplier); } else { world->score += (5 * world->scoreMultiplier); } for (i32 i = 0; i < numParticles; i++) { { // Add particles Entity *particle = &world->entityList[world->entityIndex++]; particle->id = world->entityIdCounter++; particle->pos = colliderA->pos; particle->size = V2(4.0f, 4.0f); i32 randValue = rand(); Radians rotation = DEGREES_TO_RADIANS((randValue % 360)); v2 randDirectionVec = V2(math_cosf(rotation), math_sinf(rotation)); i32 particleDpLimit = 8; f32 randDpMultiplier = (f32)(randValue % particleDpLimit) + 1; v2 newDp = v2_scale(colliderA->dP, randDpMultiplier); newDp = v2_hadamard(newDp, randDirectionVec); particle->dP = newDp; particle->particleInitDp = newDp; particle->offset = v2_scale(particle->size, -0.5f); particle->hitbox = particle->size; particle->rotation = 0; particle->renderMode = rendermode_polygon; if (!world->particleVertexCache) { world->particleVertexCache = MEMORY_PUSH_ARRAY(&world->entityArena, 4, v2); world->particleVertexCache[0] = V2(0, particle->size.h); world->particleVertexCache[1] = V2(0, 0); world->particleVertexCache[2] = V2(particle->size.w, 0); world->particleVertexCache[3] = particle->size; } particle->vertexPoints = world->particleVertexCache; particle->numVertexPoints = 4; particle->type = entitytype_particle; particle->color = V4(1.0f, 0.0f, 0, 1.0f); } } ASSERT(colliderB->type == entitytype_bullet); deleteEntity(world, collisionIndex); deleteEntity(world, i--); world->asteroidCounter--; ASSERT(world->asteroidCounter >= 0); char *sound; i32 choice = rand() % 3; if (choice == 0) { sound = "bang_small"; } else if (choice == 1) { sound = "bang_medium"; } else { sound = "bang_large"; } AudioVorbis *explode = asset_vorbisGet(&state->assetManager, sound); AudioRenderer *audioRenderer = getFreeAudioRenderer(world, explode, 3); if (audioRenderer) { audio_vorbisPlay(&state->transientArena, &state->audioManager, audioRenderer, explode, 1); } continue; } else if (colliderA->type == entitytype_ship) { if (colliderB->type >= entitytype_asteroid_small && colliderB->type <= entitytype_asteroid_large) { world->flags |= gameworldstateflags_player_lost; if (collideEntity->type == entitytype_ship) { deleteEntity(world, collisionIndex); } else { deleteEntity(world, i--); } AudioVorbis *explode = asset_vorbisGet(&state->assetManager, "bang_large"); AudioRenderer *audioRenderer = getFreeAudioRenderer(world, explode, 3); if (audioRenderer) { audio_vorbisPlay(&state->transientArena, &state->audioManager, audioRenderer, explode, 1); } continue; } } } RenderFlags flags = renderflag_wireframe | renderflag_no_texture; renderer_entity(&state->renderer, &state->transientArena, world->camera, entity, V2(0, 0), 0, collideColor, 0, flags); } for (i32 i = 0; i < world->numAudioRenderers; i++) { AudioRenderer *audioRenderer = &world->audioRenderer[i]; audio_updateAndPlay(&state->transientArena, &state->audioManager, audioRenderer); } }
// updatePlayer // updates the player according to game rules void updatePlayer(Player& obj) { if (obj.coolDownCounter > WEAPON_OVERHEAT) obj.overHeated = true; // Input velocity char vx = 0; char vy = 0; byte id; byte tileXMax; byte tileYMax; byte inputDirection = obj.direction; /////////// // input // /////////// bool left = arduboy.pressed(LEFT_BUTTON); bool right = arduboy.pressed(RIGHT_BUTTON); bool up = arduboy.pressed(UP_BUTTON); bool down = arduboy.pressed(DOWN_BUTTON); bool rungun = arduboy.pressed(A_BUTTON); bool standgun = arduboy.pressed(B_BUTTON); bool strafegun = rungun; obj.walking = up || down || left || right; //obj.walking = (standgun && !rungun) ? false : obj.walking; //////////// // timers // //////////// // Diagonal anti-jerk timer if (obj.diagonalTime > 0) obj.diagonalTime--; if ((up && left) || (down && left) || (up && right) || (down && right)) obj.diagonalTime = 4; // Bullet timer if (obj.shotDelay > 0) obj.shotDelay--; //////////////////////// // horizontal physics // //////////////////////// // input if (left) vx = -1; else if (right) vx = 1; // update position //if(strafegun || !standgun) obj.x += vx; // collide with zombies zombieCollide(obj.x, obj.y, true, vx, PLAYER_WIDTH, PLAYER_HEIGHT); // collide with walls mapCollide(obj.x, obj.y, true, vx, PLAYER_WIDTH, PLAYER_HEIGHT); ////////////////////// // vertical physics // ////////////////////// // input if (up) vy = -1; else if (down) vy = 1; // update position //if(strafegun || !standgun) obj.y += vy; // collide with zombies zombieCollide(obj.x, obj.y, false, vy, PLAYER_WIDTH, PLAYER_HEIGHT); // collide with walls mapCollide(obj.x, obj.y, false, vy, PLAYER_WIDTH, PLAYER_HEIGHT); // collide with survivors survivorCollide(obj.x, obj.y); // collide with door if (checkDoorCollision()) gameState = STATE_GAME_PREPARE_LEVEL; // collide with pickup pickupCollision(obj.x, obj.y); /////////////// // direction // /////////////// // Update camera direction according to the way the player is moving if (!strafegun) { if (left) { inputDirection = PLAYER_FACING_WEST; if (up) inputDirection = PLAYER_FACING_NORTHWEST; else if (down) inputDirection = PLAYER_FACING_SOUTHWEST; } else if (right) { inputDirection = PLAYER_FACING_EAST; if (up) inputDirection = PLAYER_FACING_NORTHEAST; else if (down) inputDirection = PLAYER_FACING_SOUTHEAST; } else if (up) { inputDirection = PLAYER_FACING_NORTH; } else if (down) { inputDirection = PLAYER_FACING_SOUTH; } } obj.direction = inputDirection; // the camera will only be updated if moving nondiagonally or look mode if ((standgun && !rungun) || (obj.direction % 2) == 0) { obj.camDirection = inputDirection; } //////////// // timers // //////////// if (arduboy.everyXFrames(4)) { if (obj.coolDownCounter > 1)obj.coolDownCounter--; if ((arduboy.pressed(A_BUTTON) || arduboy.pressed(B_BUTTON)) && !obj.overHeated) obj.coolDownCounter += 2; if (obj.overHeated) coolGirl.coolDownVisible = !coolGirl.coolDownVisible; } if ((standgun || rungun) && !obj.overHeated) { if (obj.shotDelay == 0) { addBullet(obj.x + 10, obj.y + 12, obj.direction, 0, 0); obj.shotDelay = 10; } } if ((obj.overHeated == true) && (obj.coolDownCounter < 2)) { obj.overHeated = false; obj.coolDownVisible = true; } // Update animation if (arduboy.everyXFrames(6) && obj.walking) obj.frame++; if (obj.frame > 3 ) obj.frame = 0; // update score if (rollingScore > 0) { rollingScore -= 5; scorePlayer += 5; } // update flashing if (obj.flashTime > 0) obj.flashTime--; //////////// // camera // //////////// // update camera short mapGoalX = coolGirl.x - WIDTH / 2 + PLAYER_WIDTH / 2; short mapGoalY = coolGirl.y - HEIGHT / 2 + PLAYER_HEIGHT / 2 - 4; // hud offset // offset the goal by the direction mapGoalX += BulletXVelocities[coolGirl.camDirection] * 4; mapGoalY += BulletXVelocities[(coolGirl.camDirection + 6) % 8] * 4; // move the camera toward the desired location mapPositionX = burp(mapPositionX, mapGoalX, 3); mapPositionY = burp(mapPositionY, mapGoalY, 3); // Clamp on screen boundaries mapPositionX = (mapPositionX < 0) ? 0 : mapPositionX; mapPositionX = (mapPositionX > LEVEL_WIDTH - WIDTH) ? LEVEL_WIDTH - WIDTH : mapPositionX; mapPositionY = (mapPositionY < 0) ? 0 : mapPositionY; mapPositionY = (mapPositionY > LEVEL_HEIGHT - HEIGHT) ? LEVEL_HEIGHT - HEIGHT : mapPositionY; }
void gameUpdate(void) { point vertex, port, starboard, exhaust, playerPos; point playerShip[5]; int i, j; //Level defaults to finished, changed when rocks or enemies are alive. HWREGBITW(&gFlags, LEVEL_COMPLETE) = True; //Update player gPlayer.x += gPlayer.dx; gPlayer.y += gPlayer.dy; gPlayer.x = floatMod(gPlayer.x, 128); gPlayer.y = floatMod(gPlayer.y, 96); gPlayer.dx = (gPlayer.dx*SPEED_DECAY); gPlayer.dy = (gPlayer.dy*SPEED_DECAY); gPlayer.exhaustOn = False; playerPos = makePoint((int)gPlayer.x, (int)gPlayer.y); vertex = rotPoint(playerPos, gPlayer.angle, makePoint(playerPos.x+6, playerPos.y)); port = rotPoint(playerPos, gPlayer.angle, makePoint(playerPos.x-5, playerPos.y-5)); starboard = rotPoint(playerPos, gPlayer.angle, makePoint(playerPos.x-5, playerPos.y+5)); exhaust = rotPoint(playerPos, gPlayer.angle, makePoint(playerPos.x-3, playerPos.y)); playerShip[0] = vertex; playerShip[1] = port; playerShip[2] = exhaust; playerShip[3] = starboard; playerShip[4] = makePoint((int)gPlayer.x, (int)gPlayer.y); switch(gPlayer.status) { case ALIVE: ////Button movement input //Forward (up) if ((GPIO_PORTG_DATA_R&0x08) == 0 || HWREGBITW(&gFlags, ANALOG_UP)) { if((gPlayer.dx*gPlayer.dx + gPlayer.dy*gPlayer.dy) < MAX_PLAYER_SPEED*MAX_PLAYER_SPEED) { gPlayer.dx += cosDeg(gPlayer.angle)*PLAYER_ACCEL; gPlayer.dy -= sinDeg(gPlayer.angle)*PLAYER_ACCEL; } gPlayer.exhaustOn = True; } //Left if((GPIO_PORTG_DATA_R&0x20) == 0) {//|| HWREGBITW(&gFlags, ANALOG_LEFT)) { gPlayer.angle += PLAYER_TURN_RATE; } //Right if((GPIO_PORTG_DATA_R&0x40) == 0) {// || HWREGBITW(&gFlags, ANALOG_RIGHT)) { gPlayer.angle -= PLAYER_TURN_RATE; } //Select (positive edge) if((GPIO_PORTG_DATA_R & 0x80) != 0) { selectNotPressed = True; } if(HWREGBITW(&gFlags, SELECT_DOWN) == 1 || (selectNotPressed == True && (GPIO_PORTG_DATA_R & 0x80) == 0)) { selectNotPressed = False; if(HWREGBITW(&gFlags, TITLE_SCREEN) == True) { HWREGBITW(&gFlags, TITLE_SCREEN) = False; setXYAvg(); } HWREGBITW(&gFlags, SELECT_DOWN) = 0; //reset flag addBullet(makePoint((int)gPlayer.x, (int)gPlayer.y), (cosDeg(gPlayer.angle)*MAX_BULLET_SPEED), -1*(sinDeg(gPlayer.angle)*MAX_BULLET_SPEED), True); } break; case HIT: gPlayer.status = DEAD; addExplosion(makePoint(gPlayer.x, gPlayer.y), 12); gPlayer.dx = 0; gPlayer.dy = 0; killBullets(); killRocks(); break; case DEAD: //Wait for explosions to stop, then stop updating the game. for(i = 0; i < MAX_EXPLOSIONS; i++) { if(gExplosions[i].status == ALIVE) { break; } } HWREGBITW(&gFlags, LEVEL_COMPLETE) = False; HWREGBITW(&gFlags, GAME_OVER) = True; killRocks(); killBullets(); killEnemies(); return; } if(HWREGBITW(&gFlags, TITLE_SCREEN) == True) { return; } //Update bullets for(i = 0; i < MAX_PLAYER_BULLETS; i++) { switch(gPlayerBullets[i].status) { //Only update visible bullets. case ALIVE: if(gPlayerBullets[i].life++ > BULLET_LIFETICKS) { gPlayerBullets[i].status = DEAD; break; } gPlayerBullets[i].x = gPlayerBullets[i].x+gPlayerBullets[i].dx; gPlayerBullets[i].y = gPlayerBullets[i].y+gPlayerBullets[i].dy; break; case HIT: break; case DEAD: break; } } for(i = 0; i < MAX_ENEMY_BULLETS; i++) { switch(gEnemyBullets[i].status) { //Only update visible bullets. case ALIVE: if(gEnemyBullets[i].life++ > BULLET_LIFETICKS) { gEnemyBullets[i].status = DEAD; break; } HWREGBITW(&gFlags, LEVEL_COMPLETE) = False; gEnemyBullets[i].x = gEnemyBullets[i].x+gEnemyBullets[i].dx; gEnemyBullets[i].y = gEnemyBullets[i].y+gEnemyBullets[i].dy; break; case HIT: break; case DEAD: break; } } //Update rocks for(i = 0; i < MAX_ROCKS; i++) { switch(gRocks[i].status) { case ALIVE: //Only update visible rocks. HWREGBITW(&gFlags, LEVEL_COMPLETE) = False; //Update rock position if(gRocks[i].dx < 0.1 && gRocks[i].dy < 0.1) { gRocks[i].dx = (randRange(32,64)*-1+randRange(32,64)*1)/64.; gRocks[i].dy = randRange(0,256)/256; } gRocks[i].x = floatMod(gRocks[i].x+gRocks[i].dx, 128); gRocks[i].y = floatMod(gRocks[i].y+gRocks[i].dy, 96); //Check collisions with enemies, players and bullets. //Player collision for(j = 0; j < 5; j++) { if(pointInRock(makePoint(((int)gRocks[i].x), ((int)gRocks[i].y)), gRocks[i].rockType, gRocks[i].rockSize, playerShip[j])) { gPlayer.status = HIT; return; } } //Bullet collision for(j = 0; j < MAX_PLAYER_BULLETS; j++) { if(gPlayerBullets[j].status == ALIVE) { if(pointInRock(makePoint(((int)gRocks[i].x), ((int)gRocks[i].y)), gRocks[i].rockType, gRocks[i].rockSize, makePoint(((int)gPlayerBullets[j].x), ((int)gPlayerBullets[j].y)))) { score += 1; addExplosion(makePoint(gPlayerBullets[j].x, gPlayerBullets[j].y), 2); gRocks[i].status = HIT; gPlayerBullets[j].status = DEAD; } } }/* for(j = 0; j < MAX_ENEMY_BULLETS; j++) { if(gEnemyBullets[i].status == ALIVE) { if(pointInRock(makePoint(((int)gRocks[i].x), ((int)gRocks[i].y)), gRocks[i].rockType, gRocks[i].rockSize, makePoint(((int)gEnemyBullets[j].x)%128, ((int)gEnemyBullets[j].y)%96))) { gRocks[i].status = HIT; addExplosion(makePoint(gEnemyBullets[j].x, gEnemyBullets[j].y), 2); gEnemyBullets[j].status = DEAD; } } }*/ if(gRocks[i].status == ALIVE) { break; } case HIT: if(gRocks[i].rockSize > 1) { addRock(makePoint((int)gRocks[i].x+1, (int)gRocks[i].y+1), randRange(24, 64)/-64., randRange(24, 64)/-64., gRocks[i].rockSize-1); addRock(makePoint((int)gRocks[i].x-1, (int)gRocks[i].y-1), randRange(64, 24)/64., randRange(64, 24)/64., gRocks[i].rockSize-1); } gRocks[i].status = DEAD; break; case DEAD: break; } } //Update UFOs for(i = 0; i < MAX_UFOS; i++) { switch(gUFOs[i].status) { case ALIVE: //Only update visible rocks. HWREGBITW(&gFlags, LEVEL_COMPLETE) = False; //Update rock position if(gUFOs[i].dx < 0.1 && gUFOs[i].dy < 0.1) { gUFOs[i].dx = (randRange(32,64)*-1+randRange(32,64)*1)/64.; gUFOs[i].dy = randRange(0,256)/256; } gUFOs[i].pos.x = floatMod(gUFOs[i].pos.x+gUFOs[i].dx, 128); gUFOs[i].pos.y = floatMod(gUFOs[i].pos.y+gUFOs[i].dy, 96); if(gUFOs[i].status == ALIVE) { break; } case HIT: gUFOs[i].status = DEAD; break; case DEAD: break; } } //Update explosions for(i = 0; i < MAX_EXPLOSIONS; i++) { if(gExplosions[i].status == ALIVE) { HWREGBITW(&gFlags, LEVEL_COMPLETE) = False; if(gExplosions[i].current++ > gExplosions[i].lifetime) { gExplosions[i].status = DEAD; continue; } } } }
WindowPlanes::WindowPlanes(QDeclarativeItem *parent) : QDeclarativeItem(parent) { number=0; game_state="stop"; bullet_type=1; prop_state=false; save_timer_bullet_to_single=save_timer_two_secs=-1; setX(0); setY(0); planes = new MyPlanes(this); connect(planes,SIGNAL(play_music(QString)),SIGNAL(play_music(QString))); thread = new QThread(this); mythread = new MyThread(this); mythread->moveToThread(thread); connect(this,SIGNAL(myThreadStart()), mythread, SLOT(start())); connect(this,SIGNAL(myThreadStop()), mythread, SLOT(stop())); connect(mythread,SIGNAL(game_over()),SLOT(planes_dit()));//Qt::QueuedConnection connect(mythread,SIGNAL(game_over()),SIGNAL(game_over())); connect(mythread,SIGNAL(captureBomb()),SIGNAL(acquireBomb()));//当用户吃到炸弹道具后发射acquireBomb()信号 connect(mythread,SIGNAL(captureDoubleBullet()),SLOT(bulletToDouble()));//吃到双倍子弹后调用bulletToDouble() thread->start(); #ifdef MEEGO_EDITION_HARMATTAN double bulletScaled=0.8,enemyScaled=0.96,enemy3Scaled=0.88,propScaled=1; #elif defined(Q_OS_SYMBIAN_V5)//判断qt的版本 double bulletScaled=0.8,enemyScaled=0.8,enemy3Scaled=0.66,propScaled=1; #else double bulletScaled=0.6,enemyScaled=0.72,enemy3Scaled=0.66,propScaled=0.75; #endif //planes->setX(width()/2-planes->width()/2);//设置飞机的位置 //planes->setY(height()-planes->height());//设置飞机的位置 image.load(":/Image/Bullets_01.png"); pixmap_bullet1=QPixmap::fromImage(image.scaled(bulletScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/Bullets_02.png"); pixmap_bullet2=QPixmap::fromImage(image.scaled(bulletScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/Bullets_Bomb.png"); pixmap_prop1=QPixmap::fromImage(image.scaled(propScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/Bullets_Dual.png"); pixmap_prop0=QPixmap::fromImage(image.scaled(propScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F2_01.png"); pixmap_enemy1_1=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F2_02.png"); pixmap_enemy1_2=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F2_03.png"); pixmap_enemy1_3=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F2_04.png"); pixmap_enemy1_4=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F2_05.png"); pixmap_enemy1_5=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_01.png"); pixmap_enemy2_1=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_02.png"); pixmap_enemy2_2=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_03.png"); pixmap_enemy2_3=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_04.png"); pixmap_enemy2_4=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_05.png"); pixmap_enemy2_5=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F3_06.png"); pixmap_enemy2_6=QPixmap::fromImage(image.scaled(enemyScaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_01.png"); pixmap_enemy3_1=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_02.png"); pixmap_enemy3_2=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_03.png"); pixmap_enemy3_3=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_04.png"); pixmap_enemy3_4=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_05.png"); pixmap_enemy3_5=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_06.png"); pixmap_enemy3_6=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_07.png"); pixmap_enemy3_7=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_08.png"); pixmap_enemy3_8=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); image.load(":/Image/F4_09.png"); pixmap_enemy3_9=QPixmap::fromImage(image.scaled(enemy3Scaled*image.size(),Qt::KeepAspectRatio,Qt::SmoothTransformation)); connect(&timer_bullet,SIGNAL(timeout()),this,SLOT(addBullet())); connect(&timer_enemy1_1,SIGNAL(timeout()),SLOT(addenemy1_1())); connect(&timer_enemy1_2,SIGNAL(timeout()),SLOT(addenemy1_2())); connect(&timer_enemy1_3,SIGNAL(timeout()),SLOT(addenemy1_3())); connect(&timer_enemy2_1,SIGNAL(timeout()),SLOT(addenemy2_1())); connect(&timer_enemy2_2,SIGNAL(timeout()),SLOT(addenemy2_2())); connect(&timer_enemy2_3,SIGNAL(timeout()),SLOT(addenemy2_3())); connect(&timer_enemy3_1,SIGNAL(timeout()),SLOT(addenemy3_1())); connect(&timer_enemy3_2,SIGNAL(timeout()),SLOT(addenemy3_2())); connect(&timer_enemy3_3,SIGNAL(timeout()),SLOT(addenemy3_3())); connect(&timer_prop,SIGNAL(timeout()),SLOT(addProp())); timer_bullet_to_single.setSingleShot(true); timer_two_secs.setSingleShot(true); connect(&timer_bullet_to_single,SIGNAL(timeout()),SLOT(bulletToSingle())); connect(&timer_two_secs,SIGNAL(timeout()),SLOT(enemy_timer_start())); grade=1; pixmap_bullet=&pixmap_bullet1; }
Sprite *BulletManager::add(Sprite *p) { return addBullet(p->getName()); }
void moveAutoPlayers() { int key; for (int i=0;i<server_data.alien_count;i++) { if(server_data.aliens[i].isauto) { int nearerpos; Alien a=server_data.aliens[i]; int pos; int previ=a.i,prevj=a.j; if(server_data.commando_count ==0) break; int min=0;; for(int pos=0;pos<server_data.commando_count;pos++) { nearerpos=0; if(min>calculate_distance(a.i,a.j,server_data.commandos[pos].i,server_data.commandos[pos].j)) {min=calculate_distance(a.i,a.j,server_data.commandos[pos].i,server_data.commandos[pos].j); nearerpos=pos;} } if(timercount%5==0) { if(a.i > server_data.commandos[nearerpos].i) {key =0;} else if(a.i < server_data.commandos[nearerpos].i) {key =1;} else if(a.j < server_data.commandos[nearerpos].j) {key=3; } else if(a.j > server_data.commandos[nearerpos].j) {key=2; } switch (key) { case 0: if(a.dir!=DOWN)a.dir=DOWN; else if(a.i>0) a.i--; break; case 1: if(a.dir!=UP)a.dir=UP; else if(a.i<(ROWS-1)) a.i++; break; case 2: if(a.dir!=LEFT)a.dir=LEFT; else if(a.j>0) a.j--; break; case 3: if(a.dir!=RIGHT)a.dir=RIGHT; else if(a.j<(COLUMNS-1)) a.j++; break; } if(!(isObstacle(a.i,a.j))) { if(checkAppleCollide(a.i,a.j)!=-1) { Bullet b; b.i = previ; b.j = prevj; b.dir=a.dir; b.pid=a.pid; addBullet(b); } else if(checkBulletCollide(a.i,a.j)!=-1) { a.energy -=20; int bulletpos =checkBulletCollide(a.i,a.j); if(getCommandoIndex(server_data.bullets[bulletpos].pid)!=-1) { int commpos =getCommandoIndex(server_data.bullets[bulletpos].pid); server_data.commandos[commpos].score +=100; } if(getAlienIndex(server_data.bullets[bulletpos].pid)!=-1) { int alienpos =getAlienIndex(server_data.bullets[bulletpos].pid); server_data.aliens[alienpos].score -=100; } if(a.energy <=0) {server_data.map_matrix[a.i][a.j]=NONE;} } else if(CheckPlayerCollide(a.i,a.j)!=-1 && CheckPlayerCollide(a.i,a.j) !=i) { } else { if(checkCommandoCollide(a.i,a.j)==-1) { //server_data.map_matrix[previ][prevj]=NONE; server_data.map_matrix[a.i][a.j]=BOOKED; a.energy -=1; server_data.aliens[i]=a;} else {Bullet b; b.i = previ; b.j = prevj; b.dir=a.dir; b.pid=a.pid; addBullet(b); } } } else { Bullet b; b.i = previ; b.j = prevj; b.dir=a.dir; b.pid=a.pid; addBullet(b); } if(a.energy <= 0) {deleteAlien(i);} if(((key == 2 || key ==3 ) && (!aliensenserhorizontal(nearerpos,i)) )|| (prevj = server_data.commandos[nearerpos].j) && (!aliensenservertical(nearerpos,i)) ) { Bullet b; b.i = a.i; b.j = a.j; b.dir=a.dir; b.pid=a.pid; addBullet(b); } } } } for (int i=0;i<server_data.commando_count;i++) { if(server_data.commandos[i].isauto) { int nearerpos; Commando a=server_data.commandos[i]; int pos; int previ=a.i,prevj=a.j; if(server_data.alien_count ==0) break; int min=0; for(int pos=0;pos<server_data.alien_count;pos++) { nearerpos=0; if(min>calculate_distance(a.i,a.j,server_data.aliens[pos].i,server_data.aliens[pos].j)) {min=calculate_distance(a.i,a.j,server_data.aliens[pos].i,server_data.aliens[pos].j); nearerpos=pos;} } if(timercount%5==0) { if(a.i > server_data.aliens[nearerpos].i) {key =0;} else if(a.i < server_data.aliens[nearerpos].i) {key =1;} else if(a.j < server_data.aliens[nearerpos].j) {key=3; } else if(a.j > server_data.aliens[nearerpos].j) {key=2; } switch (key) { case 0: if(a.dir!=DOWN)a.dir=DOWN; else if(a.i>0) a.i--; break; case 1: if(a.dir!=UP)a.dir=UP; else if(a.i<(ROWS-1)) a.i++; break; case 2: if(a.dir!=LEFT)a.dir=LEFT; else if(a.j>0) a.j--; break; case 3: if(a.dir!=RIGHT)a.dir=RIGHT; else if(a.j<(COLUMNS-1)) a.j++; break; } if(!(isObstacle(a.i,a.j))) { if(checkAppleCollide(a.i,a.j)!=-1) { server_data.map_matrix[server_data.commandos[i].i][server_data.commandos[i].j]=NONE; int pos_app=checkAppleCollide(a.i,a.j); destroyGenerateApple(pos_app); if(server_data.commandos[i].energy <= 100 && server_data.commandos[i].energy >= 80) {server_data.commandos[i].energy =100;} else if(server_data.commandos[i].energy < 80){ server_data.commandos[i].energy+=20; } server_data.commandos[i].score+=100; server_data.commandos[i].i=a.i; server_data.commandos[i].j=a.j; server_data.map_matrix[a.i][a.j]=BOOKED; server_data.commandos[i]=a; } else if(checkBulletCollide(a.i,a.j)!=-1) { a.energy -=25; int bulletpos =checkBulletCollide(a.i,a.j); if(getCommandoIndex(server_data.bullets[bulletpos].pid)!=-1) { int commpos =getCommandoIndex(server_data.bullets[bulletpos].pid); server_data.commandos[commpos].score -=100; } if(getAlienIndex(server_data.bullets[bulletpos].pid)!=-1) { int alienpos =getAlienIndex(server_data.bullets[bulletpos].pid); server_data.aliens[alienpos].score +=100; } if(a.energy <=0) { server_data.map_matrix[a.i][a.j]=NONE;} } else if(checkCommandoCollide(a.i,a.j)!=-1 && checkCommandoCollide(a.i,a.j) !=i) { } else { if(CheckPlayerCollide(a.i,a.j)==-1) { // server_data.map_matrix[previ][prevj]=NONE; server_data.map_matrix[a.i][a.j]=BOOKED; server_data.commandos[i]=a; } else {Bullet b; b.i = previ; b.j = prevj; b.dir=a.dir; b.pid=a.pid; addBullet(b); } } } else{Bullet b; b.i = previ; b.j = prevj; b.dir=a.dir; b.pid=a.pid; addBullet(b); } if(a.energy <= 0) {deleteCommando(i);} // printf("asfasfasdfas***** %d \n ",aliensenserhorizontal(nearerpos,i))); if(((key == 2 || key ==3 ) && (!commandosenserhorizontal(nearerpos,i)) )|| (a.j == server_data.aliens[nearerpos].j) && (!commandosenservertical(nearerpos,i)) ) { Bullet b; b.i = a.i; b.j = a.j; b.dir=a.dir; b.pid=a.pid; addBullet(b);} } } } }