Exemple #1
0
bool Player::Quick(Game_Manager* gm_, coord_def c, float focus_)
{
	if(GetStop())
		return false;
	if(berserker)
		return false;
	switch(quick_menu)
	{
	case 1:
		Special(gm_, c, focus_);
		break;
	case 2:
		Shot(gm_, c, focus_, 2);
		break;
	case 3:
		Shot(gm_, c, focus_, 3);
		break;
	case 4:
		Shot(gm_, c, focus_, 4);
		break;
	case 5:
		UseAbility(gm_, 0);
		break;
	case 6:
		UseAbility(gm_, 1);
		break;
	default:
		return false;
	}
	return true;
}
Exemple #2
0
void	cCancer::CancerShot()
{
	if( m_IsCanShot  )                                                                                                                      
		{
			D3DXVECTOR3	vPos	=	m_vPos;
			m_IsGrow	=	true;
			switch ( rand() % 3 )
			{
			case 0:
				m_fShotRot	=	0.5f;
				m_fShotCoolTime	=	0.2f;
				m_vPos.x -= 0.3f;
				Shot( OI_PLAYER, 2, true, D3DXVECTOR3( 3, 3, 3 ));
				m_vPos.x += 0.6f;
				Shot( OI_PLAYER, 2, false, D3DXVECTOR3( 3, 3, 3 ));
				m_vPos = vPos;
				break;
			case 1:
				m_fShotRot = 1.0f;
				m_fShotCoolTime = 2.0f;
				Shot( OI_PLAYER, 20, true , D3DXVECTOR3( 3, 3, 3 ));
				break;
			case 2:
				m_fShotCoolTime	=	0.4f;
				m_fShotRot	=	0.3f;
				Shot( OI_PLAYER, 8, true , D3DXVECTOR3( 3, 3, 3 ));
				break;
				
			}
		}
}
Exemple #3
0
void Unit_Dig::EnemyMove(void)
{
	// 移動
	VECTOR position;	// ユニットの座標
	VECTOR blockPos;	// ブロックの座標
	position.x = m_x;
	position.y = m_y;

	BlockManager &blockManager = BlockManager::GetInstance();
	// 索ブロック範囲
	BlockBase* block = blockManager.GetNearHardBlock( position, m_Rang * 3.0f );
	if( block != NULL )
	{
		blockPos.x = block->m_x;
		blockPos.y = block->m_y - blockManager.GetDepth();
	}
	else
	{
		return;
	}
	// 向き変え
	DXLibMath::FacingTarget( position, blockPos, &m_Facing, 0.1f);
	// ブロックを探す
	block = blockManager.GetNearHardBlock( position, m_Rang );
	// 硬いブロックがあったら攻撃
	if( block != NULL )
	{
		if( m_AtackCount > 1.0f)
		{
			Shot( block->m_x, block->m_y - blockManager.GetDepth(), true, true, false );
			m_AtackCount -= 1.0f;
		}
		m_AtackCount += m_AttackSpeed;
	}

	// 周りに何も無いなら移動
	VECTOR facing;
	DXLibMath::FacingTarget( position, blockPos, &m_Facing, 0.1f);
	facing.x = blockPos.x - m_x;
	facing.y = blockPos.y - m_y;
	DXLibMath::Normalize( &facing, facing );
	// 通過不可ブロックがあるなら攻撃
	block = blockManager.GetBlock( m_x + facing.x * m_Speed, m_y + facing.y * m_Speed );
	DataManager &data = DataManager::GetInstance();
	if( block != NULL)
	{
		if( m_AtackCount > 1.0f)
		{
			Shot( block->m_x, block->m_y - blockManager.GetDepth(), true, true, false);
			m_AtackCount -= 1.0f;
		}
		m_AtackCount += m_AttackSpeed;
	}
	else
	{
		m_x += facing.x * m_Speed;
		m_y += facing.y * m_Speed;
	}
}
//==============================================================
// 록 샷
void CMover::LockShot(
	bool button,     // 버튼 상태 (눌렸으면 true)
	int min_power,   // 에너지의 최소치
	int max_gauge,   // 연사 게이지의 최대치
	int& power,      // 모은 에너지
	int& gauge       // 연사 게이지
) {
	// 버튼을 누르고 있을 때:
	if (button) {
		
		// 에너지가 부족할 경우:
		// 에너지를 늘리고 연사 게이지를 최대값으로 한 후 
		// 샷을 발사. 구체적인 처리는 Shot 함수에서 수행하기로 함.
		if (power<min_power) {
			power++;
			gauge=max_gauge;
			Shot();
		}
	
		// 에너지가 충분할 경우:
		// 연사 게이지를 0으로 한 후 록 샷을 발사.
		else {
			gauge=0;
			
			// 록 샷을 발사:
			// 적기를 추적할 때는 조준탄을 쏨.
			// ("메인 캐릭터를 향하는 탄"과 같음)
			// 적기를 추적하지 않을 때는 메인 캐릭터의 정면을 향해 발사.
			// ("임의 방향으로 날아가는 탄"과 같음)
			CMover* mover=Group->GetManager()->GetGroup(WEAPON_GROUP)->New();
			mover->Init(Weapon.Laser, this);
		}
	}
	
	// 버튼을 누르고 있지 않을 때:
	else {
		
		// 연사 게이지가 0보다 클 경우:
		// 보통 샷을 쏜 후, 연사 게이지를 1 감소시킴.
		if (gauge>0) {
			Shot();
			gauge--;
		}

		// 에너지를 0으로 함.
		power=0;

		// 록을 해제함
		ClearLockedEnemy();
	}
}
Exemple #5
0
SHOT SeaGrid::ShootSquare(Pos& coords)
{
	//if (0 != std::count(shots.begin(), shots.end(), coords))
	//	throw std::exception();  // can't shoot twice
	shots.push_back(Shot());
	Shot& shot = shots.back();
	shot.result = MISS;
	shot.x = coords.x;
	shot.y = coords.y;
	for (std::vector<Ship>::iterator i=ships.begin(); i != ships.end(); i++)
	{
		Ship& ship = *i;
		for (std::vector<ShipSegment>::iterator j=ship.segments.begin(); j != ship.segments.end(); j++)
		{
			ShipSegment& segment = *j;
			if (segment.pos == coords)
			{
				assert (segment.active);
				segment.active = false;
				if (std::count_if(ship.segments.begin(), ship.segments.end(), is_active))
				{
					shot.result = HIT;
				}
				else
				{
					active_ships--;
					shot.result = SUNK;
				}
				return shot.result;
			}
		}
	}
	return shot.result;
}
Exemple #6
0
void GameWidget::mousePressEvent(QMouseEvent *e)
{
    if (!m_bInteract)
        return;
    int l = (e->modifiers() == (Qt::ShiftModifier | Qt::ControlModifier))?2:1;
    m_shots.push_back(Shot(m_gunX, sizeY-60, l));
}
Exemple #7
0
//classify frames 
void VideoShot::shotDetection()
{
    unsigned int ii = 0; 
    int startFrame, endFrame; 
    int numberOfShots = 0; 
    util = new Utility(); 
    //process frame difference scores 
    while(ii<frameDifferenceScore.size())
    {
        if(frameDifferenceScore[ii]>=shotChangeThreshold)
        {
            endFrame = ii * frameJump; 
            //move out of the transition period    
            while(frameDifferenceScore[++ii]>=shotChangeThreshold)
            {
            }
            //save shot      
            videoShotsVector.push_back(Shot());
            videoShotsVector.back().startFrame = startFrame; 
            videoShotsVector.back().startTime = util->cvtFrameNumber2Time(startFrame, fps); 
            videoShotsVector.back().endFrame = endFrame;
            videoShotsVector.back().endTime = util->cvtFrameNumber2Time(endFrame, fps);
            videoShotsVector.back().shotIndex = numberOfShots; 
            videoShotsVector.back().averageMotion = averageMotion(edgeChangeRatioValue, startFrame/frameJump, ii); 
            videoShotsVector.back().classification = classificationValue[(videoShotsVector.back().averageMotion)>0?1:0]; 
            
            //frame after the transition period
            startFrame = ii * frameJump; 
            //increase number of shots variable
            numberOfShots++;    
        }
        else
        {
            ii++;
        }
    }
    //save last shot
    videoShotsVector.push_back(Shot());
    videoShotsVector.back().startFrame = startFrame; 
    videoShotsVector.back().startTime = util->cvtFrameNumber2Time(startFrame, fps); 
    videoShotsVector.back().endFrame = ii*frameJump; 
    videoShotsVector.back().endTime = util->cvtFrameNumber2Time(ii*frameJump, fps);
    videoShotsVector.back().shotIndex = numberOfShots; 
    videoShotsVector.back().averageMotion = averageMotion(edgeChangeRatioValue, startFrame/frameJump, ii); 
    videoShotsVector.back().classification = classificationValue[(videoShotsVector.back().averageMotion)>0?1:0];
}
//==============================================================
// 연사
void CMover::AutoShot(
	bool button  // 버튼 상태 (눌렸으면 true)
) {
	// 샷의 발사:
	// 버튼이 눌려지면 샷을 발사하기.
	// 발사에 관한 상세한 처리는 Shot 함수에서 수행하기로 함.
	if (button) Shot();
}
Exemple #9
0
void Player::ShotEvent(Game_Manager * gm_)
{
	if (triggercount > 0)
	{
		triggercount--;
		Shot(gm_, aimed_pos, 0.f);
	}
}
Exemple #10
0
void Character::All(){
	Draw();
	if( life > 0 ){
		Move();
		Shot();
	}
	Death();
	
}
Exemple #11
0
 void Sensor::capture(const std::vector<FCam::Shot> &burst) {
     std::vector<Shot> dummyBurst;
     dummyBurst.reserve(burst.size());
     for (unsigned int i=0; i < burst.size(); i++ ) {
         dummyBurst.push_back(Shot(burst[i]));
         dummyBurst[i].id = burst[i].id;
     }
     capture(dummyBurst);
 }
//==============================================================
// 세미 오토 연사
void CMover::SemiAutoShot(
	bool button,    // 버튼 상태 (눌렸으면 true)
	int min_power,  // 에너지의 최소치
	int max_power,  // 에너지의 최대치
	int max_gauge,  // 연사 게이지의 최대치
	int& power,     // 모은 에너지
	int& gauge      // 연사 게이지
) {
	// 버튼을 누르고 있을 때:
	if (button) {
		
		// 에너지가 부족할 경우:
		// 보통 샷을 발사.
		if (power<min_power) Shot();
	
		// 파워를 늘리고, 연사 게이지를 최대로 함.
		if (power<max_power) power++;
		gauge=max_gauge;
	}
	
	// 버튼을 떼고 있을 때:
	else {
		
		// 에너지가 충분할 경우:
		// 에너지 샷을 발사:
		// 모아둔 에너지가 최대치에 도달했을 때는 특별한 샷을 발사.
		if (min_power<=power) {
			if (power==max_power) MaxShot(); 
				else BigShot(power);
			gauge=0;
		}
		
		// 연사 게이지가 0보다 클 경우:
		// 보통 샷을 발사하고, 연사 게이지를 1 감소시킴.
		if (gauge>0) {
			Shot();
			gauge--;
		}

		// 에너지를 0으로 함.
		power=0;
	}
}
void ShotAndLaser(
    bool button,    // 버튼 상태 (눌렸으면 true)
    int min_power,  // 에너지 샷이 발사될 최소한의 파워
    int max_gauge   // 연사 게이지의 최대치
) {
    // 모은 에너지, 연사 게이지
    static int power=0, gauge=0;

    // 버튼을 누르고 있을 때:
    if (button) {

        // 에너지가 부족할 경우:
        // 에너지를 늘려주고 연사 게이지를 최대값으로 하여
        // 샷을 발사함. 구체적인 처리는 Shot 함수에서 수행하기로 함.
        if (power<min_power) {
            power++;
            gauge=max_gauge;
            Shot();
        }

        // 에너지가 충분한 경우:
        // 연사 게이지를 0으로 하고 레이저를 발사.
        // 구체적인 처리는 Laser 함수에서 수행하기로 함.
        else {
            gauge=0;
            Laser();
        }
    }

    // 버튼을 누르고 있지 않을 때:
    else {

        // 연사 게이지가 0보다 클 경우:
        // 보통 샷을 쏘고 연사 게이지를 1 감소시킴.
        if (gauge>0) {
            Shot();
            gauge--;
        }

        // 에너지를 0으로 함.
        power=0;
    }
}
void ShootManager::shootLaser(const VEC3& origin, const VEC3& reach)
{
	PROFILE_FUNCTION("ShootManager: shootLaser");
	/*MAT44 mat = MAT44::Identity;
	mat = MAT44::CreateScale(.1f, .1f, reach);
	mat *= MAT44::CreateFromQuaternion(quat);
	//mat *= MAT44::CreateLookAt(origin, dest, VEC3(0,1,0));
	mat.Translation(origin);*/
	shots.push_back(Shot(origin, reach));
}
//==============================================================
// 연사와 레이저를 함께 사용하기
void CMover::ShotAndLaser(
	bool button,    // 버튼 상태 (눌렸으면 true)
	int min_power,  // 에너지 샷이 발사될 최소한의 파워
	int max_gauge,  // 연사 게이지의 최대치
	int& power,     // 모은 에너지
	int& gauge      // 연사 게이지
) {
	// 버튼을 누르고 있을 때:
	if (button) {
		
		// 에너지가 부족할 경우:
		// 에너지를 늘려주고 연사 게이지를 최대값으로 하여
		// 샷을 발사함. 구체적인 처리는 Shot 함수에서 수행하기로 함.
		if (power<min_power) {
			power++;
			gauge=max_gauge;
			Shot();
		}
	
		// 에너지가 충분한 경우:
		// 연사 게이지를 0으로 하고 레이저를 발사.
		else {
			gauge=0;
			CMover* mover=Group->GetManager()->GetGroup(WEAPON_GROUP)->New();
			if (mover) mover->Init(Weapon.Laser, this);
		}
	}
	
	// 버튼을 누르고 있지 않을 때:
	else {
		
		// 연사 게이지가 0보다 클 경우:
		// 보통 샷을 쏘고 연사 게이지를 1 감소시킴.
		if (gauge>0) {
			Shot();
			gauge--;
		}

		// 에너지를 0으로 함.
		power=0;
	}
}
Exemple #16
0
	void ManagerModel::AddShot(Vec2 startPosition) {
		Shot *shot = DBG_NEW Shot();
		shot->startPosition = startPosition;
		shot->OnInit(this);
		mEntities.push_back(shot);

		for (auto *view : mViews) {
			view->OnShotSpawned((Shot*)shot);
			view->PlayShotSoundEffect((Shot*)shot);
		}
	}
Exemple #17
0
//----------------------------------------------------------------------
//C2PointCurveMoveクラス(2点間曲線移動をする基底クラス)
//----------------------------------------------------------------------
bool C2PointCurveMove::Move()
{
	// 移動範囲、速度
	static const float
		MaxLX=120, MaxRX=520,
		MaxTY=0, MaxBY=480;

	//体力測定
	if(vitality<=0)
	{
		Game->score->AddScore(m_score);
		new CEnemyCrash(X,Y);
		return false;
	}

	// 移動範囲の制限
	if (X<MaxLX) {
		return false;
	}else if (MaxRX<X){
		return false;
	}
	if (Y<MaxTY){
		return false;
	}else if (MaxBY<Y){
		return false;
	}

	// 移動
	//float x=0,y=0;
	if(m_frame_count<=m_time1)
	{
		BezCurve(0.5f*m_frame_count/m_time1,&X,&Y);
		//Y =m_y1+Y_AXEL*(X-m_x1)*(X-m_x1);
		//X +=X_SPEED;
	}
	else if(m_frame_count<=m_time1+m_shot_time)
	{
		Shot();
	}
	else if(m_frame_count<=m_time1+m_shot_time+m_time2)
	{
		BezCurve(0.5f+0.5f*(m_frame_count-m_time1-m_shot_time)/m_time1,&X,&Y);
		//Y =m_y2+Y_AXEL2*(X-m_x2)*(X-m_x2);
		//X +=X_SPEED2;
	}
	else
	{
		new CEnemyCrash(X,Y);
		return false;
	}
	++m_frame_count;
	
	return HitorNot();
}
//==============================================================
// 기본적인 샷 조작
void CMover::BasicShot(
	bool button,       // 지금의 버튼상태
	bool& prev_button  // 이전의 버튼상태
) {
	// 샷의 발사:
	// 전에 버튼이 눌려져 있지 않다가 이번에 처음 눌렸을 때만
	// 샷을 발사함.
	// 샷을 발사하는 구체적인 처리는 Shot 함수에서 수행하기로 함.
	if (!prev_button && button) Shot();
	
	// 지금의 버튼 상태를 저장해 둠
	prev_button=button;
}
Exemple #19
0
  Shot Weapon::fire(GameWorld & world, WeaponFireEventData & eventData) const {
    HIKARI_LOG(debug4) << "Weapon::fire executed. name=" << getName();

    std::list<std::weak_ptr<GameObject>> spawnedObjects;

    std::for_each(std::begin(actions), std::end(actions), [this, &world, &eventData, &spawnedObjects](const std::shared_ptr<WeaponAction> & action) {
      if(action) {
        spawnedObjects.push_back(action->apply(world, *this, eventData));
      }
    });

    return Shot(spawnedObjects);
  }
void EnemyLobber::Continue() {

    fPoint objective = CalculateObjectivePosition();

    if (objective.x > pos.x - speed && objective.x < pos.x + speed) {
        right = BLOCK;
        left = BLOCK;
        LookAtPlayer();
        Shot();
    }
    else if (objective.x > pos.x) {
        right = ACTIVE;
        left = BLOCK;
    }
    else {
        right = BLOCK;
        left = ACTIVE;
    }


    if (objective.y > pos.y - speed && objective.y < pos.y + speed) {
        up = BLOCK;
        down = BLOCK;
        LookAtPlayer();
        Shot();
    }
    else if (objective.y > pos.y) {
        down = ACTIVE;
        up = BLOCK;
    }
    else {
        down = BLOCK;
        up = ACTIVE;
    }

}
Exemple #21
0
void CBeak::Update(float _time, CCamera *_camera, CInput *_input,vector<CEntity* > _listObjectInViewPort)
{
    float timeChange = m_Status == BeakWait ? TIME_CHANGE/2 : TIME_CHANGE;

    if (m_IsLife) {
        if (m_TimeSpent < timeChange) {
            m_TimeSpent += _time;
        } else {
            m_TimeSpent = 0;
            //Change status
            m_Status = m_Status == BeakWait ? BeakShot : BeakWait;
        }

        if (m_Status == BeakShot) {
            if (m_TimeShot < TIME_SHOT) {
                m_TimeShot += _time;
            } else {
                m_TimeShot = 0;
                Shot();
            }
        }

        switch (m_Status)
        {
        case BeakWait:
            m_Sprite->IndexOf(0);
            break;
        case BeakShot:
            m_Sprite->NextOf(_time, 1, 3);
            break;
        default:
            break;
        }
        //Update bullet
        for(int i = 0; i < NUM_BULLET; ++i) {
            if (m_ListBullet[i]->GetActive())
                m_ListBullet[i]->Update(_time,_camera,_input,_listObjectInViewPort);
        }
    } else {
        CEnemy::Update(_time, _camera, _input, _listObjectInViewPort);
        //m_Item->Update(_time,_camera,_input,_listObjectInViewPort);
    }
}
Exemple #22
0
//KeyRelease
void KeyRelease( unsigned char keyPressed, int,int) {

    if ((keyPressed==' ')&&
            (StateMachine==SWING)) {
        GLfloat dx=Ball[0].Pos_xCM()-Camera.Pos_xCM();
        GLfloat dy=Ball[0].Pos_yCM()-Camera.Pos_yCM();
        GLfloat Abstand=sqrt(dx*dx+dy*dy);
        Shot(dx*AusholStaerke/Abstand,dy*AusholStaerke/Abstand);
        StateMachine=SHOT;
        Menu.NewMenuState();
        Camera.EyesOn2(Ball[0].Pos_xCM(),Ball[0].Pos_yCM());
        //Kamera.Verfolge(0);
        DelayCompensation=1;
    }
    if (keyPressed==127) {
        KEY_CTRL=0;
    }

}
Exemple #23
0
void Unit_Dig::FreeMove(void)
{
	VECTOR position;
	position.x = m_x;
	position.y = m_y;

	// ブロックを探す
	BlockManager &blockManager = BlockManager::GetInstance();
	BlockBase* block = blockManager.GetNearHardBlock( position, m_Rang );
	// 硬いブロックがあったら攻撃
	if( block != NULL )
	{
		if( m_AtackCount > 1.0f)
		{
			Shot( block->m_x, block->m_y - blockManager.GetDepth(), false, true, false );
			m_AtackCount -= 1.0f;
		}
		m_AtackCount += m_AttackSpeed;
	}
	// 敵は無視
}
Exemple #24
0
void Robot::handleEvents(SDL_Event event, int SCREEN_PLAYABLE_WIDTH, Piece mainPiece, ShotsOnTheWorld & shotsOnTheWorld,
        Timer & delta_robot, const int ROBOT_SHOOT_DELAY, const int ROBOT_MOVE_DELAY) {

    Uint8 *keystates = SDL_GetKeyState(NULL);

    if (delta_robot.get_ticks() > ROBOT_MOVE_DELAY) {
        if (keystates[ SDLK_LEFT ])
            move(speed * (-1), SCREEN_PLAYABLE_WIDTH, mainPiece);
        if (keystates[ SDLK_RIGHT ])
            move(speed, SCREEN_PLAYABLE_WIDTH, mainPiece);
    }

    if (delta_robot.get_ticks() > ROBOT_SHOOT_DELAY) {
        if (keystates[ SDLK_SPACE ])
            shotsOnTheWorld.newShot(Shot(box.x + ROBOT_GUN_POSITION, box.y, shot_width, shot_height, shot_velx, shot_vely, shot_surface, this));
    }

    if ((delta_robot.get_ticks() > ROBOT_MOVE_DELAY) and (delta_robot.get_ticks() > ROBOT_SHOOT_DELAY))
        delta_robot.start();

}
Exemple #25
0
//----------------------------------------------------------------------
//CCurveMoveクラス(曲線移動をする基底クラス)
//----------------------------------------------------------------------
bool CCurveMove::Move()
{
	// 移動範囲、速度
	static const float
		MaxLX=120, MaxRX=520,
		MaxTY=0, MaxBY=480;

	//体力測定
	if(vitality<=0)
	{
		Game->score->AddScore(m_score);
		new CEnemyCrash(X,Y);
		return false;
	}

	// 移動
	X +=X_SPEED;
	X_SPEED +=X_AXEL;
	Y +=Y_SPEED;
	Y_SPEED +=Y_AXEL;

	// 移動範囲の制限
	if (X<MaxLX) {
		return false;
	}else if (MaxRX<X){
		return false;
	}
	if (Y<MaxTY){
		return false;
	}else if (MaxBY<Y){
		return false;
	}

	Shot();

	return HitorNot();
}
Exemple #26
0
void Unit_Dig::MovePoint(void)
{
	VECTOR position, target, facing;
	position.x = m_x;
	position.y = m_y;
	target.x = m_nextX;
	target.y = m_nextY;
	DXLibMath::FacingTarget( position, target, &m_Facing, 0.1f);
	facing.x = m_nextX - m_x;
	facing.y = m_nextY - m_y;
	DXLibMath::Normalize( &facing, facing );
	BlockManager &blockManager = BlockManager::GetInstance();
	BlockBase* block = blockManager.GetBlock( m_x + facing.x * m_Speed, m_y + facing.y * m_Speed );
	DataManager &data = DataManager::GetInstance();
	// 進行途中に邪魔なブロックがあるなら破壊
	if( block != NULL)
	{
		if( m_AtackCount > 1.0f)
		{
			Shot( block->m_x, block->m_y - blockManager.GetDepth(), false, true, false );
			m_AtackCount -= 1.0f;
		}
		m_AtackCount += m_AttackSpeed;
	}
	else
	{
		m_x += facing.x * m_Speed;
		m_y += facing.y * m_Speed;
	}
	// 目標地点に到達したら自由行動
	// または攻撃を受けても目標地点に向かう
	if( DXLibMath::CircleOnPoint( position, target, 0.1f))
	{
		m_MoveStatus = UnitBase::Free;
	}
}
void ReflectBullet(
	float fx0, float fy0,    // 반사막의 좌상좌표
	float fx1, float fy1,    // 반사막의 우하좌표
	int num_bullet,          // 탄의 갯수
	float x0[], float y0[],  // 탄의 좌상좌표
	float x1[], float y1[],  // 탄의 우하좌표
	float x[], float y[],    // 탄의 중심좌표
	float ex[], float ey[],  // 탄을 쏜 적기의 중심좌표
	float speed              // 샷의 속도
) {
	// 모든 탄에 대하여 처리를 해 줌
	for (int i=0; i<num_bullet; i++) {
	
		// 탄과 반사막의 접촉 판정:
		// 탄이 반사막에 접촉했다면
		// 탄을 제거하고 그 자리에서 적기를 향해 날아가는 샷을 발사함.
		if (fx0<x1[i] && x0[i]<fx1 && 
			fy0<y1[i] && y0[i]<fy1) {

			// 탄의 제거:
			// 구체적인 처리는 DeleteBullet 함수에서 수행하기로 함.
			DeleteBullet(i);
			
			// 샷의 발사:
			// 적기를 향하는 샷을 발사.
			// 구체적인 처리는 Shot 함수에서 수행하기로 함.
			float vx=ex[i]-x[i], vy=ey[i]-y[i];
			if (vx!=0 || vy!=0) {
				float d=sqrt(vx*vx+vy*vy);
				vx*=speed/d;
				vy*=speed/d;
				Shot(x[i], y[i], vx, vy);
			}
		}
	}
}
Exemple #28
0
//Callback Funktion: Reaktion auf Mausclicks
void MouseClick(int button, int state, int x, int y)
{

    if (Menu.MouseClick(button,state,x,y)!=0) {
        MouseButtonIntercepted=1;
        //printf("Abgefangen\n");
    } else {
        MouseButtonIntercepted=0;
        //printf("AbgefangenAus\n");
        MouseLookLast_x=x;
        MouseLookLast_y=y;

        //  Kamera.FahrtAus();

        /*
           if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
           switch (StateMaschin) {
           case START:
           StateMaschin=VIEWING;
           Menu.NeuerMenuZustand();
           break;
           case VIEWING: {
           if (LageVerbesserungKopffeld|LageVerbesserung) {
           StateMaschin=NEW_WHITE;
           Menu.NeuerMenuZustand();
           }
           } break;
           case AIMING:
           StateMaschin=VIEWING;
           Menu.NeuerMenuZustand();
           break;
           case SWING:
           StateMaschin=AIMING;
           Menu.NeuerMenuZustand();
           Anzeige.setzeStossStaerke(0);
           break;
           case SHOT: {
           if (xnor) {
           StateMaschin=VIEWING;
           Menu.NeuerMenuZustand();
           for (int i=1;i<16;i++) {
           if (KugelnImSpiel[i] && !KugelnVersenkt[i] && (Kugel[i].Pos_x()==3000)) {
           KugelnVersenkt[i]=1;
           }
           }
           Menu.NeuerMenuZustand();
           Anzeige.setzeStossStaerke(0);
           }
           } break;
           }
           }
           */

        if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) MouseButton=GLUT_LEFT_BUTTON;
        if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) MouseButton=GLUT_RIGHT_BUTTON;

        if (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) {
            MouseButton=GLUT_LEFT_BUTTON;
            switch (StateMachine) {
            case VIEWING: {
                StateMachine=AIMING;
                Menu.NewMenuState();
                Camera.EyesOn(Ball[0].Pos_xCM(),Ball[0].Pos_yCM());
            } break;
            case AIMING: {
                AusholStartTime=ElapsedTime();
                StateMachine=SWING;
                Menu.NewMenuState();
            } break;
            case SHOT: {
                if (xnor) {
                    for (int Kugelnr=0;Kugelnr<16;Kugelnr++) { // Alle Kugeln ans Ziel
                        Ball[Kugelnr].newPositionD(LightingTable[shot_time][Kugelnr]);
                        if (BallsInGame[Kugelnr] && !BallsSunk[Kugelnr] && (Ball[Kugelnr].Pos_x()==3000)) {
                            BallsSunk[Kugelnr]=1;
                        }
                        Menu.NewMenuState();
                    }
                    if (Ball[0].Pos_x()==3000) {
                        StateMachine=NEW_WHITE;
                        WhiteChosen();
                    } else {
                        StateMachine=VIEWING;
                        Menu.NewMenuState();
                    }
                    ShotStrength.setShotStrength(0);
                }
            } break;
            case NEW_WHITE: {
                StateMachine=VIEWING;
                Menu.NewMenuState();
            } break;
            case JUDGEING: {
                if (LageVerbesserungKopffeld|LageVerbesserung) {
                    WhiteChosen();
                    StateMachine=NEW_WHITE;
                    Menu.NewMenuState();
                } else {
                    StateMachine=VIEWING;
                    Menu.NewMenuState();
                }
            } break;
            }
        }

        if (button == GLUT_MIDDLE_BUTTON && state == GLUT_UP && StateMachine==SWING) {
            GLfloat dx=Ball[0].Pos_xCM()-Camera.Pos_xCM();
            GLfloat dy=Ball[0].Pos_yCM()-Camera.Pos_yCM();
            GLfloat Abstand=sqrt(dx*dx+dy*dy);
            Shot(dx*AusholStaerke/Abstand,dy*AusholStaerke/Abstand);
            StateMachine=SHOT;
            Menu.NewMenuState();
            //Kamera.Verfolge(0);
            Camera.EyesOn2(Ball[0].Pos_xCM(),Ball[0].Pos_yCM());
            //    Kamera.FahrtEin();
            DelayCompensation=1;
        }

    }
}
Exemple #29
0
//Taste
//Callback Funktion: Reaktion auf Tastendruck
void KeyPress( unsigned char keyPressed, int x, int y )
{
    //printf("%c: %i\n",keyPressed,keyPressed);

    if (!Menu.KeyboardButton(keyPressed,x,y)) {
        switch( keyPressed ) {
        case 'h': {
            if (xnor==4) {
                BackgroundColor=1-BackgroundColor;
                glClearColor(BackgroundColor,BackgroundColor,BackgroundColor,0);
            }
        } break;                           //h: Hintergrundfarbe invertieren
        case 'v': {
            if (xnor==4) {
                switch (PolygonMode_view) {      //v: Vorne/Hinten/Beides
                case GL_FRONT:
                    PolygonMode_view=GL_BACK;
                    break;
                case GL_BACK:
                    PolygonMode_view=GL_FRONT_AND_BACK;
                    break;
                case GL_FRONT_AND_BACK:
                    PolygonMode_view=GL_FRONT;
                    break;
                }
                glPolygonMode(PolygonMode_view,PolygonMode_mode);
            }
        } break;
        case 'w': {
            if (xnor==4) {
                switch (PolygonMode_mode) {     //w: Punkte/Linien/Fl"achen
                case GL_FILL: PolygonMode_mode=GL_POINT;break;
                case GL_POINT: PolygonMode_mode=GL_LINE;break;
                case GL_LINE: PolygonMode_mode=GL_FILL;break;
                }
                glPolygonMode(PolygonMode_view,PolygonMode_mode);
            }
        } break;

        case '1': Camera.savePosition(0);break; //1
        case '2': Camera.savePosition(1);break; //2
        case '3': Camera.savePosition(2);break; //3
        case '4': Camera.savePosition(3);break; //4
        case '5': Camera.savePosition(4);break; //5
        case '6': Camera.savePosition(5);break; //6
        case '7': Camera.savePosition(6);break; //7
        case '8': Camera.savePosition(7);break; //8

        case '\b': {
            switch (StateMachine) {
            case START:
                StateMachine=VIEWING;
                Menu.NewMenuState();
                break;
            case VIEWING: {
                if (LageVerbesserungKopffeld|LageVerbesserung) {
                    StateMachine=NEW_WHITE;
                    Menu.NewMenuState();
                }
            } break;
            case AIMING:
                StateMachine=VIEWING;
                Menu.NewMenuState();
                break;
            case SWING:
                StateMachine=AIMING;
                Menu.NewMenuState();
                ShotStrength.setShotStrength(0);
                break;
            case SHOT: {
                if (xnor) {
                    StateMachine=VIEWING;
                    Menu.NewMenuState();
                    for (int i=1;i<16;i++) {
                        if (BallsInGame[i] && !BallsSunk[i] && (Ball[i].Pos_x()==3000)) {
                            BallsSunk[i]=1;
                        }
                    }
                    Menu.NewMenuState();
                    ShotStrength.setShotStrength(0);
                }
            } break;
            }
        } break;

        case 'r': {
            if (xnor==3) {
                xnor=4;
            } else if (!AllerersterStoss) {
                StartTime=ElapsedTime();
                //Frames=0;
                StateMachine=SHOT;
                Menu.NewMenuState();
                for (int Kugelnr=0;Kugelnr<16;Kugelnr++) {
                    Ball[Kugelnr].newPositionD(LightingTable[0][Kugelnr]);
                }
                glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
            }
        } break;           //r


        case 'c': {
            if (xnor==4) {
                glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
            }
        } break; //c

        case 27 : {
            Menu.setMenuState(OFF_GAME);
        } break;

        case 'q': {
            if (xnor==4) {
                StateMachine=START;
                Menu.setMenuState(HOME_SCREEN);
            }
        } break;

        case 'f': {
            /*
                             (FullScreen=1-FullScreen);
                             if (FullScreen) {
                             glutFullScreen();
                             } else {
                             glutReshapeWindow(800, 600);
                             }
                             */
        } break;
            /*
                      //      if (xnor==4) {
                      (FullScreen=1-FullScreen);
                      if (FullScreen) {
                      glutFullScreen();
                      //glutGameModeString("640x480:16@60");
                      //glutEnterGameMode();
                      //AktuellesFenster=glutGetWindow();
                      //glutIgnoreKeyRepeat(1);
                      //glutMouseFunc(Maus);
                      //glutMotionFunc(Bewegung);
                      //glutKeyboardFunc(Taste);
                      //glutKeyboardUpFunc(TasteLos);
                      //glutSpecialFunc(Sondertaste);
                      //glutSpecialUpFunc(SondertasteLos);
                      //glutIdleFunc(timerEvent);
                      //glutDisplayFunc(updateGL);
                      //glutVisibilityFunc(Sichtbar);
                      //      CreateMenu();
                      } else {
                      glutReshapeWindow(800, 600);
                      if (OriginalFenster != 0 && AktuellesFenster != OriginalFenster) {
                      glutLeaveGameMode();
                      AktuellesFenster=OriginalFenster;
                      }
                      }
                      }
                      } break;
                      */
        case 127: {
            KEY_CTRL=1;
        } break;
        case 'x': {
            if (xnor==0) {
                xnor=1;
            }
        } break;
        case 'o': {
            if (xnor==2) {
                xnor=3;
            }
        } break;
        case 'z': {
            if (xnor==4) {
                GameType=GT_RANDOM;
                BoardLayout();
            }
        } break;//z
        case 'a': {
            if (xnor==4) {
                GameType=EIGHT_BALL;
                BoardLayout();
                Judge.NewGame(GameType);
            }
        } break;//a
        case 'n': {
            if (xnor==1) {
                xnor=2;
            }
            if (xnor==4) {
                GameType=NINE_BALL;
                BoardLayout();
                Judge.NewGame(GameType);
            }
        } break;//n
        case '9': {
            if (xnor==4) {
                GameType=NINE_BALL;
                BoardLayout();
                Judge.NewGame(GameType);
            }
        } break;//9
        case 's': {
            if (xnor==4) {
                GameType=TWO_BALLS;
                BoardLayout();
            }
        } break;//s
        case 'l': {
            if (xnor==4) {
                GameType=GT_EMPTY;
                BoardLayout();
            }
        } break;//l
        case 'd': {
            if (xnor==4) {
                GLfloat dx=Ball[0].Pos_xCM()-Camera.Pos_xCM();
                GLfloat dy=Ball[0].Pos_yCM()-Camera.Pos_yCM();
                GLfloat Abstand=sqrt(dx*dx+dy*dy);
                Shot(dx*80.0/Abstand,dy*80.0/Abstand);
            }
        } break;//d
        case 'e': {
            if (xnor==4) {
                GLfloat dx=Ball[0].Pos_xCM()-Camera.Pos_xCM();
                GLfloat dy=Ball[0].Pos_yCM()-Camera.Pos_yCM();
                GLfloat Abstand=sqrt(dx*dx+dy*dy);
                Shot(dx*80.0/Abstand,dy*80.0/Abstand);
                StateMachine=SHOT;
                Menu.NewMenuState();
                Camera.EyesOn2(Ball[0].Pos_xCM(),Ball[0].Pos_yCM());
                //Kamera.Verfolge(0);
                DelayCompensation=1;
            }
        } break;//e
        case ' ': {
            switch (StateMachine) {
            case VIEWING:
                StateMachine=AIMING;
                Menu.NewMenuState();
                Camera.EyesOn(Ball[0].Pos_xCM(),Ball[0].Pos_yCM());
                break;
            case AIMING:
                AusholStartTime=ElapsedTime();
                StateMachine=SWING;
                Menu.NewMenuState();
                break;
            case SHOT: {
                if (xnor) {
                    for (int Kugelnr=0;Kugelnr<16;Kugelnr++) { // Alle Kugeln ans Ziel
                        Ball[Kugelnr].newPositionD(LightingTable[shot_time][Kugelnr]);
                    }
                    if (Ball[0].Pos_x()==3000) {
                        StateMachine=NEW_WHITE;
                        WhiteChosen();
                        Menu.NewMenuState();
                    } else {
                        StateMachine=VIEWING;
                        Menu.NewMenuState();
                    }
                }
            } break;
            case NEW_WHITE: {
                StateMachine=VIEWING;
                Menu.NewMenuState();
            } break;
            case JUDGEING: {
                if (LageVerbesserungKopffeld|LageVerbesserung) {
                    WhiteChosen();
                    StateMachine=NEW_WHITE;
                    Menu.NewMenuState();
                } else {
                    StateMachine=VIEWING;
                    Menu.NewMenuState();
                }
            } break;
            }
        }
        }
    }
}
Exemple #30
0
int main() {
	typedef std::deque<Invader> InvaderList;
	typedef std::deque<Shot> ShotList;

	cv::VideoCapture cap( DEFAULT_DEVICE );
	if(!cap.isOpened()) {
		std::cerr << "Error opening VideoCapture!" << std::endl;
		return -1;
	}
	
	cap.set(CV_CAP_PROP_FRAME_WIDTH, 1024);
	cap.set(CV_CAP_PROP_FRAME_HEIGHT, 768);
	
	cv::namedWindow("SpaceInvaders", CV_WINDOW_AUTOSIZE);
	
	cv::Mat cameraImage;
	cap >> cameraImage;
	
	const cv::Size CameraImageSize( cameraImage.size() );
	
	for (int key = -1; ' ' != key; key = cv::waitKey(WAIT_DELAY_MS)) {
		cap >> cameraImage;
		cv::flip(cameraImage, cameraImage, FLIPPING_AROUND_Y_AXIS);
		cv::putText(cameraImage, "Press space to play!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 2, cv::Scalar::all(255), 2, 8);
		cv::resize(cameraImage, cameraImage, CameraImageSize * 2);
		cv::imshow("SpaceInvaders", cameraImage);
	}
	
	const GameImage playerImage( PLAYER_PNG );
	const GameImage invaderImage( INVADER_PNG );
	
	const int YPlayerShot = CameraImageSize.height - playerImage.size().height;
	const int YGameOver = YPlayerShot - invaderImage.size().height;
	
	Player player(playerImage, CameraImageSize, SHOT_LINE_PIX);
	PlayerPosition playerPosition(player, HAARCASCADE_XML, CameraImageSize);
	Shot playerShot;
	bool gameOver = false;
	
	InvaderList invaders;
	std::generate_n(std::back_inserter(invaders), MAX_INVADERS, Invader::Factory(invaderImage, CameraImageSize, 5));
	
	ShotList shots;
	
	cv::RNG rng(uint64(std::time(0)));
	
	for (int key = -1; 'q' != key; key = cv::waitKey(WAIT_DELAY_MS)) {
		cap >> cameraImage;
		cv::flip(cameraImage, cameraImage, FLIPPING_AROUND_Y_AXIS);

		if (!gameOver) {
		
		playerPosition.update(cameraImage);
		playerShot.update();
		std::for_each(invaders.begin(), invaders.end(), GraphicUpdate);
		std::for_each(shots.begin(), shots.end(), GraphicUpdate);
		
		if (playerShot.isValid()) {
			const InvaderList::iterator iInvaderEnd = std::remove_if(invaders.begin(),invaders.end(), GraphicColision(playerShot.rect()));
			if (iInvaderEnd != invaders.end()) {
				invaders.erase(iInvaderEnd, invaders.end());
				playerShot = Shot();
			}
		}
		
		if (!shots.empty()) {
			const ShotList::iterator iShotsEnd = std::remove_if(shots.begin(), shots.end(), isInvalidShot);
			if (iShotsEnd != shots.end()) {
				shots.erase(iShotsEnd, shots.end());
			}
		}
		
		for (InvaderList::const_iterator iInvader = invaders.begin(); iInvader != invaders.end() && !gameOver; ++iInvader) {
			const cv::Rect irect( iInvader->rect() );
			if ((rng.uniform(0.0,1.0) < 0.05) && (shots.size() < MAX_INVADERS)) {
				cv::Point shotPos(irect.x + (irect.width / 2), irect.y + irect.height);
				shots.push_back( Shot(shotPos, SHOT_SPEED, cv::Scalar(100,50,100), CameraImageSize) );
			}
			if (irect.y >= YGameOver) {
				gameOver = true;
			}
		}
		
		if (!playerShot.isValid() && player.isShooting()) {
			cv::Point shotPoint( player.facePosition().x, YPlayerShot );
			playerShot = Shot(shotPoint, -SHOT_SPEED, cv::Scalar(100,170,10), CameraImageSize);
		}
		
		for (ShotList::iterator iShot(shots.begin()); iShot != shots.end() && !gameOver; ++iShot) {
			if (iShot->isValid() && checkColision(iShot->rect(),player.rect())) {
				gameOver = true;
			}
		}
		
		}
		
		std::for_each(invaders.begin(), invaders.end(), GraphicPaint(cameraImage));
		std::for_each(shots.begin(), shots.end(), GraphicPaint(cameraImage));
		player.paint(cameraImage);
		playerShot.paint(cameraImage);
		
		if (invaders.empty()) {
			cv::putText(cameraImage, "Winner!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar::all(255), 2, 8);
		} else if (gameOver) {
			cv::putText(cameraImage, "Game Over!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar::all(255), 2, 8);
		}
		
		cv::resize(cameraImage, cameraImage, CameraImageSize * 2);
		cv::imshow("SpaceInvaders", cameraImage);
	}
	
	return 0;
}