void CompositeStochasticTask::random_child(Agent* pAgent)
{
    BEHAVIAC_ASSERT(!this->GetNode() || CompositeStochastic::DynamicCast(this->GetNode()));
    const CompositeStochastic* pNode = (const CompositeStochastic*)(this->GetNode());

    if (this->m_set.size() != this->m_children.size())
    {
        this->m_set.resize(this->m_children.size());
    }

    uint32_t n = this->m_set.size();

    for (uint32_t i = 0; i < n; ++i)
    {
        this->m_set[i] = i;
    }

    for (uint32_t i = 0; i < n; ++i)
    {
        uint32_t index1 = (uint32_t)(n * GetRandomValue(pNode ? pNode->m_method : 0, pAgent));
        BEHAVIAC_ASSERT(index1 < n);

        uint32_t index2 = (uint32_t)(n * GetRandomValue(pNode ? pNode->m_method : 0, pAgent));
        BEHAVIAC_ASSERT(index2 < n);

        //swap
        if (index1 != index2)
        {
            uint32_t old = this->m_set[index1];
            this->m_set[index1] = this->m_set[index2];
            this->m_set[index2] = old;
        }
    }
}
Beispiel #2
0
static void UpdateIncomingFire()
{
    static int missileIndex = 0;

    // Launch missile
    if (framesCounter % MISSILE_LAUNCH_FRAMES == 0)
    {
        float module;
        float sideX;
        float sideY;

        // Activate the missile
        missile[missileIndex].active = true;

        // Assign start position
        missile[missileIndex].origin = (Vector2){ GetRandomValue(20, screenWidth - 20), -10 };
        missile[missileIndex].position = missile[missileIndex].origin;
        missile[missileIndex].objective = (Vector2){ GetRandomValue(20, screenWidth - 20), screenHeight + 10 };

        // Calculate speed
        module = sqrt( pow(missile[missileIndex].objective.x - missile[missileIndex].origin.x, 2) +
                       pow(missile[missileIndex].objective.y - missile[missileIndex].origin.y, 2));

        sideX = (missile[missileIndex].objective.x - missile[missileIndex].origin.x)*MISSILE_SPEED/module;
        sideY = (missile[missileIndex].objective.y - missile[missileIndex].origin.y)*MISSILE_SPEED/module;

        missile[missileIndex].speed = (Vector2){ sideX, sideY };

        // Update
        missileIndex++;
        if (missileIndex == MAX_MISSILES) missileIndex = 0;
    }
}
Beispiel #3
0
//------------------------------------------------------------------------------
CRenderAudio::CRenderAudio(const CRegionAI& AudioInfo,const SString& AudioName,ILogicHandler* pHandler) 
: CRenderNode(pHandler),m_uUnitSetIndex(0)
{
	m_pAEmitter = GetAudioModule()->CreateAudioEmitter();
	m_pAEmitter->SetAutoStop(true);

	m_uUnitSetIndex		= AudioInfo.SetIndex;
	SetPosition(AudioInfo.cX,AudioInfo.cY,AudioInfo.cZ);
	m_bPlayNotRepeat	= AudioInfo.bPlayNotRepeat;
	m_uPlayTimeLenMin	= AudioInfo.uPlayTimeLenMin;
	m_uPlayTimeLenMax	= AudioInfo.uPlayTimeLenMax;
	m_uPlayIntervalMin	= AudioInfo.uPlayIntervalMin;
	m_uPlayIntervalMax	= AudioInfo.uPlayIntervalMax;

	m_uCurRandomPlayTime = GetRandomValue(m_uPlayTimeLenMin,  m_uPlayTimeLenMax);
	m_uCurRandomInterval = GetRandomValue(m_uPlayIntervalMin, m_uPlayIntervalMax);

	m_strAudioName	= AudioName;

	CVector3f mMin = CVector3f(-30.0f, 0.0f,  -30.0f);
	CVector3f mMax = CVector3f( 30.0f, 60.0f,  30.0f);
	float fRange = eGridSpan * AudioRange;

	mMin = mMin  - CVector3f(fRange, fRange, fRange);
	mMax = mMax  + CVector3f(fRange, fRange, fRange);

	m_OrgAABB.setExtents(mMin, mMax);
	UpdateBox();

	m_pAEmitter->SetPosition(GetPosition());
	m_bNeedPlayBegin     = true;
	m_bNeedIntervalBegin = true;
	m_bPlayError		 = false;
}
Beispiel #4
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values");

    int framesCounter = 0;  // Variable used to count frames

    int randValue = GetRandomValue(-8,5);   // Get a random integer number between -8 and 5 (both included)

    SetTargetFPS(60);       // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        framesCounter++;

        // Every two seconds (120 frames) a new random value is generated
        if (((framesCounter/120)%2) == 1)
        {
            randValue = GetRandomValue(-8,5);
            framesCounter = 0;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            DrawText("Every 2 seconds a new random value is generated:", 130, 100, 20, MAROON);

            DrawText(FormatText("%i", randValue), 360, 180, 80, LIGHTGRAY);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
static void inline PlasmaPixel(Image *image,double x,double y)
{
    register PixelPacket
    *q;

    q=GetImagePixels(image,(long) ceil(x-0.5),(long) ceil(y-0.5),1,1);
    if (q == (PixelPacket *) NULL)
        return;
    q->red=ScaleAnyToQuantum(GetRandomValue(),1.0);
    q->green=ScaleAnyToQuantum(GetRandomValue(),1.0);
    q->blue=ScaleAnyToQuantum(GetRandomValue(),1.0);
    (void) SyncImagePixels(image);
}
Beispiel #6
0
void InitialiseScene(void)
{
	//Code for the rigid bodies is now nice and tidy, but look at cleaning up Sweep and Prune / Better visualising it!
	prevFrameTimeSinceStart = glutGet(GLUT_ELAPSED_TIME);
	
	bodyShader = new Shader("vTexture.shader", "fTexture.shader");
	lineShader = new Shader("vLine.shader", "fLine.shader");
	simpleCamera = new SimpleCamera();

	sceneBodies.push_back(new BasicCube());
	for(int i = 1; i < rigidBodyCount; i++)
		sceneBodies.push_back(new BasicCube(glm::vec3(GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f)),
											glm::vec3(GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f)),
											glm::vec3(GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f), GetRandomValue(-1.0f, 1.0f))));

	curSelectedCube = sceneBodies[0];

	for(int i = 0; i < sceneBodies.size(); i++)
		AddToSweepPrune(sceneBodies[i]->GetBoundingBox());

	activeColliders.resize(sceneBodies.size());

	collisionTable = vector<vector<int>>();
	collisionTable.resize(sceneBodies.size());
	for(int i = 0; i < sceneBodies.size(); i++)
	{
		collisionTable[i].resize(sceneBodies.size());
		for(int j = 0; j < sceneBodies.size(); j++)
		{
			collisionTable[i][j] = 0;
		}
	}

	SortSweepPrune();
}
Beispiel #7
0
// Initialize game variables
void InitGame(void)
{
    // Initialize game variables
    shootRate = 0;
    pause = false;
    gameOver = false;
    victory = false;
    smooth = false;
    wave = FIRST;
    activeEnemies = FIRST_WAVE;
    enemiesKill = 0;
    score = 0;
    alpha = 0;

    // Initialize player
    player.rec.x =  20;
    player.rec.y = 50;
    player.rec.width = 20;
    player.rec.height = 20;
    player.speed.x = 5;
    player.speed.y = 5;
    player.color = BLACK;

    // Initialize enemies
    for (int i = 0; i < NUM_MAX_ENEMIES; i++)
    {
        enemy[i].rec.width = 10;
        enemy[i].rec.height = 10;
        enemy[i].rec.x = GetRandomValue(screenWidth, screenWidth + 1000);
        enemy[i].rec.y = GetRandomValue(0, screenHeight - enemy[i].rec.height);
        enemy[i].speed.x = 5;
        enemy[i].speed.y = 5;
        enemy[i].active = true;
        enemy[i].color = GRAY;
    }

    // Initialize shoots
    for (int i = 0; i < NUM_SHOOTS; i++)
    {
        shoot[i].rec.x = player.rec.x;
        shoot[i].rec.y = player.rec.y + player.rec.height/4;
        shoot[i].rec.width = 10;
        shoot[i].rec.height = 5;
        shoot[i].speed.x = 7;
        shoot[i].speed.y = 0;
        shoot[i].active = false;
        shoot[i].color = MAROON;
    }
}
Beispiel #8
0
// Level06 Screen Initialization logic
void InitLevel06Screen(void)
{
    // Initialize Level06 screen variables here!
    framesCounter = 0;
    finishScreen = 0;
    
    centerRec = (Rectangle){ GetScreenWidth()/2 - 100, 0, 200, GetScreenHeight() };
    
    for (int i = 0; i < 4; i++)
    {
        movingRecs[i] = (Rectangle){ GetRandomValue(0, 5)*150, (i*150) + 90, 100, 100 };
        stoppedRec[i] = false;
        speedRecs[i] = GetRandomValue(4, 8);
    }
}
Beispiel #9
0
void FluidSim::InitialiseParticles(void)
{
	KernelPow9 = glm::pow(SmoothingKernelSize, 9.0f);
	KernelPow6 = glm::pow(SmoothingKernelSize, 6.0f);
	KernelPow2 = glm::pow(SmoothingKernelSize, 2.0f);

	float pi = glm::pi<float>();

	DefaultKernelConstant = 315.0f / (64.0f * pi * KernelPow9);
	NormalKernelConstant = -945.0f / (32.0f * pi * KernelPow9);
	SurfaceKernelConstant = NormalKernelConstant;
	PressureKernelConstant = -45.0f  / (pi * KernelPow6);
	ViscosityKernelConstant = 45.0f / (pi * KernelPow6);

	particles.reserve(ParticleCount);

	for(int x = 0; x < ParticlesPerDimension; x++)
		for(int y = 0; y < ParticlesPerDimension; y++)
			for(int z = 0; z < ParticlesPerDimension; z++)
			{
				Particle* particle = new Particle(ParticleMass);
				particle->SetPosition(GetRandomValue(-HorizontalBounds, HorizontalBounds), GetRandomValue(0.0f, HorizontalBounds), GetRandomValue(-HorizontalBounds, HorizontalBounds));
				//particle->SetPosition(0.0f, 0.0f, 0.0f);
				particle->SetVelocity(0.0f, 0.0f, 0.0f);
				particles.push_back(particle);
			}

	container = Capsule();
	container.radius = HorizontalBounds;
	container.length = HorizontalBounds;
	container.centre = glm::vec3();

	innerContainer = Capsule();

	innerRadius = HorizontalBounds / 2.0f;
	innerLength = HorizontalBounds / 2.0f;

	innerContainer.radius = innerRadius;
	innerContainer.length = innerLength;
	innerContainer.centre = glm::vec3();

	container.CalculateCapsulePosition(glm::vec3());
	innerContainer.CalculateCapsulePosition(glm::vec3());

	crashCapsule = brokenCapsule = showNeighbours = showSurfaceParticles = hideSurfaceParticles = false;
	particleHighlightID = 0;
	wallEnabled = true;
}
static inline void PlasmaPixel(Image *image,double x,double y)
{
  register PixelPacket
    *q;

  q=GetImagePixels(image,(long) ceil(x-0.5),(long) ceil(y-0.5),1,1);
  if (q == (PixelPacket *) NULL)
    return;
  q->red=ScaleAnyToQuantum((unsigned long)
    (65535.0*GetRandomValue()+0.5),16UL);
  q->green=ScaleAnyToQuantum((unsigned long)
    (65535.0*GetRandomValue()+0.5),16UL);
  q->blue=ScaleAnyToQuantum((unsigned long)
    (65535.0*GetRandomValue()+0.5),16UL);
  (void) SyncImagePixels(image);
}
Beispiel #11
0
int main() {
    srand(static_cast<unsigned>(time(NULL)));
    double variables[MaxVarCount];
    for (int i = 0; i < MaxVarCount; i++) {
        variables[i] = GetRandomValue(MaxVarValue);
    }
    std::map<std::string, double> expressions;
    std::ofstream output;
    output.open("../ADTest/TestFunctions.h");
    std::vector<std::string> lines;
    lines.push_back("#ifndef TESTFUNCTIONS_H");
    lines.push_back("#define TESTFUNCTIONS_H");
    lines.push_back("");
    lines.push_back("const int DataInSize = " + IntToStr(MaxVarCount) + ";");
    lines.push_back("const int SimpleTestCases = " + IntToStr(SimpleTestCases) + ";");
    lines.push_back("const int ComplexTestCases = " + IntToStr(ComplexTestCases) + ";");
    lines.push_back("const int LoopTestCases = " + IntToStr(LoopTestCases) + ";");
    lines.push_back("const int TotalTestCases = " + IntToStr(TotalTestCases) + ";");
    lines.push_back("const int LoopIterations = " + IntToStr(LoopIterations) + ";");
    lines.push_back("");
    std::string arguments = "";
    for (int i = 0; i < MaxVarCount; i++) {
        arguments += DoubleToStr(variables[i]) + ", ";
    }
    arguments = arguments.substr(0, arguments.size() - 2);
    lines.push_back("const real realArgs[DataInSize] = {" + arguments + "};");
    lines.push_back("");
    lines.push_back("template<typename ADType>");
    lines.push_back("struct FunctionBase {");
    lines.push_back("    virtual ADType TestFunction(const ADType(&x)[DataInSize]) = 0;");
    lines.push_back("};");
    lines.push_back("");

    GenerateSimpleTestCases(0, lines, expressions, variables);
    GenerateComplexTestCases(SimpleTestCases, lines, expressions, variables);
    GenerateLoopTestCases(SimpleTestCases + ComplexTestCases, lines, expressions, variables);

    lines.push_back("template<typename ADType>");
    lines.push_back("void Initialize(FunctionBase<ADType>* testArray[TotalTestCases]) {");
    for (int i = 0; i < TotalTestCases; i++) {
        lines.push_back("    testArray[" + IntToStr(i) + "] = new FunctionSpec" + IntToStr(i) + "<ADType>();");
    }
    lines.push_back("};");
    lines.push_back("");
    lines.push_back("template<typename ADType>");
    lines.push_back("void Finalize(FunctionBase<ADType>* testArray[TotalTestCases]) {");
    lines.push_back("    for (int i = 0; i < TotalTestCases; i++)");
    lines.push_back("        delete testArray[i]; ");
    lines.push_back("};");
    lines.push_back("");
    lines.push_back("#endif  // TESTFUNCTIONS_H");

    for (std::vector<std::string>::iterator line = lines.begin(); line != lines.end(); line++) {
        output << *line << '\n';
    }
    output.close();
    return 0;
};
Beispiel #12
0
void AddConstants(std::map<std::string, double>& expressions) {
    for (int i = 0; i < MaxConstCount; i++) {
        double constant = GetRandomValue(MaxConstValue);
        std::string key = DoubleToStr(constant);
        if (constant < 0.0) {
            key = "(" + key + ")";
        }
        expressions[key] = constant;
    }
};
    EBTStatus SelectorProbabilityTask::update(Agent* pAgent, EBTStatus childStatus)
    {
		BEHAVIAC_ASSERT(SelectorProbability::DynamicCast(this->GetNode()));
        const SelectorProbability* pSelectorProbabilityNode = (const SelectorProbability*)(this->GetNode());

		if (childStatus != BT_RUNNING)
		{
			return childStatus;
		}

        //check if we've already chosen a node to run
        if (this->m_activeChildIndex != CompositeTask::InvalidChildIndex)
        {
			BehaviorTask* pNode = this->m_children[this->m_activeChildIndex];

			EBTStatus status = pNode->exec(pAgent);

            return status;
        }

		BEHAVIAC_ASSERT(this->m_weightingMap.size() == this->m_children.size());

		//generate a number between 0 and the sum of the weights
		double chosen = this->m_totalSum * GetRandomValue(pSelectorProbabilityNode->m_method, pAgent);

		double sum = 0;

        for (uint32_t i = 0; i < this->m_children.size() ; ++i)
        {
			int w = this->m_weightingMap[i];

            sum += w;

            if (w > 0 && sum >= chosen) //execute this node
            {
				BehaviorTask* pChild = this->m_children[i];

                EBTStatus status = pChild->exec(pAgent);

				if (status == BT_RUNNING)
				{
					this->m_activeChildIndex = i;
				}
				else
				{
					this->m_activeChildIndex = CompositeTask::InvalidChildIndex;
				}

                return status;
            }
        }

		return BT_FAILURE;
    }
Beispiel #14
0
// FAST LOOP: 50 Hz-ish
void RAMBLERBot::loop50Hz()
{  
  // Check if the speed should accelerate or decelerate
  if (speedLimit(&motor_left_, motor_left_goal_))
  {
    motors_.setLeftSpeed(motor_left_);
  }
  
  // Check if the speed should accelerate or decelerate
  if (speedLimit(&motor_right_, motor_right_goal_))
  {
    motors_.setRightSpeed(motor_right_);
  }
  
  // Reset 50 Hz Count if necessary
  if (++count50Hz_ >= 5)
  {
    count50Hz_ = 0;
  }
  
  // Perform Operations on the 50 Hz time
  if (count50Hz_ == 1)
  {
    rand1_ = GetRandomValue();
  }
  if (count50Hz_ == 2)
  {
    rand2_ = GetRandomValue();
  }
  if (count50Hz_ == 3)
  {
    rand3_ = GetRandomValue();
  }
  if (count50Hz_ == 4)
  {
    whiskers_.GetWhiskerValues(&ant_right_, &ant_left_);
  }
}
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [textures] example - particles blending");

    // Particles pool, reuse them!
    Particle mouseTail[MAX_PARTICLES] = { 0 };

    // Initialize particles
    for (int i = 0; i < MAX_PARTICLES; i++)
    {
        mouseTail[i].position = (Vector2){ 0, 0 };
        mouseTail[i].color = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
        mouseTail[i].alpha = 1.0f;
        mouseTail[i].size = (float)GetRandomValue(1, 30)/20.0f;
        mouseTail[i].rotation = (float)GetRandomValue(0, 360);
        mouseTail[i].active = false;
    }

    float gravity = 3.0f;

    Texture2D smoke = LoadTexture("resources/smoke.png");

    int blending = BLEND_ALPHA;

    SetTargetFPS(60);
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------

        // Activate one particle every frame and Update active particles
        // NOTE: Particles initial position should be mouse position when activated
        // NOTE: Particles fall down with gravity and rotation... and disappear after 2 seconds (alpha = 0)
        // NOTE: When a particle disappears, active = false and it can be reused.
        for (int i = 0; i < MAX_PARTICLES; i++)
        {
            if (!mouseTail[i].active)
            {
                mouseTail[i].active = true;
                mouseTail[i].alpha = 1.0f;
                mouseTail[i].position = GetMousePosition();
                i = MAX_PARTICLES;
            }
        }

        for (int i = 0; i < MAX_PARTICLES; i++)
        {
            if (mouseTail[i].active)
            {
                mouseTail[i].position.y += gravity;
                mouseTail[i].alpha -= 0.01f;

                if (mouseTail[i].alpha <= 0.0f) mouseTail[i].active = false;

                mouseTail[i].rotation += 5.0f;
            }
        }

        if (IsKeyPressed(KEY_SPACE))
        {
            if (blending == BLEND_ALPHA) blending = BLEND_ADDITIVE;
            else blending = BLEND_ALPHA;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(DARKGRAY);

            BeginBlendMode(blending);

                // Draw active particles
                for (int i = 0; i < MAX_PARTICLES; i++)
                {
                    if (mouseTail[i].active) DrawTexturePro(smoke, (Rectangle){ 0.0f, 0.0f, (float)smoke.width, (float)smoke.height },
                                                           (Rectangle){ mouseTail[i].position.x, mouseTail[i].position.y, smoke.width*mouseTail[i].size, smoke.height*mouseTail[i].size },
                                                           (Vector2){ (float)(smoke.width*mouseTail[i].size/2.0f), (float)(smoke.height*mouseTail[i].size/2.0f) }, mouseTail[i].rotation,
                                                           Fade(mouseTail[i].color, mouseTail[i].alpha));
                }

            EndBlendMode();

            DrawText("PRESS SPACE to CHANGE BLENDING MODE", 180, 20, 20, BLACK);

            if (blending == BLEND_ALPHA) DrawText("ALPHA BLENDING", 290, screenHeight - 40, 20, BLACK);
            else DrawText("ADDITIVE BLENDING", 280, screenHeight - 40, 20, RAYWHITE);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadTexture(smoke);

    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #16
0
// Ending Screen Initialization logic
void InitEndingScreen(void)
{
    framesCounter = -10;
    finishScreen = 0;
    drawTimer = 15;
    replayTimer = 0;
    replaying = false;
    finalYears = initYears + (seasons/4);
    yearsElapsed = seasons/4;
    
    playButton = (Rectangle){ GetScreenWidth()*0.871, GetScreenHeight()*0.096, 123, 123};
    shopButton = (Rectangle){ GetScreenWidth()*0.871, GetScreenHeight()*0.303, 123, 123};
    trophyButton = (Rectangle){ GetScreenWidth()*0.871, GetScreenHeight()*0.513, 123, 123};
    shareButton = (Rectangle){ GetScreenWidth()*0.871, GetScreenHeight()*0.719, 123, 123};
    
    buttonPlayColor = WHITE;
    buttonShopColor = WHITE;
    buttonTrophyColor = WHITE;
    buttonShareColor = WHITE;
    
    currentScore = 0;
    seasonsCounter = 0;
    currentLeavesEnding = 0;
    
    endingCounter = DELAY;
    
    backgroundColor = (Color){ 176, 167, 151, 255};
    
    for (int j = 0; j < 20; j++)
    {
        leafParticles[j].active = false;
        leafParticles[j].position = (Vector2){ GetRandomValue(-20, 20), GetRandomValue(-20, 20) };
        leafParticles[j].speed = (Vector2){ (float)GetRandomValue(-500, 500)/100, (float)GetRandomValue(-500, 500)/100 };
        leafParticles[j].size = (float)GetRandomValue(3, 10)/5;
        leafParticles[j].rotation = GetRandomValue(0, 360);
        leafParticles[j].color = WHITE;
        leafParticles[j].alpha = 1;
    }
    
    // Seasons death texts
    if (initSeason == 0)
    {
        sprintf(initMonthText, "SUMMER");
        clockRotation = 225;
        initRotation = 225;
    }
    else if (initSeason == 1)
    {
        sprintf(initMonthText, "AUTUMN");
        clockRotation = 135;
        initRotation = 135;
    }
    else if (initSeason == 2)
    {
        sprintf(initMonthText, "WINTER");
        clockRotation = 45;
        initRotation = 45;  
    }
    else if (initSeason == 3)
    {
        sprintf(initMonthText, "SPRING");
        clockRotation = 315;
        initRotation = 315; 
    }
    
    if (currentSeason == 0)
    {
        sprintf(finalMonthText, "SUMMER");
        finalRotation = 225 + 360*yearsElapsed;
    }
    else if (currentSeason == 1)
    {    
        sprintf(finalMonthText, "AUTUMN");
        finalRotation = 135 + 360*yearsElapsed;
    }
    else if (currentSeason == 2)
    {
        sprintf(finalMonthText, "WINTER");
        finalRotation = 45 + 360*yearsElapsed;
    }
    else if (currentSeason == 3)
    {
        sprintf(finalMonthText, "SPRING");
        finalRotation = 315 + 360*yearsElapsed;
    }

    for (int i = 0; i < MAX_KILLS; i++) active[i] = false;
}
Beispiel #17
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 1280;
    const int screenHeight = 720;
    
    // Init window
    ShowLogo();
    InitWindow(screenWidth, screenHeight, "Dr. Turtle & Mr. GAMERA");
    
    // Initialize audio device
    InitAudioDevice();      
    
    // Load game resources: textures
    Texture2D sky = LoadTexture("resources/sky.png");
    Texture2D mountains = LoadTexture("resources/mountains.png");
    Texture2D sea = LoadTexture("resources/sea.png");
    Texture2D title = LoadTexture("resources/title.png");
    Texture2D turtle = LoadTexture("resources/turtle.png");
    Texture2D gamera = LoadTexture("resources/gamera.png");
    Texture2D shark = LoadTexture("resources/shark.png");
    Texture2D orca = LoadTexture("resources/orca.png");
    Texture2D swhale = LoadTexture("resources/swhale.png");
    Texture2D fish = LoadTexture("resources/fish.png");
    Texture2D gframe = LoadTexture("resources/gframe.png");
    
    // Load game resources: fonts
    SpriteFont font = LoadSpriteFont("resources/komika.png");
    
    // Load game resources: sounds
    Sound eat = LoadSound("resources/eat.wav");
    Sound die = LoadSound("resources/die.wav");
    Sound growl = LoadSound("resources/gamera.wav");
    
    // Start playing streaming music
    PlayMusicStream("resources/speeding.ogg");

    // Define scrolling variables
    int backScrolling = 0;
    int seaScrolling = 0;
    
    // Define current screen
    GameScreen currentScreen = TITLE;
    
    // Define player variables
    int playerRail = 1;
    Rectangle playerBounds = { 30 + 14, playerRail*120 + 90 + 14, 100, 100 };
    bool gameraMode = false;
    
    // Define enemies variables
    Rectangle enemyBounds[MAX_ENEMIES];
    int enemyRail[MAX_ENEMIES];
    int enemyType[MAX_ENEMIES];
    bool enemyActive[MAX_ENEMIES];
    float enemySpeed = 10;
    
    // Init enemies variables
    for (int i = 0; i < MAX_ENEMIES; i++)
    {
        // Define enemy type (all same probability)
        //enemyType[i] = GetRandomValue(0, 3);
    
        // Probability system for enemies type
        int enemyProb = GetRandomValue(0, 100);
        
        if (enemyProb < 30) enemyType[i] = 0;
        else if (enemyProb < 60) enemyType[i] = 1;
        else if (enemyProb < 90) enemyType[i] = 2;
        else enemyType[i] = 3;

        // define enemy rail
        enemyRail[i] = GetRandomValue(0, 4);

        // Make sure not two consecutive enemies in the same row
        if (i > 0) while (enemyRail[i] == enemyRail[i - 1]) enemyRail[i] = GetRandomValue(0, 4);
        
        enemyBounds[i] = (Rectangle){ screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100 };
        enemyActive[i] = false;
    }
    
    // Define additional game variables
    int score = 0;
    float distance = 0.0f;
    int hiscore = 0;
    float hidistance = 0.0f;
    int foodBar = 0;
    int framesCounter = 0;
    
    unsigned char blue = 200;
    float timeCounter = 0;
    
    SetTargetFPS(60);       // Setup game frames per second
    //--------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        framesCounter++;
        
        // Sea color tint effect
        blue = 210 + 25 * sin(timeCounter);
        timeCounter += 0.01;

        // Game screens management
        switch (currentScreen)
        {
            case TITLE:
            {
                // Sea scrolling
                seaScrolling -= 2;
                if (seaScrolling <= -screenWidth) seaScrolling = 0; 
            
                // Press enter to change to gameplay screen
                if (IsKeyPressed(KEY_ENTER))
                {
                    currentScreen = GAMEPLAY;
                    framesCounter = 0;
                }
                
            } break;
            case GAMEPLAY:
            {
                // Background scrolling logic
                backScrolling--;
                if (backScrolling <= -screenWidth) backScrolling = 0; 
                
                // Sea scrolling logic
                seaScrolling -= (enemySpeed - 2);
                if (seaScrolling <= -screenWidth) seaScrolling = 0; 
            
                // Player movement logic
                if (IsKeyPressed(KEY_DOWN)) playerRail++;
                else if (IsKeyPressed(KEY_UP)) playerRail--;
                
                // Check player not out of rails
                if (playerRail > 4) playerRail = 4;
                else if (playerRail < 0) playerRail = 0;
            
                // Update player bounds
                playerBounds = (Rectangle){ 30 + 14, playerRail*120 + 90 + 14, 100, 100 };
                
                // Enemies activation logic (every 40 frames)        
                if (framesCounter > 40)
                {
                    for (int i = 0; i < MAX_ENEMIES; i++)
                    {
                        if (enemyActive[i] == false)
                        {
                            enemyActive[i] = true;
                            i = MAX_ENEMIES;
                        }
                    }
                    
                    framesCounter = 0;
                }
                
                // Enemies logic
                for (int i = 0; i < MAX_ENEMIES; i++)
                {
                    if (enemyActive[i])
                    {
                        enemyBounds[i].x -= enemySpeed;
                    }
                    
                    // Check enemies out of screen
                    if (enemyBounds[i].x <= 0 - 128)
                    {
                        enemyActive[i] = false;
                        enemyType[i] = GetRandomValue(0, 3);
                        enemyRail[i] = GetRandomValue(0, 4);
                        
                        // Make sure not two consecutive enemies in the same row
                        if (i > 0) while (enemyRail[i] == enemyRail[i - 1]) enemyRail[i] = GetRandomValue(0, 4);
                        
                        enemyBounds[i] = (Rectangle){ screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100 };
                    }
                }
                
                if (!gameraMode) enemySpeed += 0.005;
                
                // Check collision player vs enemies
                for (int i = 0; i < MAX_ENEMIES; i++)
                {
                    if (enemyActive[i])
                    {
                        if (CheckCollisionRecs(playerBounds, enemyBounds[i]))
                        {                       
                            if (enemyType[i] < 3)   // Bad enemies
                            {
                                if (gameraMode)
                                {
                                    if (enemyType[i] == 0) score += 50;
                                    else if (enemyType[i] == 1) score += 150;
                                    else if (enemyType[i] == 2) score += 300;
                                    
                                    foodBar += 15;
                                
                                    enemyActive[i] = false;
                                    
                                    // After enemy deactivation, reset enemy parameters to be reused
                                    enemyType[i] = GetRandomValue(0, 3);
                                    enemyRail[i] = GetRandomValue(0, 4);
                                    
                                    // Make sure not two consecutive enemies in the same row
                                    if (i > 0) while (enemyRail[i] == enemyRail[i - 1]) enemyRail[i] = GetRandomValue(0, 4);
                                    
                                    enemyBounds[i] = (Rectangle){ screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100 };
                                    
                                    PlaySound(eat);
                                }
                                else
                                {
                                    // Player die logic
                                    PlaySound(die);
                                
                                    currentScreen = ENDING;
                                    framesCounter = 0;
                                    
                                    // Save hiscore and hidistance for next game
                                    if (score > hiscore) hiscore = score;
                                    if (distance > hidistance) hidistance = distance;
                                }
                            }
                            else    // Sweet fish
                            {
                                enemyActive[i] = false;
                                enemyType[i] = GetRandomValue(0, 3);
                                enemyRail[i] = GetRandomValue(0, 4);
                                
                                // Make sure not two consecutive enemies in the same row
                                if (i > 0) while (enemyRail[i] == enemyRail[i - 1]) enemyRail[i] = GetRandomValue(0, 4);
                                
                                enemyBounds[i] = (Rectangle){ screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100 };
                                
                                if (!gameraMode) foodBar += 80;
                                else foodBar += 25;
                                
                                score += 10;
                                
                                if (foodBar == 400)
                                {
                                    gameraMode = true;
                                    
                                    PlaySound(growl);
                                }
                                
                                PlaySound(eat);
                            }
                        }
                    }
                }
                
                // Gamera mode logic
                if (gameraMode)
                {
                    foodBar--;
                    
                    if (foodBar <= 0) 
                    {
                        gameraMode = false;
                        enemySpeed -= 2;
                        if (enemySpeed < 10) enemySpeed = 10;
                    }
                }
        
                // Update distance counter
                distance += 0.5f;
            
            } break;
            case ENDING:
            {
                // Press enter to play again
                if (IsKeyPressed(KEY_ENTER))
                {
                    currentScreen = GAMEPLAY;
                    
                    // Reset player
                    playerRail = 1;
                    playerBounds = (Rectangle){ 30 + 14, playerRail*120 + 90 + 14, 100, 100 };
                    gameraMode = false;
                    
                    // Reset enemies data
                    for (int i = 0; i < MAX_ENEMIES; i++)
                    {
                        int enemyProb = GetRandomValue(0, 100);
                        
                        if (enemyProb < 30) enemyType[i] = 0;
                        else if (enemyProb < 60) enemyType[i] = 1;
                        else if (enemyProb < 90) enemyType[i] = 2;
                        else enemyType[i] = 3;
                        
                        //enemyType[i] = GetRandomValue(0, 3);
                        enemyRail[i] = GetRandomValue(0, 4);

                        // Make sure not two consecutive enemies in the same row
                        if (i > 0) while (enemyRail[i] == enemyRail[i - 1]) enemyRail[i] = GetRandomValue(0, 4);
                        
                        enemyBounds[i] = (Rectangle){ screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100 };
                        enemyActive[i] = false;
                    }
                    
                    enemySpeed = 10;
                    
                    // Reset game variables
                    score = 0;
                    distance = 0.0;
                    foodBar = 0;
                    framesCounter = 0;
                }
      
            } break;
            default: break;
        }
        //----------------------------------------------------------------------------------
        
        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();
        
            ClearBackground(RAYWHITE);
            
            // Draw background (common to all screens)
            DrawTexture(sky, 0, 0, WHITE);
            
            DrawTexture(mountains, backScrolling, 0, WHITE);
            DrawTexture(mountains, screenWidth + backScrolling, 0, WHITE);
            
            if (!gameraMode)
            {
                DrawTexture(sea, seaScrolling, 0, (Color){ 16, 189, blue, 255});
                DrawTexture(sea, screenWidth + seaScrolling, 0, (Color){ 16, 189, blue, 255});
            }
            else
            {
                DrawTexture(sea, seaScrolling, 0, (Color){ 255, 113, 66, 255});
                DrawTexture(sea, screenWidth + seaScrolling, 0, (Color){ 255, 113, 66, 255});
            }
            
            switch (currentScreen)
            {
                case TITLE:
                {
                    // Draw title
                    DrawTexture(title, screenWidth/2 - title.width/2, screenHeight/2 - title.height/2 - 80, WHITE);
                    
                    // Draw blinking text
                    if ((framesCounter/30) % 2) DrawTextEx(font, "PRESS ENTER", (Vector2){ screenWidth/2 - 150, 480 }, GetFontBaseSize(font), 0, WHITE);
                
                } break;
                case GAMEPLAY:
                {
                    // Draw water lines
                    for (int i = 0; i < 5; i++) DrawRectangle(0, i*120 + 120, screenWidth, 110, Fade(SKYBLUE, 0.1f));
                    
                    // Draw player
                    if (!gameraMode) DrawTexture(turtle, playerBounds.x - 14, playerBounds.y - 14, WHITE);
                    else DrawTexture(gamera, playerBounds.x - 64, playerBounds.y - 64, WHITE);
                    
                    // Draw player bounding box
                    //if (!gameraMode) DrawRectangleRec(playerBounds, Fade(GREEN, 0.4f));
                    //else DrawRectangleRec(playerBounds, Fade(ORANGE, 0.4f));
                    
                    // Draw enemies
                    for (int i = 0; i < MAX_ENEMIES; i++)
                    {
                        if (enemyActive[i]) 
                        {
                            // Draw enemies
                            switch(enemyType[i])
                            {
                                case 0: DrawTexture(shark, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                                case 1: DrawTexture(orca, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                                case 2: DrawTexture(swhale, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                                case 3: DrawTexture(fish, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                                default: break;
                            }
                            
                            // Draw enemies bounding boxes
                            /*
                            switch(enemyType[i])
                            {
                                case 0: DrawRectangleRec(enemyBounds[i], Fade(RED, 0.5f)); break;
                                case 1: DrawRectangleRec(enemyBounds[i], Fade(RED, 0.5f)); break;
                                case 2: DrawRectangleRec(enemyBounds[i], Fade(RED, 0.5f)); break;
                                case 3: DrawRectangleRec(enemyBounds[i], Fade(GREEN, 0.5f)); break;
                                default: break;
                            }
                            */
                        }
                    }
                    
                    // Draw gameplay interface
                    DrawRectangle(20, 20, 400, 40, Fade(GRAY, 0.4f));
                    DrawRectangle(20, 20, foodBar, 40, ORANGE);
                    DrawRectangleLines(20, 20, 400, 40, BLACK);
                    
                    DrawTextEx(font, FormatText("SCORE: %04i", score), (Vector2){ screenWidth - 300, 20 }, GetFontBaseSize(font), -2, ORANGE);
                    DrawTextEx(font, FormatText("DISTANCE: %04i", (int)distance), (Vector2){ 550, 20 }, GetFontBaseSize(font), -2, ORANGE);
                    
                    if (gameraMode)
                    {
                        DrawText("GAMERA MODE", 60, 22, 40, GRAY);
                        DrawTexture(gframe, 0, 0, Fade(WHITE, 0.5f));
                    }
            
                } break;
                case ENDING:
                {
                    // Draw a transparent black rectangle that covers all screen
                    DrawRectangle(0, 0, screenWidth, screenHeight, Fade(BLACK, 0.4f));
                
                    DrawTextEx(font, "GAME OVER", (Vector2){ 300, 160 }, GetFontBaseSize(font)*3, -2, MAROON);
                    
                    DrawTextEx(font, FormatText("SCORE: %04i", score), (Vector2){ 680, 350 }, GetFontBaseSize(font), -2, GOLD);
                    DrawTextEx(font, FormatText("DISTANCE: %04i", (int)distance), (Vector2){ 290, 350 }, GetFontBaseSize(font), -2, GOLD);
                    DrawTextEx(font, FormatText("HISCORE: %04i", hiscore), (Vector2){ 665, 400 }, GetFontBaseSize(font), -2, ORANGE);
                    DrawTextEx(font, FormatText("HIDISTANCE: %04i", (int)hidistance), (Vector2){ 270, 400 }, GetFontBaseSize(font), -2, ORANGE);
                    
                    // Draw blinking text
                    if ((framesCounter/30) % 2) DrawTextEx(font, "PRESS ENTER to REPLAY", (Vector2){ screenWidth/2 - 250, 520 }, GetFontBaseSize(font), -2, LIGHTGRAY);
                    
                } break;
                default: break;
            }

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    
    // Unload textures
    UnloadTexture(sky);
    UnloadTexture(mountains);
    UnloadTexture(sea);
    UnloadTexture(gframe);
    UnloadTexture(title);
    UnloadTexture(turtle);
    UnloadTexture(shark);
    UnloadTexture(orca);
    UnloadTexture(swhale);
    UnloadTexture(fish);
    UnloadTexture(gamera);
    
    // Unload font texture
    UnloadSpriteFont(font);
    
    // Unload sounds
    UnloadSound(eat);
    UnloadSound(die);
    UnloadSound(growl);
    
    StopMusicStream();      // Stop music
    CloseAudioDevice();     // Close audio device
    
    CloseWindow();          // Close window and OpenGL context
    //--------------------------------------------------------------------------------------
    
    return 0;
}
Beispiel #18
0
//
// Swap cards between two hands
//
// - take a high face card from the nSource hand and swap it 
//   for a lower card in the nDest hand
//
double CEasyBDoc::SwapPoints(int nDest, int nSource, double fMax, 
							 int nGameCode, int nSuitCode, int nSlamCode)
{
	//
	double fSrcPoints = PLAYER(nSource).CountCardPoints();
	double fDestPoints = PLAYER(nDest).CountCardPoints();
	CCard *pSrcCard,*pDestCard;
	double fDiff, fTotalLeft = fMax;
	int i,nSrcCard,nDestCard,nSrcVal,nDestVal;
	int nSuit,nOuterLoopCount,nInnerLoopCount;
	int	nTopmostLoopCount = 0;
	double fValSwapped = 0;
	do 
	{
		// values needed to observe Ace/King constraints
		int numAcesRequired = theApp.GetValue(tnumAcesForSlam,nSlamCode);
		int numAcesHeld = PLAYER(SOUTH).GetNumCardsOf(ACE) + PLAYER(NORTH).GetNumCardsOf(ACE);
		int numKingsRequired = theApp.GetValue(tnumKingsForSlam,nSlamCode);
		int numKingsHeld = PLAYER(SOUTH).GetNumCardsOf(KING) + PLAYER(NORTH).GetNumCardsOf(KING);
		// first see if there's an honor card in the source hand
		int nSum = 0;
		BOOL bIsHonor = FALSE;
		for(i=0;i<13;i++) 
		{
			if (ISHONOR(nSource,i)) 
			{
				bIsHonor = TRUE;
				break;
			}
//			nSum += HONOR_VALUE(PLAYER(nSource).m_holdings[i]->GetFaceValue());
		}
//		if (nSum == 0)
		if (!bIsHonor)
			return fValSwapped;	// out of high cards

		// else swap cards randomly
		// begin outer loop
		nOuterLoopCount = 0;
		do {
			// first grab an honor from the source hand
			BOOL bInvalid;
			nInnerLoopCount = 0;
			do 
			{
				bInvalid = FALSE;
				nSrcCard = GetRandomValue(12);
				pSrcCard = PLAYER(nSource).GetCardByPosition(nSrcCard);
				nSrcVal = pSrcCard->GetFaceValue();
				nSuit = pSrcCard->GetSuit();
				// check that dest has cards in this suit
				if (PLAYER(nDest).GetNumCardsInSuit(nSuit) == 0) 
				{
					bInvalid = TRUE;
				} 
				else if (nSuitCode == 1) 
				{
					// check for suit preference
					// if minor suit, don't pull a clubs or
					// diamonds honor above minimum
					if ( ((nSuit == CLUBS) || (nSuit == DIAMONDS)) &&
						 ((nSource == SOUTH) || (nSource == NORTH)) &&
						 (nSrcVal >= theApp.GetValue(tnMinTopMinorCard)) )
						bInvalid = TRUE;
				} 
				else if (nSuitCode == 2) 
				{
					if ( ((nSuit == HEARTS) || (nSuit == SPADES)) &&
						 ((nSource == SOUTH) || (nSource == NORTH)) &&
						 (nSrcVal >= theApp.GetValue(tnMinTopMajorCard)) )
						bInvalid = TRUE;
				}
				// if dealing slam, don't pull an ace from N/S
				// if that will put partnership below limit
				if ((nGameCode == 2) && (nSrcVal == ACE) && 
						((nSource == SOUTH) || (nSource == NORTH)) ) 
				{
					if (numAcesHeld <= numAcesRequired)
						bInvalid = TRUE;
				}
				// likewise, also don't pull a king from N/S
				// if that will put partnership below limit
				if ((nGameCode == 2) && (nSrcVal == KING) && 
						((nSource == SOUTH) || (nSource == NORTH)) ) 
				{
					if (numKingsHeld <= numKingsRequired)
						bInvalid = TRUE;
				}
				nInnerLoopCount++;
			} while ( ((!ISHONOR(nSource, nSrcCard)) || (bInvalid))
							&& (nInnerLoopCount < 40));
			if (nInnerLoopCount >= 40)
				break;
			// then grab a lesser card from the dest hand of 
			// the same suit
			// this could fail under certain circumstances
			nInnerLoopCount = 0;
			bInvalid = FALSE;
			do 
			{
				nDestCard = GetRandomValue(PLAYER(nDest).GetNumCardsInSuit(nSuit)-1);
				pDestCard = PLAYER(nDest).GetCardInSuit(nSuit,nDestCard);
				if (pDestCard == NULL) 
				{	
					// shouldn't happen, but does -- dunno why
					nInnerLoopCount++;
					continue;
				}
				nDestVal = (pDestCard->GetFaceValue() > 10)? pDestCard->GetFaceValue() : 10;
				fDiff = nSrcVal - nDestVal;
				// check to see that we don't replace a king with an ace
				// thus possibly violating a minimum king count requirement
				if ((nGameCode == 2) && (nSrcVal == ACE) && (nDestVal == KING) &&
							((nDest == SOUTH) || (nDest == NORTH)) ) 
				{
					if (numKingsHeld <= numKingsRequired)
						bInvalid = TRUE;
				}
				// increment counter -- this loop could possibly fail
				nInnerLoopCount++;
			} while (((fDiff <= 0) || (fDiff > fTotalLeft) || (bInvalid))
									 && (nInnerLoopCount < 40));
			if (nInnerLoopCount >= 40)
				break;
			nOuterLoopCount++;
			// continue looping until a suitable pair of cards is found
		} while ((fDiff > fTotalLeft) && (nOuterLoopCount < 40));
		//
		if ((fDiff > 0) && (fDiff <= fTotalLeft) && 
				(nInnerLoopCount < 40) && (nOuterLoopCount < 40)) 
		{
			// success -- swap the two cards
			PLAYER(nSource).RemoveCardFromHand(pSrcCard);
			PLAYER(nDest).RemoveCardFromHand(pDestCard);
			PLAYER(nDest).AddCardToHand(pSrcCard,TRUE);
			PLAYER(nSource).AddCardToHand(pDestCard,TRUE);
			//
			PLAYER(nDest).CountCardPoints(TRUE);
			PLAYER(nSource).CountCardPoints(TRUE);
			//
			fValSwapped += fDiff;
			fTotalLeft -= fDiff;
		}
		nTopmostLoopCount++;

	} while ((fTotalLeft > 0) && (nTopmostLoopCount < 30));
	//
	return fValSwapped;
}
Beispiel #19
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 1280;
    const int screenHeight = 720;

    // Init window
    InitWindow(screenWidth, screenHeight, "Dr. Turtle & Mr. GAMERA");

    // Load game resources: textures
    Texture2D sky = LoadTexture("resources/sky.png");
    Texture2D mountains = LoadTexture("resources/mountains.png");
    Texture2D sea = LoadTexture("resources/sea.png");
    Texture2D title = LoadTexture("resources/title.png");
    Texture2D turtle = LoadTexture("resources/turtle.png");
    Texture2D gamera = LoadTexture("resources/gamera.png");
    Texture2D shark = LoadTexture("resources/shark.png");
    Texture2D orca = LoadTexture("resources/orca.png");
    Texture2D swhale = LoadTexture("resources/swhale.png");
    Texture2D fish = LoadTexture("resources/fish.png");

    // Define scrolling variables
    int backScrolling = 0;
    int seaScrolling = 0;

    // Define current screen
    GameScreen currentScreen = TITLE;

    // Define player variables
    int playerRail = 1;
    Rectangle playerBounds = { 30 + 14, playerRail*120 + 90 + 14, 100, 100 };
    bool gameraMode = false;

    // Define enemies variables
    Rectangle enemyBounds[MAX_ENEMIES];
    int enemyRail[MAX_ENEMIES];
    int enemyType[MAX_ENEMIES];
    bool enemyActive[MAX_ENEMIES];
    float enemySpeed = 10;

    // Init enemies variables
    for (int i = 0; i < MAX_ENEMIES; i++)
    {
        // Define enemy type (all same probability)
        enemyType[i] = GetRandomValue(0, 3);

        // Define enemy rail
        enemyRail[i] = GetRandomValue(0, 4);

        // Define enemy bounding box
        enemyBounds[i] = (Rectangle) {
            screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100
        };
        enemyActive[i] = false;
    }

    // Define additional game variables
    int foodBar = 0;
    int framesCounter = 0;

    SetTargetFPS(60);       // Setup game frames per second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        framesCounter++;

        // Game screens management
        switch (currentScreen)
        {
        case TITLE:
        {
            // Sea scrolling
            seaScrolling -= 2;
            if (seaScrolling <= -screenWidth) seaScrolling = 0;

            // Press enter to change to gameplay screen
            if (IsKeyPressed(KEY_ENTER))
            {
                currentScreen = GAMEPLAY;
                framesCounter = 0;
            }

        }
        break;
        case GAMEPLAY:
        {
            // Background scrolling logic
            backScrolling--;
            if (backScrolling <= -screenWidth) backScrolling = 0;

            // Sea scrolling logic
            seaScrolling -= (enemySpeed - 2);
            if (seaScrolling <= -screenWidth) seaScrolling = 0;

            // Player movement logic
            if (IsKeyPressed(KEY_DOWN)) playerRail++;
            else if (IsKeyPressed(KEY_UP)) playerRail--;

            // Check player not out of rails
            if (playerRail > 4) playerRail = 4;
            else if (playerRail < 0) playerRail = 0;

            // Update player bounds
            playerBounds = (Rectangle) {
                30 + 14, playerRail*120 + 90 + 14, 100, 100
            };

            // Enemies activation logic (every 40 frames)
            if (framesCounter > 40)
            {
                for (int i = 0; i < MAX_ENEMIES; i++)
                {
                    if (enemyActive[i] == false)
                    {
                        enemyActive[i] = true;
                        i = MAX_ENEMIES;
                    }
                }

                framesCounter = 0;
            }

            // Enemies logic
            for (int i = 0; i < MAX_ENEMIES; i++)
            {
                if (enemyActive[i])
                {
                    enemyBounds[i].x -= enemySpeed;
                }

                // Check enemies out of screen
                if (enemyBounds[i].x <= 0 - 128)
                {
                    enemyType[i] = GetRandomValue(0, 3);
                    enemyRail[i] = GetRandomValue(0, 4);

                    enemyBounds[i] = (Rectangle) {
                        screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100
                    };
                    enemyActive[i] = false;
                }
            }

            // Enemies speed increase every frame
            if (!gameraMode) enemySpeed += 0.005;

            // Check collision player vs enemies
            for (int i = 0; i < MAX_ENEMIES; i++)
            {
                if (enemyActive[i])
                {
                    if (CheckCollisionRecs(playerBounds, enemyBounds[i]))
                    {
                        if (enemyType[i] < 3)   // Bad enemies
                        {
                            if (gameraMode)
                            {
                                foodBar += 15;

                                // After enemy deactivation, reset enemy parameters to be reused
                                enemyType[i] = GetRandomValue(0, 3);
                                enemyRail[i] = GetRandomValue(0, 4);

                                enemyBounds[i] = (Rectangle) {
                                    screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100
                                };
                                enemyActive[i] = false;
                            }
                            else
                            {
                                // Player die logic
                                currentScreen = ENDING;
                                framesCounter = 0;
                            }
                        }
                        else    // Sweet fish
                        {
                            enemyActive[i] = false;
                            enemyType[i] = GetRandomValue(0, 3);
                            enemyRail[i] = GetRandomValue(0, 4);

                            enemyBounds[i] = (Rectangle) {
                                screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100
                            };

                            if (!gameraMode) foodBar += 80;
                            else foodBar += 25;

                            if (foodBar == 400)
                            {
                                gameraMode = true;
                            }
                        }
                    }
                }
            }

            // Gamera mode logic
            if (gameraMode)
            {
                foodBar--;

                if (foodBar <= 0)
                {
                    gameraMode = false;
                    enemySpeed -= 2;
                    if (enemySpeed < 10) enemySpeed = 10;
                }
            }

        }
        break;
        case ENDING:
        {
            // Press enter to play again
            if (IsKeyPressed(KEY_ENTER))
            {
                currentScreen = GAMEPLAY;

                // Reset player
                playerRail = 1;
                playerBounds = (Rectangle) {
                    30 + 14, playerRail*120 + 90 + 14, 100, 100
                };
                gameraMode = false;

                // Reset enemies data
                for (int i = 0; i < MAX_ENEMIES; i++)
                {
                    enemyType[i] = GetRandomValue(0, 3);
                    enemyRail[i] = GetRandomValue(0, 4);

                    enemyBounds[i] = (Rectangle) {
                        screenWidth + 14, 120*enemyRail[i] + 90 + 14, 100, 100
                    };
                    enemyActive[i] = false;
                }

                enemySpeed = 10;

                // Reset game variables
                foodBar = 0;
                framesCounter = 0;
            }

        }
        break;
        default:
            break;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

        ClearBackground(RAYWHITE);

        // Draw background (common to all screens)
        DrawTexture(sky, 0, 0, WHITE);

        DrawTexture(mountains, backScrolling, 0, WHITE);
        DrawTexture(mountains, screenWidth + backScrolling, 0, WHITE);

        if (!gameraMode)
        {
            DrawTexture(sea, seaScrolling, 0, BLUE);
            DrawTexture(sea, screenWidth + seaScrolling, 0, BLUE);
        }
        else
        {
            DrawTexture(sea, seaScrolling, 0, RED);
            DrawTexture(sea, screenWidth + seaScrolling, 0, RED);
        }

        switch (currentScreen)
        {
        case TITLE:
        {
            // Draw title
            DrawTexture(title, screenWidth/2 - title.width/2, screenHeight/2 - title.height/2 - 80, WHITE);

            // Draw blinking text
            if ((framesCounter/30) % 2) DrawText("PRESS ENTER", 480, 480, 40, BLACK);

        }
        break;
        case GAMEPLAY:
        {
            // Draw water lines
            for (int i = 0; i < 5; i++) DrawRectangle(0, i*120 + 120, screenWidth, 110, Fade(SKYBLUE, 0.1f));

            // Draw player
            if (!gameraMode) DrawTexture(turtle, playerBounds.x - 14, playerBounds.y - 14, WHITE);
            else DrawTexture(gamera, playerBounds.x - 64, playerBounds.y - 64, WHITE);

            // Draw player bounding box
            //if (!gameraMode) DrawRectangleRec(playerBounds, Fade(GREEN, 0.4f));
            //else DrawRectangleRec(playerBounds, Fade(ORANGE, 0.4f));

            // Draw enemies
            for (int i = 0; i < MAX_ENEMIES; i++)
            {
                if (enemyActive[i])
                {
                    // Draw enemies
                    /*
                    switch(enemyType[i])
                    {
                        case 0: DrawTexture(shark, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                        case 1: DrawTexture(orca, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                        case 2: DrawTexture(swhale, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                        case 3: DrawTexture(fish, enemyBounds[i].x - 14, enemyBounds[i].y - 14, WHITE); break;
                        default: break;
                    }
                    */

                    // Draw enemies bounding boxes
                    switch(enemyType[i])
                    {
                    case 0:
                        DrawRectangleRec(enemyBounds[i], RED);
                        break;
                    case 1:
                        DrawRectangleRec(enemyBounds[i], RED);
                        break;
                    case 2:
                        DrawRectangleRec(enemyBounds[i], RED);
                        break;
                    case 3:
                        DrawRectangleRec(enemyBounds[i], GREEN);
                        break;
                    default:
                        break;
                    }
                }
            }

            // Draw gameplay interface

            // Draw food bar
            DrawRectangle(20, 20, 400, 40, Fade(GRAY, 0.4f));
            DrawRectangle(20, 20, foodBar, 40, ORANGE);
            DrawRectangleLines(20, 20, 400, 40, BLACK);

            if (gameraMode)
            {
                DrawText("GAMERA MODE", 60, 22, 40, GRAY);
            }

        }
        break;
        case ENDING:
        {
            // Draw a transparent black rectangle that covers all screen
            DrawRectangle(0, 0, screenWidth, screenHeight, Fade(BLACK, 0.4f));

            DrawText("GAME OVER", 300, 200, 100, MAROON);

            // Draw blinking text
            if ((framesCounter/30) % 2) DrawText("PRESS ENTER to REPLAY", 400, 420, 30, LIGHTGRAY);

        }
        break;
        default:
            break;
        }

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------

    // Unload textures
    UnloadTexture(sky);
    UnloadTexture(mountains);
    UnloadTexture(sea);
    UnloadTexture(title);
    UnloadTexture(turtle);
    UnloadTexture(gamera);
    UnloadTexture(shark);
    UnloadTexture(orca);
    UnloadTexture(swhale);
    UnloadTexture(fish);

    CloseWindow();          // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #20
0
// Ending Screen Update logic
void UpdateEndingScreen(void)
{
    framesCounter += 1*TIME_FACTOR;
  
    switch (endingCounter)
    {
        case DELAY:
        {
            if(framesCounter >= 10)
            {
                endingCounter = SEASONS;
                framesCounter = 0;
            }
            
        } break;
        case SEASONS:
        {
            if (seasons > 0)
            {
                seasonsCounter = (int)LinearEaseIn((float)framesCounter, 0.0f, (float)(seasons), 90.0f);
                clockRotation = LinearEaseIn((float)framesCounter, (float)initRotation, (float)-(finalRotation - initRotation), 90.0f);
                
                if (framesCounter >= 90)
                {
                    endingCounter = LEAVES;
                    framesCounter = 0;
                }
            }
            else endingCounter = LEAVES;
            
#if (defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB))
            if (IsGestureDetected(GESTURE_TAP))
            {
                seasonsCounter = seasons;
                clockRotation = finalRotation;
                framesCounter = 0;
                endingCounter = LEAVES;
            }
#elif (defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB))
            if (IsKeyPressed(KEY_ENTER))
            {
                seasonsCounter = seasons;
                clockRotation = finalRotation;
                framesCounter = 0;
                endingCounter = LEAVES;
            }
#endif
        } break;
        case LEAVES: 
        {
            if (currentLeaves > 0)
            {
                if (currentLeavesEnding == currentLeaves)
                {
                    endingCounter = KILLS;
                    framesCounter = 0;
                }
                else if (currentLeavesEnding < currentLeaves)
                {
                    if (framesCounter >= 4)
                    {
                        currentLeavesEnding += 1;
                        framesCounter = 0;
                    }
                    
                    for (int i = 0; i < 20; i++)
                    {
                        if (!leafParticles[i].active)
                        {
                            leafParticles[i].position = (Vector2){ GetScreenWidth()*0.46, GetScreenHeight()*0.32};
                            leafParticles[i].alpha = 1.0f;
                            leafParticles[i].active = true;
                        }
                    }
                }
            }
            else endingCounter = KILLS;       

#if (defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB))
            if (IsGestureDetected(GESTURE_TAP))
            {
                currentLeavesEnding = currentLeaves;
                framesCounter = 0;
                endingCounter = KILLS;
            }
#elif (defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB))
            if (IsKeyPressed(KEY_ENTER))
            {
                currentLeavesEnding = currentLeaves;
                framesCounter = 0;
                endingCounter = KILLS;
            }  
#endif
        } break;
        case KILLS:
        {
            if (score > 0)
            {
                if (framesCounter <= 90 && !replaying)
                {
                    currentScore = (int)LinearEaseIn((float)framesCounter, 0.0f, (float)(score), 90.0f);
                }
                
                framesKillsCounter += 1*TIME_FACTOR;
                
                for (int i = 0; i < MAX_KILLS; i++)
                {
                    if (framesKillsCounter >= drawTimer && active[i] == false)
                    {
                        active[i] = true;
                        framesKillsCounter = 0;
                    }
                }
                
                if (framesCounter >= 90)
                {
                    endingCounter = REPLAY;
                    framesCounter = 0;
                }
            }
            else endingCounter = REPLAY;   
            
#if (defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB))
            if (IsGestureDetected(GESTURE_TAP))
            {
               currentScore = score;
               framesCounter = 0;
               for (int i = 0; i < MAX_KILLS; i++) active[i] = true;
               endingCounter = REPLAY;
            }
#elif (defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB))
            if (IsKeyPressed(KEY_ENTER))
            {
               currentScore = score;
               framesCounter = 0;
               for (int i = 0; i < MAX_KILLS; i++) active[i] = true;
               endingCounter = REPLAY;
            }
#endif
        } break;
        case REPLAY:
        {
#if (defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB))
            if (IsGestureDetected(GESTURE_TAP)) replaying = true;
#elif (defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB))
            if (IsKeyPressed(KEY_ENTER)) replaying = true;
#endif
            if (replaying)
            {
                replayTimer += 1*TIME_FACTOR;
                
                if (replayTimer >= 30)
                {
                    finishScreen = 1;
                    initSeason = GetRandomValue(0, 3);
                }
                
                buttonPlayColor = GOLD;
            }
        } break;
    }
    
    for (int i = 0; i < 20; i++)
    {
        if (leafParticles[i].active == true)
        {
            leafParticles[i].position.x +=  leafParticles[i].speed.x;
            leafParticles[i].position.y +=  leafParticles[i].speed.y;
            leafParticles[i].rotation += 6;
            leafParticles[i].alpha -= 0.03f;
            leafParticles[i].size -= 0.004;

            if (leafParticles[i].size <= 0) leafParticles[i].size = 0.0f;

            if (leafParticles[i].alpha <= 0)
            {
                leafParticles[i].alpha = 0.0f;
                leafParticles[i].active = false;
            }               
        }
    }

    // Buttons logic
#if (defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB))
    if ((IsGestureDetected(GESTURE_TAP)) && CheckCollisionPointRec(GetTouchPosition(0), playButton))
    {
        endingCounter = REPLAY;
        replaying = true;
    }
    
#elif (defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB))
    if (CheckCollisionPointRec(GetMousePosition(), playButton)) 
    {
        buttonPlayColor = GOLD;  
        if (IsMouseButtonPressed(0)) 
        {
            endingCounter = REPLAY;
            replaying = true;
        }
    }       
    else buttonPlayColor = WHITE;

    if (CheckCollisionPointRec(GetMousePosition(), shopButton)) buttonShopColor = GOLD;
    else buttonShopColor = WHITE;
    
    if (CheckCollisionPointRec(GetMousePosition(), trophyButton)) buttonTrophyColor = GOLD;
    else buttonTrophyColor = WHITE;
    
    if (CheckCollisionPointRec(GetMousePosition(), shareButton)) buttonShareColor = GOLD;
    else buttonShareColor = WHITE;
#endif
}
Beispiel #21
0
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");

    Rectangle player = { 400, 280, 40, 40 };
    Rectangle buildings[MAX_BUILDINGS] = { 0 };
    Color buildColors[MAX_BUILDINGS] = { 0 };

    int spacing = 0;

    for (int i = 0; i < MAX_BUILDINGS; i++)
    {
        buildings[i].width = GetRandomValue(50, 200);
        buildings[i].height = GetRandomValue(100, 800);
        buildings[i].y = screenHeight - 130 - buildings[i].height;
        buildings[i].x = -6000 + spacing;

        spacing += buildings[i].width;

        buildColors[i] = (Color){ GetRandomValue(200, 240), GetRandomValue(200, 240), GetRandomValue(200, 250), 255 };
    }

    Camera2D camera = { 0 };
    camera.target = (Vector2){ player.x + 20, player.y + 20 };
    camera.offset = (Vector2){ 0, 0 };
    camera.rotation = 0.0f;
    camera.zoom = 1.0f;

    SetTargetFPS(60);                   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())        // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        if (IsKeyDown(KEY_RIGHT))
        {
            player.x += 2;              // Player movement
            camera.offset.x -= 2;       // Camera displacement with player movement
        }
        else if (IsKeyDown(KEY_LEFT))
        {
            player.x -= 2;              // Player movement
            camera.offset.x += 2;       // Camera displacement with player movement
        }

        // Camera target follows player
        camera.target = (Vector2){ player.x + 20, player.y + 20 };

        // Camera rotation controls
        if (IsKeyDown(KEY_A)) camera.rotation--;
        else if (IsKeyDown(KEY_S)) camera.rotation++;

        // Limit camera rotation to 80 degrees (-40 to 40)
        if (camera.rotation > 40) camera.rotation = 40;
        else if (camera.rotation < -40) camera.rotation = -40;

        // Camera zoom controls
        camera.zoom += ((float)GetMouseWheelMove()*0.05f);

        if (camera.zoom > 3.0f) camera.zoom = 3.0f;
        else if (camera.zoom < 0.1f) camera.zoom = 0.1f;

        // Camera reset (zoom and rotation)
        if (IsKeyPressed(KEY_R))
        {
            camera.zoom = 1.0f;
            camera.rotation = 0.0f;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            BeginMode2D(camera);

                DrawRectangle(-6000, 320, 13000, 8000, DARKGRAY);

                for (int i = 0; i < MAX_BUILDINGS; i++) DrawRectangleRec(buildings[i], buildColors[i]);

                DrawRectangleRec(player, RED);

                DrawLine(camera.target.x, -screenHeight*10, camera.target.x, screenHeight*10, GREEN);
                DrawLine(-screenWidth*10, camera.target.y, screenWidth*10, camera.target.y, GREEN);

            EndMode2D();

            DrawText("SCREEN AREA", 640, 10, 20, RED);

            DrawRectangle(0, 0, screenWidth, 5, RED);
            DrawRectangle(0, 5, 5, screenHeight - 10, RED);
            DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED);
            DrawRectangle(0, screenHeight - 5, screenWidth, 5, RED);

            DrawRectangle( 10, 10, 250, 113, Fade(SKYBLUE, 0.5f));
            DrawRectangleLines( 10, 10, 250, 113, BLUE);

            DrawText("Free 2d camera controls:", 20, 20, 10, BLACK);
            DrawText("- Right/Left to move Offset", 40, 40, 10, DARKGRAY);
            DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, DARKGRAY);
            DrawText("- A / S to Rotate", 40, 80, 10, DARKGRAY);
            DrawText("- R to reset Zoom and Rotation", 40, 100, 10, DARKGRAY);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #22
0
//
// DealSpecial()
//
// Possible codes:
// ---------------
// Game Code: 0 = Any (Random)
// 			  1 = Game
// 			  2 = Slam
// Suit Code: 0 = Any
// 			  1 = Minor
// 			  2 = Major
// 			  3 = NoTrump
// Slam Code: 0 = Any
//			  1 = Small Slam
//			  2 = Grand Slam
//
void CEasyBDoc::DealSpecial(int nGameCode, int nSuitCode, int nSlamCode, int nTeam, int nDealNumber) 
{
	CString strFeedback;

	//
	CMainFrame::SetStatusMessage("Performing deal...");

	// validate inputs
	if ((nGameCode < 0 ) || (nGameCode > 2) ||
				(nSuitCode < 0 ) || (nSuitCode > 3) ||
				(nSlamCode < 0 ) || (nSlamCode > 2) )
		return;

	// first clear all hands
	InitNewHand();

	// delete document info
	if (!m_bReviewingGame)
		DeleteContents();

	// save special deal code
	m_nSpecialDealCode = (nGameCode << 6) | (nSuitCode << 4) | (nSlamCode << 2) | nTeam;

	// perform the initial shuffle
	m_nDealNumber = deck.Shuffle(nDealNumber);

	// set busy cursor
	pVIEW->SetCurrentMode(CEasyBView::MODE_WAITSPECIALDEAL);

	// first set target points
	int nMin, nMax;
	double fScoreTarget;
	//
	switch (nGameCode) 
	{

		case 0:
			// any random deal
			break;

		case 1:
			// game deal
			nMin = theApp.GetValue(tnRequiredPointsForGame,nSuitCode,0);
			nMax = theApp.GetValue(tnRequiredPointsForGame,nSuitCode,1);
			fScoreTarget = nMin + GetRandomValue(nMax - nMin);
			switch(nSuitCode) 
			{
				case 0:
					// game hand, any suit
					strFeedback.Format("Dealt game hand\n");
					break;
				case 1:
					// game hand, minor suit
					strFeedback.Format("Dealt Minor game hand\n");
					break;
				case 2:
					// game hand, major suit
					strFeedback.Format("Dealt Major game hand\n");
					break;
				case 3:
					// game hand, notrumps
					strFeedback.Format("Dealt NoTrump game hand\n");
					break;
			}
			break;

		case 2:
			// slam deal
			nMin = theApp.GetValue(tnRequiredPointsForSlam,nSlamCode,0);
			nMax = theApp.GetValue(tnRequiredPointsForSlam,nSlamCode,1);
			fScoreTarget = nMin + GetRandomValue(nMax - nMin);
			switch(nSlamCode) 
			{
				case 0:
					// any slam
					strFeedback.Format("Dealt slam hand\n");
					break;
				case 1: 
					// small slam
					strFeedback.Format("Dealt small slam hand\n");
					break;
				case 2: 
					// grand slam
					strFeedback.Format("Dealt grand slam hand\n");
					break;
			}
			break;
	}

	// declare loop counters
	int i;
	int nOuterLoopCount = 0;
	int nAceLoopCount1, nAceLoopCount2;
	int nKingLoopCount1, nKingLoopCount2;
	int nPointSwapLoopCount, nFailCount;

shuffle:
	nOuterLoopCount++;
	// check if we've exceeded the limit on iterations
	if (nOuterLoopCount >= MAX_SPECIAL_DEAL_ITERATIONS) 
	{
		AfxMessageBox("Failed to meet hand requirements.  Try again.");
		pVIEW->ClearMode();
		return;
	}

/*
	// every 100 count, reseed the random # generator
	if (((nOuterLoopCount % 100) == 0) && (nOuterLoopCount > 0))
		srand((unsigned)time(NULL));
*/

	// assign new hands
	DealCards();


	//
	//----------------------------------------------------------
	//
	// Now check the strength of N/S's hands
	//
	double fSouthPoints, fNorthPoints;
	if (nSuitCode != 3) 
	{
		fSouthPoints = PLAYER(SOUTH).GetTotalPoints();
		fNorthPoints = PLAYER(NORTH).GetTotalPoints();
	} 
	else 
	{
		// No Trumps; count high card points only
		fSouthPoints = PLAYER(SOUTH).GetHCPoints();
		fNorthPoints = PLAYER(NORTH).GetHCPoints();
	}
	double fTotalPoints = fSouthPoints + fNorthPoints;
	double fDiff, fSwapped;
	int nSource,nDest;

	// at this point, check cards' distribution
	int numInSuit[4];
	BOOL bSuitFit[4];
	for(i=0;i<4;i++) 
	{
		numInSuit[i] = PLAYER(SOUTH).GetNumCardsInSuit(i) +
						PLAYER(NORTH).GetNumCardsInSuit(i);
		// check for a proper card distribution (min 4/3)
		int nDistIndex = theApp.GetValue(tnMinSuitDistributions,nSuitCode-1);
		int nDistVal[2];
		nDistVal[0] = theApp.GetValue(tnMinSuitDistributions,nSuitCode-1,nDistIndex,0);
		nDistVal[1] = theApp.GetValue(tnMinSuitDistributions,nSuitCode-1,nDistIndex,1);
		if ((nSuitCode == 1) || (nSuitCode == 2)) 
		{
			if ( ((PLAYER(SOUTH).GetNumCardsInSuit(i) >= nDistVal[0]) &&
						  (PLAYER(NORTH).GetNumCardsInSuit(i) >= nDistVal[1])) ||
			     ((PLAYER(NORTH).GetNumCardsInSuit(i) >= nDistVal[0]) &&
						  (PLAYER(SOUTH).GetNumCardsInSuit(i) >= nDistVal[1])) )
				bSuitFit[i] = TRUE;
			else
				bSuitFit[i] = FALSE;
		}
		else 
		{
			// generic suit or no trumps specified; default to
			// 4/3 for fit determination
			if ( ((PLAYER(SOUTH).GetNumCardsInSuit(i) >= 3) &&
				  (PLAYER(NORTH).GetNumCardsInSuit(i) >= 4)) ||
			     ((PLAYER(NORTH).GetNumCardsInSuit(i) >= 3) &&
				  (PLAYER(SOUTH).GetNumCardsInSuit(i) >= 4)) )
				bSuitFit[i] = TRUE;
			else
				bSuitFit[i] = FALSE;
		}
	}

	//
	if (nSuitCode == 3) 
	{

		// No Trump contract -- check hand balance
		int nMaxImbalance = theApp.GetValue(tnMaxImbalanceForNT);
		if (theApp.GetValue(tbNeedTwoBalancedTrumpHands)) 
		{
			// both players need balanced hands
			if ((PLAYER(SOUTH).GetBalanceValue() > nMaxImbalance) ||
					(PLAYER(NORTH).GetBalanceValue() > nMaxImbalance))
				goto shuffle;
		} 
		else 
		{
			// at least one player has balanced hand
			if ((PLAYER(SOUTH).GetBalanceValue() > nMaxImbalance) && 
					(PLAYER(NORTH).GetBalanceValue() > nMaxImbalance))
				goto shuffle;
		}

	} 
	else if (nSuitCode == 2) 
	{

		// major suit game -- need at least one major suit
		// that has >= min cards
		int nCardsInMajor = theApp.GetValue(tnMinCardsInMajor);	
		if ((numInSuit[HEARTS] < nCardsInMajor) &&
					(numInSuit[SPADES] < nCardsInMajor))
			goto shuffle;
		// also need a minimum 4-3 fit in a major suit
		if ((!bSuitFit[HEARTS]) && (!bSuitFit[SPADES]))
			goto shuffle;
		// and also check that the suit is adequately topped
		BOOL bTopped = FALSE;
		int nMinTopMajorCard = theApp.GetValue(tnMinTopMajorCard);
		if ((bSuitFit[HEARTS]) && (PLAYER(SOUTH).GetNumCardsInSuit(HEARTS) >= 4) &&
			(PLAYER(SOUTH).GetCardInSuit(HEARTS,0)->GetFaceValue() >= nMinTopMajorCard))
			bTopped = TRUE;
		if ((bSuitFit[SPADES]) && (PLAYER(SOUTH).GetNumCardsInSuit(SPADES) >= 4) &&
			(PLAYER(SOUTH).GetCardInSuit(SPADES,0)->GetFaceValue() >= nMinTopMajorCard))
			bTopped = TRUE;
		if ((bSuitFit[HEARTS]) && (PLAYER(NORTH).GetNumCardsInSuit(HEARTS) >= 4) &&
			(PLAYER(NORTH).GetCardInSuit(HEARTS,0)->GetFaceValue() >= nMinTopMajorCard))
			bTopped = TRUE;
		if ((bSuitFit[SPADES]) && (PLAYER(NORTH).GetNumCardsInSuit(SPADES) >= 4) &&
			(PLAYER(NORTH).GetCardInSuit(SPADES,0)->GetFaceValue() >= nMinTopMajorCard))
			bTopped = TRUE;
		if (!bTopped)
			goto shuffle;

	} 
	else if (nSuitCode == 1) 
	{

		// minor suit game -- need at least one major suit
		// that has >= min cards
		int nCardsInMinor = theApp.GetValue(tnMinCardsInMinor);	
		if ((numInSuit[CLUBS] < nCardsInMinor) &&
					(numInSuit[DIAMONDS] < nCardsInMinor))
			goto shuffle;
		// also need a minimum 4-3 fit in a minor suit
		if ((!bSuitFit[CLUBS]) && (!bSuitFit[DIAMONDS]))
			goto shuffle;
		// and also check that the suit is adequately topped
		BOOL bTopped = FALSE;
		int nMinTopMinorCard = theApp.GetValue(tnMinTopMinorCard);
		if ((bSuitFit[CLUBS]) && (PLAYER(SOUTH).GetNumCardsInSuit(CLUBS) >= 4) &&
			(PLAYER(SOUTH).GetCardInSuit(CLUBS,0)->GetFaceValue() >= nMinTopMinorCard))
			bTopped = TRUE;
		if ((bSuitFit[DIAMONDS]) && (PLAYER(SOUTH).GetNumCardsInSuit(DIAMONDS) >= 4) &&
			(PLAYER(SOUTH).GetCardInSuit(DIAMONDS,0)->GetFaceValue() >= nMinTopMinorCard))
			bTopped = TRUE;
		if ((bSuitFit[CLUBS]) && (PLAYER(NORTH).GetNumCardsInSuit(CLUBS) >= 4) &&
			(PLAYER(NORTH).GetCardInSuit(CLUBS,0)->GetFaceValue() >= nMinTopMinorCard))
			bTopped = TRUE;
		if ((bSuitFit[DIAMONDS]) && (PLAYER(NORTH).GetNumCardsInSuit(DIAMONDS) >= 4) &&
			(PLAYER(NORTH).GetCardInSuit(DIAMONDS,0)->GetFaceValue() >= nMinTopMinorCard))
			bTopped = TRUE;
		if (!bTopped)
			goto shuffle;

	}

	//
	//----------------------------------------------------------
	//
	// Fudging time --
	//
	// for a grand slam hand, check to make sure there are some 
	// non-ace, non-king honors in the N/S suits.  This will make
	// it easier to trade down points later on
	if ((nGameCode == 2) && (nSlamCode == 2)) 
	{
		double fDiff1 = m_pPlayer[SOUTH]->GetHCPoints() - (m_pPlayer[SOUTH]->GetNumCardsOf(ACE)*4 + m_pPlayer[SOUTH]->GetNumCardsOf(KING)*3);
		double fDiff2 = m_pPlayer[NORTH]->GetHCPoints() - (m_pPlayer[NORTH]->GetNumCardsOf(ACE)*4 + m_pPlayer[NORTH]->GetNumCardsOf(KING)*3);
		// #### TEMP ####
		double fHC1 = m_pPlayer[SOUTH]->GetHCPoints();
		int nAces1 = m_pPlayer[SOUTH]->GetNumCardsOf(ACE);
		int nKings1 = m_pPlayer[SOUTH]->GetNumCardsOf(KING);
		double fHC2 = m_pPlayer[NORTH]->GetHCPoints();
		int nAces2 = m_pPlayer[NORTH]->GetNumCardsOf(ACE);
		int nKings2 = m_pPlayer[NORTH]->GetNumCardsOf(KING);
		ASSERT((fDiff1 >= 0) && (fDiff2 >= 0));
		//
		if ((fDiff1 < 2) || (fDiff2 < 2))
			goto shuffle;
	}

	//
	//----------------------------------------------------------
	//
	// slam hand -- check for aces if necessary
	//
	int numAcesRequired;
	int numAcesHeld;
	if (nGameCode == 2) 
	{
		numAcesRequired = theApp.GetValue(tnumAcesForSlam,nSlamCode);
		numAcesHeld = PLAYER(SOUTH).GetNumCardsOf(ACE) + PLAYER(NORTH).GetNumCardsOf(ACE);
		int numCards,nSrcPlayer,nDestPlayer,nSuit1,nSuit2,nDestCard;
		int fDiff = numAcesRequired - numAcesHeld;
		// trade aces with opponents
		if (fDiff > 0) 
		{
			for(i=0;i<fDiff;i++) 
			{
				// first pick a source opponent, semi-randomly
				// 0 or 1; 0 means west, unless west has zero aces
				if ( ((GetRandomValue(1) == 0) &&
					  		(PLAYER(WEST).GetNumCardsOf(ACE) > 0)) ||
					 (PLAYER(EAST).GetNumCardsOf(ACE) == 0) )
					nSrcPlayer = WEST;
				else
					nSrcPlayer = EAST;
				ASSERT(PLAYER(nSrcPlayer).GetNumCardsOf(ACE) != 0);
				// and likewise pick a dest player; 0=South
				int nVal = GetRandomValue(1);
				if ( ((nVal == 0) && (PLAYER(SOUTH).GetNumCardsOf(ACE) < 4)) ||
					 (PLAYER(NORTH).GetNumCardsOf(ACE) == 4) )
					nDestPlayer = SOUTH;
				else
					nDestPlayer = NORTH;
				// now pick a source suit and a dest suit
				nAceLoopCount1 = 0;
				do 
				{
					// search for a source suit with an ace
					nSuit1 = GetRandomValue(3);
					if ((PLAYER(nSrcPlayer).GetNumCardsInSuit(nSuit1) > 0) &&
						(PLAYER(nSrcPlayer).GetCardInSuit(nSuit1,0)->GetFaceValue() == ACE)) {
						break;
					}
					nAceLoopCount1++;
				} 
				while (nAceLoopCount1 < 100);
				if (nAceLoopCount1 >= 100) 
				{
					AfxMessageBox("Failed to meet deal constraints (Ace search stage 1 failure).");
					break;
				}
				//
				nAceLoopCount2 = 0;
				do 
				{
					nSuit2 = GetRandomValue(3);
					// make sure the dest suit has > 1 cards in it,
					// or if it has only one card, that it's not an ace
					if ((PLAYER(nDestPlayer).GetNumCardsInSuit(nSuit2) > 1) ||
					    ((PLAYER(nDestPlayer).GetNumCardsInSuit(nSuit2) == 1) &&
						 (PLAYER(nDestPlayer).GetCardInSuit(nSuit2,0)->GetFaceValue() != ACE)) ) {
						break;
					}
					nAceLoopCount2++;
				} while (nAceLoopCount2 < 100);
				if (nAceLoopCount2 >= 100) 
				{
					AfxMessageBox("Failed to meet deal constraints (Ace search stage 2 failure).");
					break;
				}
				// and then pick a nonace card from the dest suit
				numCards = PLAYER(nDestPlayer).GetNumCardsInSuit(nSuit2);
				do 
				{
					nDestCard = GetRandomValue(numCards-1);
				} while (PLAYER(nDestPlayer).GetCardInSuit(nSuit2,nDestCard)->GetFaceValue() == ACE);
				// and finally, then swap cards
				SwapPlayersCards(nSrcPlayer,nDestPlayer, nSuit1, nSuit2, 0, nDestCard, TRUE);
			}
		}		
	}

	//
	//----------------------------------------------------------
	//
	// likewise, check for kings if necessary
	//
	int numKingsRequired;
	int numKingsHeld;
	if (nGameCode == 2) 
	{
		numKingsRequired = theApp.GetValue(tnumKingsForSlam,nSlamCode);
		numKingsHeld = PLAYER(SOUTH).GetNumCardsOf(KING) + PLAYER(NORTH).GetNumCardsOf(KING);
		int numCards,nSrcPlayer,nDestPlayer,nSuit1,nSuit2,nDestCard,nSrcCard;
		int fDiff = numKingsRequired - numKingsHeld;

		// trade kings with opponents
		if (fDiff > 0) 
		{
			for(i=0;i<fDiff;i++) 
			{
				// first pick a source opponent, semi-randomly
				// 0 or 1; 0 means west, unless west has zero kings
				if ( ((GetRandomValue(1) == 0) &&
					  		(PLAYER(WEST).GetNumCardsOf(KING) > 0)) ||
					 (PLAYER(EAST).GetNumCardsOf(KING) == 0) )
					nSrcPlayer = WEST;
				else
					nSrcPlayer = EAST;
				// and likewise pick a dest player; 0=South
				if ( ((GetRandomValue(1) == 0) &&
					  		(PLAYER(SOUTH).GetNumCardsOf(KING) < 4)) ||
					 (PLAYER(NORTH).GetNumCardsOf(KING) == 4) )
					nDestPlayer = SOUTH;
				else
					nDestPlayer = NORTH;
				// now pick a source suit and a dest suit
				nKingLoopCount1 = 0;
				do 
				{
					// search for a source suit with a king
					nSuit1 = GetRandomValue(3);
					if ((PLAYER(nSrcPlayer).GetNumCardsInSuit(nSuit1) >= 1) &&
 						(PLAYER(nSrcPlayer).GetCardInSuit(nSuit1,0)->GetFaceValue() == KING)) 
					{
						nSrcCard = 0;
						break;
					}
					if ((PLAYER(nSrcPlayer).GetNumCardsInSuit(nSuit1) >= 2) &&
					    (PLAYER(nSrcPlayer).GetCardInSuit(nSuit1,1)->GetFaceValue() == KING)) 
					{
						nSrcCard = 1;
						break;
					}
					nKingLoopCount1++;
				} 
				while (nKingLoopCount1 < 100);
				if (nKingLoopCount1 >= 100) 
				{
					AfxMessageBox("Failed to meet deal constraints (King search stage 1 failure).");
					break;
				}
				//
				nKingLoopCount2 = 0;
				do 
				{
					nSuit2 = GetRandomValue(3);
					// make sure the dest suit has > 1 cards in it, including a 
					// card lower than a king which can be swapped out 
					int nNum = PLAYER(nDestPlayer).GetNumCardsInSuit(nSuit2);
					if ((nNum >= 1) &&
						(PLAYER(nDestPlayer).GetCardInSuit(nSuit2,nNum-1)->GetFaceValue() < KING)) {
						break;
					}
					nKingLoopCount2++;
				} while (nKingLoopCount2 < 100);
				if (nKingLoopCount2 >= 100) 
				{
					AfxMessageBox("Failed to meet deal constraints (King search stage 2 failure).");
					break;
				}
				// and then pick a non-king, non-ace card from the dest suit
				numCards = PLAYER(nDestPlayer).GetNumCardsInSuit(nSuit2);
				do 
				{
					nDestCard = GetRandomValue(numCards-1);
				} while ((PLAYER(nDestPlayer).GetCardInSuit(nSuit2,nDestCard)->GetFaceValue() == KING) ||
						 (PLAYER(nDestPlayer).GetCardInSuit(nSuit2,nDestCard)->GetFaceValue() == ACE));
				// and finally, then swap cards
				SwapPlayersCards(nSrcPlayer,nDestPlayer,nSuit1,nSuit2,nSrcCard,nDestCard,TRUE);
			}
		}	
	}

	//
	//----------------------------------------------------------
	//
	// now, adjust hand points if necessary
	// note that we must maintain card topping requirements
	//
	fDiff = fTotalPoints - fScoreTarget;
//	srand((unsigned)time(NULL));
	BOOL bSouthHoldsExtraHonors,bNorthHoldsExtraHonors;
	nPointSwapLoopCount = 0;
	nFailCount = 0;
	//
	while (fDiff != 0) 
	{
		// check some hand parameters to ensure success of swap routine
		// see if N/S have high cards available to swap down
		int nSouthAces = m_pPlayer[SOUTH]->GetNumCardsOf(ACE);
		int nSouthKings = m_pPlayer[SOUTH]->GetNumCardsOf(KING);
		if ((m_pPlayer[SOUTH]->GetHCPoints() > nSouthAces*4 + nSouthKings*3) ||
			((nSouthAces > 0) && (numAcesHeld > numAcesRequired)) ||
			((nSouthKings > 0) && (numKingsHeld > numKingsRequired))	)
			bSouthHoldsExtraHonors = TRUE;
		else
			bSouthHoldsExtraHonors = FALSE;
		int nNorthAces = m_pPlayer[NORTH]->GetNumCardsOf(ACE);
		int nNorthKings = m_pPlayer[NORTH]->GetNumCardsOf(KING);
		if ((m_pPlayer[NORTH]->GetHCPoints() > nNorthAces*4 + nNorthKings*3) ||
			((nNorthAces > 0) && (numAcesHeld > numAcesRequired)) ||
			((nNorthKings > 0) && (numKingsHeld > numKingsRequired)) )
			bNorthHoldsExtraHonors = TRUE;
		else
			bNorthHoldsExtraHonors = FALSE;
		//
 		nDest = (GetRandomValue(1)==0)? EAST: WEST;
		if (fDiff < 0) 
		{
			// adjust hand upwards
			if ((theApp.GetValue(tbBalanceTeamHands)) &&
				((fSouthPoints >= 13) || (fNorthPoints >= 13)) ) 
			{
				if (fSouthPoints < fNorthPoints)
					nSource = SOUTH;
				else
					nSource = NORTH;
			} 
			else 
			{
				nSource = (GetRandomValue(1)==0)? NORTH: SOUTH;
			}
			fSwapped = SwapPoints(nSource, nDest, Abs(fDiff), nGameCode, nSuitCode, nSlamCode);
		} 
		else 
		{
			// adjust hand down
			if ((numAcesHeld <= numAcesRequired) &&
				(numKingsHeld <= numKingsRequired) &&
				(!bSouthHoldsExtraHonors) && (!bNorthHoldsExtraHonors)) 
			{
				// neither hand has a high card to trade down while
				// meeting Aces/Kings requirement, just give up
				break;
			}
			// else proceed
			if ((theApp.GetValue(tbBalanceTeamHands))  &&
				((fSouthPoints >= 13) || (fNorthPoints >= 13)) ) 
			{
				// deduct points from hand with the most points, unless that hand
				// lacks honors below a king (which must be held)
				if ( ((fSouthPoints > fNorthPoints) && (bSouthHoldsExtraHonors)) ||
					 ((bSouthHoldsExtraHonors) && (!bNorthHoldsExtraHonors)) )
					nSource = SOUTH;
				else
					nSource = NORTH;
			} 
			else 
			{
				nSource = (GetRandomValue(1)==0)? NORTH: SOUTH;
			}
			fSwapped = SwapPoints(nDest, nSource, Abs(fDiff), nGameCode, nSuitCode, nSlamCode);
		}
		//
		if (fSwapped == 0) 
		{
			nFailCount++;
			if (nFailCount > 40)
				break;	// could've run out of high cards
		}
		// and re-evaluate
		PLAYER(SOUTH).CountCardPoints(TRUE);
		PLAYER(NORTH).CountCardPoints(TRUE);
		if (nSuitCode != 3) 
		{
			fSouthPoints = PLAYER(SOUTH).GetTotalPoints();
			fNorthPoints = PLAYER(NORTH).GetTotalPoints();
		} 
		else 
		{
			// No Trumps; count high card points only
			fSouthPoints = PLAYER(SOUTH).GetHCPoints();
			fNorthPoints = PLAYER(NORTH).GetHCPoints();
		}
		fTotalPoints = fSouthPoints + fNorthPoints;
		fDiff = fTotalPoints - fScoreTarget;
		nPointSwapLoopCount++;
	}

	//
	//----------------------------------------------------------------
	// now report on success of the special deal
	//
	CString strTemp;
/*
	strTemp.Format("Iterations: O=%d, A1=%d, A2=%d, K1=%d, K2=%d, PS=%d, FL=%d\n",
							nOuterLoopCount,nAceLoopCount1,nAceLoopCount2,
							nKingLoopCount1, nKingLoopCount2,
							nPointSwapLoopCount,nFailCount);
	strFeedback += strTemp;
*/

	for(i=0;i<4;i++)
		PLAYER(i).CountCardPoints(TRUE);
	//
	strTemp.Format("S: %d/%d pts;  N: %d/%d pts (Total: %d/%d/%d)\nEast: %d/%d pts;  West: %d/%d pts (Total E/W: %d)",
					PLAYER(SOUTH).GetHCPoints(),
					PLAYER(SOUTH).GetTotalPoints(),
					PLAYER(NORTH).GetHCPoints(),
					PLAYER(NORTH).GetTotalPoints(),
					PLAYER(SOUTH).GetHCPoints() + PLAYER(NORTH).GetHCPoints(),
					fTotalPoints,fScoreTarget,
					PLAYER(EAST).GetHCPoints(),
					PLAYER(EAST).GetTotalPoints(),
					PLAYER(WEST).GetHCPoints(),
					PLAYER(WEST).GetTotalPoints(),
					PLAYER(EAST).GetTotalPoints() + PLAYER(WEST).GetTotalPoints());
	strFeedback += strTemp;
	strTemp.Format("\nQT's: N: %3.1f S: %3.1f;   Stoppers: N: %d S: %d",
					PLAYER(NORTH).GetNumQuickTricks(),
					PLAYER(SOUTH).GetNumQuickTricks(),
					PLAYER(NORTH).GetNumSuitsStopped(),
					PLAYER(SOUTH).GetNumSuitsStopped());
	strFeedback += strTemp;
	if (nGameCode == 2) 
	{
		int numAcesRequired = theApp.GetValue(tnumAcesForSlam,nSlamCode);
		int numAcesHeld = PLAYER(SOUTH).GetNumCardsOf(ACE) + PLAYER(NORTH).GetNumCardsOf(ACE);
		int numKingsRequired = theApp.GetValue(tnumKingsForSlam,nSlamCode);
		int numKingsHeld = PLAYER(SOUTH).GetNumCardsOf(KING) + PLAYER(NORTH).GetNumCardsOf(KING);
		strTemp.Format("\nAces, Kings held by team = %d/%d, %d/%d",
						numAcesHeld,numAcesRequired,
						numKingsHeld,numKingsRequired);
		strFeedback += strTemp;
	}
	FEEDBACK(strFeedback);

	// swap hands if desired
	if (nTeam == EAST_WEST)
		RotatePlayersHands(0, FALSE, FALSE);

	// copy hands to the initial hands
	for(i=0;i<4;i++)
		PLAYER(i).InitializeHand();

	// turn off game auto-play
	if ((theApp.GetValue(tnCardPlayMode) == CEasyBApp::PLAY_FULL_AUTO) || (theApp.GetValue(tnCardPlayMode) == CEasyBApp::PLAY_FULL_AUTO_EXPRESS))
		theApp.SetValue(tnCardPlayMode, CEasyBApp::PLAY_NORMAL);

	// done dealing
	CMainFrame::ResetStatusMessage();
	
	// mark that the deal # is available
	m_bDealNumberAvailable = TRUE;

	// reset view mode
	pVIEW->ClearMode();

	// and begin play
	InitPlay();
}
Beispiel #23
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 1280;
    int screenHeight = 960;

    InitWindow(screenWidth, screenHeight, "raylib example - Bunnymark");

    Texture2D texBunny = LoadTexture("resources/wabbit_alpha.png");

    Bunny *bunnies = (Bunny *)malloc(MAX_BUNNIES*sizeof(Bunny));          // Bunnies array

    int bunniesCount = 0;    // Bunnies counter

    SetTargetFPS(60);
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        if (IsMouseButtonDown(MOUSE_LEFT_BUTTON))
        {
            // Create more bunnies
            for (int i = 0; i < 100; i++)
            {
                bunnies[bunniesCount].position = GetMousePosition();
                bunnies[bunniesCount].speed.x = (float)GetRandomValue(250, 500)/60.0f;
                bunnies[bunniesCount].speed.y = (float)(GetRandomValue(250, 500) - 500)/60.0f;
                bunniesCount++;
            }
        }

        // Update bunnies
        for (int i = 0; i < bunniesCount; i++)
        {
            bunnies[i].position.x += bunnies[i].speed.x;
            bunnies[i].position.y += bunnies[i].speed.y;

            if ((bunnies[i].position.x > GetScreenWidth()) || (bunnies[i].position.x < 0)) bunnies[i].speed.x *= -1;
            if ((bunnies[i].position.y > GetScreenHeight()) || (bunnies[i].position.y < 0)) bunnies[i].speed.y *= -1;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            for (int i = 0; i < bunniesCount; i++)
            {
                // NOTE: When internal QUADS batch limit is reached, a draw call is launched and
                // batching buffer starts being filled again; before launching the draw call,
                // updated vertex data from internal buffer is send to GPU... it seems it generates
                // a stall and consequently a frame drop, limiting number of bunnies drawn at 60 fps
                DrawTexture(texBunny, bunnies[i].position.x, bunnies[i].position.y, RAYWHITE);
            }

            DrawRectangle(0, 0, screenWidth, 40, LIGHTGRAY);
            DrawText("raylib bunnymark", 10, 10, 20, DARKGRAY);
            DrawText(FormatText("bunnies: %i", bunniesCount), 400, 10, 20, RED);
            DrawFPS(260, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    free(bunnies);

    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #24
0
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values");

    int score = 0;
    int hiscore = 0;
    int framesCounter = 0;

    SetTargetFPS(60);               // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        if (IsKeyPressed(KEY_R))
        {
            score = GetRandomValue(1000, 2000);
            hiscore = GetRandomValue(2000, 4000);
        }

        if (IsKeyPressed(KEY_ENTER))
        {
            StorageSaveValue(STORAGE_SCORE, score);
            StorageSaveValue(STORAGE_HISCORE, hiscore);
        }
        else if (IsKeyPressed(KEY_SPACE))
        {
            // NOTE: If requested position could not be found, value 0 is returned
            score = StorageLoadValue(STORAGE_SCORE);
            hiscore = StorageLoadValue(STORAGE_HISCORE);
        }

        framesCounter++;
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            DrawText(FormatText("SCORE: %i", score), 280, 130, 40, MAROON);
            DrawText(FormatText("HI-SCORE: %i", hiscore), 210, 200, 50, BLACK);

            DrawText(FormatText("frames: %i", framesCounter), 10, 10, 20, LIME);

            DrawText("Press R to generate random numbers", 220, 40, 20, LIGHTGRAY);
            DrawText("Press ENTER to SAVE values", 250, 310, 20, LIGHTGRAY);
            DrawText("Press SPACE to LOAD values", 252, 350, 20, LIGHTGRAY);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #25
0
//----------------------------------------------------------------------------------
// Main entry point
//----------------------------------------------------------------------------------
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const char windowTitle[30] = "raylib functionality demo";
   
    //SetupFlags(FLAG_FULLSCREEN_MODE);
    InitWindow(screenWidth, screenHeight, windowTitle);
    
    InitAudioDevice();             // Initialize audio device

    // TITLE screen variables Initialization
    fontAlagard = LoadSpriteFont("resources/fonts/alagard.rbmf");        // rBMF font loading
    fontPixelplay = LoadSpriteFont("resources/fonts/pixelplay.rbmf");    // rBMF font loading
    fontMecha = LoadSpriteFont("resources/fonts/mecha.rbmf");            // rBMF font loading
    fontSetback = LoadSpriteFont("resources/fonts/setback.rbmf");        // rBMF font loading
    fontRomulus = LoadSpriteFont("resources/fonts/romulus.rbmf");        // rBMF font loading
    
    pongBallPosition = (Vector2){ screenWidth/2, screenHeight/2 + 20 };
    pongBallSpeed = (Vector2){ 6, 6 };
    pongPlayerRec = (Rectangle){ 20, screenHeight/2 - 50 + 40, 20, 100 };
    pongEnemyRec = (Rectangle){ screenWidth - 40, screenHeight/2 - 60, 20, 120 };

    // LOGO screen variables Initialization
    logoPositionX = screenWidth/2 - 128;
    logoPositionY = screenHeight/2 - 128;
    
    // MODULES screen variables Initialization
    raylibWindow = LoadTexture("resources/raylib_window.png");
    raylibWindow01 = LoadTexture("resources/raylib_window_01.png");
    raylibWindow02 = LoadTexture("resources/raylib_window_02.png");
    raylibWindow03 = LoadTexture("resources/raylib_window_03.png");
    platforms = LoadTexture("resources/platforms.png");
    raylibLogoB = LoadTexture("resources/raylib_logo128x128.png");
    lena = LoadTexture("resources/lena.png");
    mandrill = LoadTexture("resources/mandrill.png");
    texAlagard = LoadTexture("resources/fonts/custom_alagard.png");
    fontMechaC = LoadSpriteFont("resources/fonts/custom_mecha.png");
    fontAlagardC = LoadSpriteFont("resources/fonts/custom_alagard.png");
    fontJupiterC = LoadSpriteFont("resources/fonts/custom_jupiter_crash.png");
    
    ballPosition = (Vector2){ 520 + 656/2, 220 + 399/2 };
    
    camera = (Camera){{ 0.0, 12.0, 15.0 }, { 0.0, 3.0, 0.0 }, { 0.0, 1.0, 0.0 }};

    catTexture = LoadTexture("resources/catsham.png");   // Load model texture
    cat = LoadModel("resources/cat.obj");                 // Load OBJ model
    SetModelTexture(&cat, catTexture);
    
    fxWav = LoadSound("resources/audio/weird.wav");         // Load WAV audio file
    fxOgg = LoadSound("resources/audio/tanatana.ogg");      // Load OGG audio file
    
    for (int i = 0; i < MAX_BALLS; i++)
    {
        soundBallsPosition[i] = (Vector2){ 650 + 560/2 + GetRandomValue(-280, 280), 220 + 200 + GetRandomValue(-200, 200) };
        soundBallsColor[i] = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
        soundBallsRadius[i] = GetRandomValue(2, 50);
        soundBallsAlpha[i] = 1.0f;
        
        soundBallsActive[i] = false;
    }
    
    // ENDING screen variables Initialization
    raylibLogoA = LoadTexture("resources/raylib_logo.png");

#ifndef PLATFORM_WEB
    SetTargetFPS(60);
#endif

#if defined(PLATFORM_WEB)
    emscripten_set_main_loop(UpdateDrawOneFrame, 0, 1);
#else
    //--------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose() && !closeWindow)    // Detect window close button or ESC key
    {
        UpdateDrawOneFrame();
    }
#endif

    // De-Initialization
    //--------------------------------------------------------------------------------------

    // Unload all loaded data (textures, fonts, audio)
    UnloadSpriteFont(fontAlagard);      // SpriteFont unloading
    UnloadSpriteFont(fontPixelplay);    // SpriteFont unloading
    UnloadSpriteFont(fontMecha);        // SpriteFont unloading
    UnloadSpriteFont(fontSetback);      // SpriteFont unloading
    UnloadSpriteFont(fontRomulus);      // SpriteFont unloading

    UnloadTexture(raylibWindow);
    UnloadTexture(raylibWindow01);
    UnloadTexture(raylibWindow02);
    UnloadTexture(raylibWindow03);
    UnloadTexture(platforms);
    UnloadTexture(raylibLogoA);
    UnloadTexture(raylibLogoB);
    UnloadTexture(lena);
    UnloadTexture(mandrill);
    UnloadTexture(texAlagard);

    UnloadSpriteFont(fontMechaC);
    UnloadSpriteFont(fontAlagardC);
    UnloadSpriteFont(fontJupiterC);

    UnloadTexture(catTexture);
    UnloadModel(cat);

    UnloadSound(fxWav);
    UnloadSound(fxOgg);

    CloseAudioDevice();
    
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #26
0
void UpdateDrawOneFrame(void)
{
    // Update
    //----------------------------------------------------------------------------------
    if (!onTransition)
    {
        switch(currentScreen) 
        {
            case LOADING: 
            {
                // Update LOADING screen variables
                framesCounter++;    // Count frames

                if ((loadBarWidth < loadBarMaxWidth) && ((framesCounter%30) == 0)) loadBarWidth++;

                if (IsKeyDown(KEY_SPACE) && (loadBarWidth < loadBarMaxWidth)) loadBarWidth += 4;

                if (IsKeyPressed(KEY_ENTER) && (loadBarWidth >= loadBarMaxWidth)) TransitionToScreen(LOGO);

            } break;
            case LOGO:
            {
                // Update LOGO screen variables
                if (logoScreenState == 0)                 // State 0: Small box blinking
                {
                    framesCounter++;

                    if (framesCounter == 120)
                    {
                        logoScreenState = 1;
                        framesCounter = 0;      // Reset counter... will be used later...
                    }
                }
                else if (logoScreenState == 1)            // State 1: Top and left bars growing
                {
                    topSideRecWidth += 4;
                    leftSideRecHeight += 4;

                    if (topSideRecWidth == 256) logoScreenState = 2;
                }
                else if (logoScreenState == 2)            // State 2: Bottom and right bars growing
                {
                    bottomSideRecWidth += 4;
                    rightSideRecHeight += 4;

                    if (bottomSideRecWidth == 256)
                    {
                        lettersCounter = 0;
                        for (int i = 0; i < strlen(msgBuffer); i++) msgBuffer[i] = ' ';

                        logoScreenState = 3;
                    }
                }
                else if (logoScreenState == 3)            // State 3: Letters appearing (one by one)
                {
                    framesCounter++;

                    // Every 12 frames, one more letter!
                    if ((framesCounter%12) == 0) raylibLettersCount++;

                    switch (raylibLettersCount)
                    {
                        case 1: raylib[0] = 'r'; break;
                        case 2: raylib[1] = 'a'; break;
                        case 3: raylib[2] = 'y'; break;
                        case 4: raylib[3] = 'l'; break;
                        case 5: raylib[4] = 'i'; break;
                        case 6: raylib[5] = 'b'; break;
                        default: break;
                    }

                    if (raylibLettersCount >= 10)
                    {
                        // Write raylib description messages
                        if ((framesCounter%2) == 0) lettersCounter++;

                        if (!msgLogoADone)
                        {
                            if (lettersCounter <= strlen(msgLogoA)) strncpy(msgBuffer, msgLogoA, lettersCounter);
                            else
                            {
                                for (int i = 0; i < strlen(msgBuffer); i++) msgBuffer[i] = ' ';

                                lettersCounter = 0;
                                msgLogoADone = true;
                            }
                        }
                        else if (!msgLogoBDone)
                        {
                            if (lettersCounter <= strlen(msgLogoB)) strncpy(msgBuffer, msgLogoB, lettersCounter);
                            else
                            {
                                msgLogoBDone = true;
                                framesCounter = 0;
                            }
                        }
                    }
                }

                // Press enter to change to MODULES screen
                if (IsKeyPressed(KEY_ENTER) && msgLogoBDone) TransitionToScreen(MODULES);
                else if (IsKeyPressed(KEY_BACKSPACE)) TransitionToScreen(LOGO);

            } break;
            case MODULES:
            {
                // Update MODULES screen variables here!
                framesCounter++;

                if (IsKeyPressed(KEY_RIGHT) && (selectedModule < 5))
                {
                    selectedModule++;
                    framesCounter = 0;
                }
                else if (IsKeyPressed(KEY_LEFT) && (selectedModule > 0))
                {
                    selectedModule--;
                    framesCounter = 0;
                }

                if (selectedModule == CORE)
                {
                    if ((framesCounter > 60) && (windowOffset < 40))
                    {
                        windowOffset++;
                        ballPosition.x++;
                        ballPosition.y++;
                    }

                    if (framesCounter > 140)
                    {
                        if (IsKeyDown('A')) ballPosition.x -= 5;
                        if (IsKeyDown('D')) ballPosition.x += 5;
                        if (IsKeyDown('W')) ballPosition.y -= 5;
                        if (IsKeyDown('S')) ballPosition.y += 5;

                        if (IsKeyPressed('1')) coreWindow = 1;
                        if (IsKeyPressed('2')) coreWindow = 2;
                        if (IsKeyPressed('3')) coreWindow = 3;
                        if (IsKeyPressed('4')) coreWindow = 4;
                    }
                }

                if (selectedModule == TEXTURES) scaleFactor = (sinf(2*PI/240*framesCounter) + 1.0f)/2;

                if (selectedModule == AUDIO)
                {
                    if (IsKeyPressed(KEY_SPACE) && !MusicIsPlaying()) PlayMusicStream("resources/audio/guitar_noodling.ogg");         // Play music stream

                    if (IsKeyPressed('S'))
                    {
                        StopMusicStream();
                        timePlayed = 0.0f;

                        for (int i = 0; i < MAX_BALLS; i++)
                        {
                            soundBallsPosition[i] = (Vector2){ 650 + 560/2 + GetRandomValue(-280, 280), 220 + 200 + GetRandomValue(-200, 200) };
                            soundBallsColor[i] = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
                            soundBallsRadius[i] = GetRandomValue(2, 50);
                            soundBallsAlpha[i] = 1.0f;

                            soundBallsActive[i] = false;
                        }
                    }

                    if (MusicIsPlaying())
                    {
                        timePlayed = GetMusicTimePlayed() / GetMusicTimeLength() * 100 * 4;

                        if ((framesCounter%10) == 0)
                        {
                            for (int i = 0; i < MAX_BALLS; i++)
                            {
                                if (!soundBallsActive[i])
                                {
                                    soundBallsActive[i] = true;
                                    break;
                                }
                            }
                        }

                        for (int i = 0; i < MAX_BALLS; i++)
                        {
                            if (soundBallsActive[i]) soundBallsAlpha[i] -= 0.005f;

                            if (soundBallsAlpha[i] <= 0)
                            {
                                soundBallsActive[i] = false;

                                // Reset ball random
                                soundBallsPosition[i] = (Vector2){ 650 + 560/2 + GetRandomValue(-280, 280), 220 + 200 + GetRandomValue(-200, 200) };
                                soundBallsColor[i] = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
                                soundBallsRadius[i] = GetRandomValue(2, 60);
                                soundBallsAlpha[i] = 1.0f;
                            }
                        }
                    }

                    if (IsKeyPressed('N')) PlaySound(fxWav);
                    //if (IsKeyPressed('M')) PlaySound(fxOgg);
                }

                // Press enter to change to ENDING screen
                if (IsKeyPressed(KEY_ENTER)) TransitionToScreen(ENDING);
                else if (IsKeyPressed(KEY_BACKSPACE)) TransitionToScreen(LOGO);

            } break;
            case PONG:
            {
                // Update SECRET screen variables here!
                framesCounter++;

                if (IsKeyPressed('P')) pongPaused = !pongPaused;
                
                if (!pongPaused)
                {
                    pongBallPosition.x += pongBallSpeed.x;
                    pongBallPosition.y += pongBallSpeed.y;

                    if ((pongBallPosition.x >= screenWidth - 5) || (pongBallPosition.x <= 5)) pongBallSpeed.x *= -1;
                    if ((pongBallPosition.y >= screenHeight - 5) || (pongBallPosition.y <= 5)) pongBallSpeed.y *= -1;

                    if (IsKeyDown(KEY_UP) || IsKeyDown('W'))
                    {
                        pongPlayerRec.y -= 5;
                        pongAutoMode = false;
                        pongAutoCounter = 180;
                    }
                    else if (IsKeyDown(KEY_DOWN) || IsKeyDown('S'))
                    {
                        pongPlayerRec.y += 5;
                        pongAutoMode = false;
                        pongAutoCounter = 180;
                    }
                    else if (pongAutoCounter > 0)
                    {
                        pongAutoCounter--;
                        
                        if (pongAutoCounter == 0) pongAutoMode = true;
                    }

                    if ((pongBallPosition.x < 600) && pongAutoMode)
                    {
                        if (pongBallPosition.y > (pongPlayerRec.y + pongPlayerRec.height/2)) pongPlayerRec.y += 5;
                        else if (pongBallPosition.y < (pongPlayerRec.y + pongPlayerRec.height/2)) pongPlayerRec.y -= 5;
                    }

                    if (pongPlayerRec.y <= 0) pongPlayerRec.y = 0;
                    else if ((pongPlayerRec.y + pongPlayerRec.height) >= screenHeight) pongPlayerRec.y = screenHeight - pongPlayerRec.height;
                    
                    if (pongBallPosition.x > screenWidth - 600)
                    {
                        if (pongBallPosition.y > (pongEnemyRec.y + pongEnemyRec.height/2)) pongEnemyRec.y += 5;
                        else if (pongBallPosition.y < (pongEnemyRec.y + pongEnemyRec.height/2)) pongEnemyRec.y -= 5;

                        if (pongEnemyRec.y <= 0) pongEnemyRec.y = 0;
                        else if ((pongEnemyRec.y + pongEnemyRec.height) >= screenHeight) pongEnemyRec.y = screenHeight - pongEnemyRec.height;
                    }

                    if ((CheckCollisionCircleRec(pongBallPosition, 10, pongPlayerRec)) || (CheckCollisionCircleRec(pongBallPosition, 10, pongEnemyRec))) pongBallSpeed.x *= -1;
                    
                    if (pongBallPosition.x >= screenWidth - 5) pongScorePlayer++;
                    else if (pongBallPosition.x <= 5) pongScoreEnemy++;
                }

                // Press enter to move back to MODULES screen
                if (IsKeyPressed(KEY_ENTER)) TransitionToScreen(ENDING);
                if (IsKeyPressed(KEY_BACKSPACE)) TransitionToScreen(ENDING);
            } break;
            case ENDING:
            {
                // Update ENDING screen
                framesCounter++;

                // Press enter to move back to MODULES screen
                if (IsKeyPressed(KEY_ENTER)) TransitionToScreen(PONG);
                if (IsKeyPressed(KEY_BACKSPACE)) TransitionToScreen(MODULES);

            } break;
            default: break;
        }

        if ((currentScreen != LOADING) && (timeCounter < totalTime)) timeCounter++;
    }
    else UpdateTransition(); // Update transition (fade-in, fade-out)
    //----------------------------------------------------------------------------------

    // Draw
    //----------------------------------------------------------------------------------
    BeginDrawing();

        ClearBackground(RAYWHITE);

        switch(currentScreen)
        {
            case LOADING:
            {
                // Draw LOADING screen
                if ((loadBarWidth < loadBarMaxWidth) && ((framesCounter/40)%2)) DrawText(msgLoading, 360, 240, 40, DARKGRAY);

                DrawRectangle(360 - 4, 300 - 4, loadBarMaxWidth + 8, 60 + 8, LIGHTGRAY);
                DrawRectangle(360, 300, loadBarWidth - 1, 60, DARKGRAY);
                DrawRectangleLines(360 - 4, 300 - 5, loadBarMaxWidth + 8, 60 + 8, DARKGRAY);

                if (loadBarWidth >= loadBarMaxWidth)
                {
                    //DrawText(msgLoading, 360, 240, 40, DARKGRAY);
                    if ((framesCounter/30)%2) DrawText(msgPressEnter, screenWidth/2 - MeasureText(msgPressEnter, 40)/2 + 20, 400, 40, DARKGRAY);
                }
                else DrawText("PRESS SPACE to ACCELERATE LOADING! ;)", screenWidth/2 - 200, 400, 20, LIGHTGRAY);

            } break;
            case LOGO:
            {
                // Draw LOGO screen
                if (logoScreenState == 0)
                {
                    if ((framesCounter/15)%2) DrawRectangle(logoPositionX, logoPositionY - 60, 16, 16, BLACK);
                }
                else if (logoScreenState == 1)
                {
                    DrawRectangle(logoPositionX, logoPositionY - 60, topSideRecWidth, 16, BLACK);
                    DrawRectangle(logoPositionX, logoPositionY - 60, 16, leftSideRecHeight, BLACK);
                }
                else if (logoScreenState == 2)
                {
                    DrawRectangle(logoPositionX, logoPositionY - 60, topSideRecWidth, 16, BLACK);
                    DrawRectangle(logoPositionX, logoPositionY - 60, 16, leftSideRecHeight, BLACK);

                    DrawRectangle(logoPositionX + 240, logoPositionY - 60, 16, rightSideRecHeight, BLACK);
                    DrawRectangle(logoPositionX, logoPositionY + 240 - 60, bottomSideRecWidth, 16, BLACK);
                }
                else if (logoScreenState == 3)
                {
                    DrawRectangle(logoPositionX, logoPositionY - 60, topSideRecWidth, 16, BLACK);
                    DrawRectangle(logoPositionX, logoPositionY + 16 - 60, 16, leftSideRecHeight - 32, BLACK);

                    DrawRectangle(logoPositionX + 240, logoPositionY + 16 - 60, 16, rightSideRecHeight - 32, BLACK);
                    DrawRectangle(logoPositionX, logoPositionY + 240 - 60, bottomSideRecWidth, 16, BLACK);

                    DrawRectangle(screenWidth/2 - 112, screenHeight/2 - 112 - 60, 224, 224, RAYWHITE);

                    DrawText(raylib, screenWidth/2 - 44, screenHeight/2 + 48 - 60, 50, BLACK);

                    if (!msgLogoADone) DrawText(msgBuffer, screenWidth/2 - MeasureText(msgLogoA, 30)/2, 460, 30, GRAY);
                    else
                    {
                        DrawText(msgLogoA, screenWidth/2 - MeasureText(msgLogoA, 30)/2, 460, 30, GRAY);

                        if (!msgLogoBDone) DrawText(msgBuffer, screenWidth/2 - MeasureText(msgLogoB, 30)/2, 510, 30, GRAY);
                        else
                        {
                            DrawText(msgLogoB, screenWidth/2 - MeasureText(msgLogoA, 30)/2, 510, 30, GRAY);

                            if ((framesCounter > 90) && ((framesCounter/30)%2)) DrawText("PRESS ENTER to CONTINUE", 930, 650, 20, GRAY);
                        }
                    }
                }
            } break;
            case MODULES:
            {
                // Draw MODULES screen
                DrawTexture(raylibLogoB, 40, 40, WHITE);
                DrawText("raylib is composed of 6 main modules:", 128 + 40 + 30, 50, 20, GRAY);

                if (framesCounter < 120)
                {
                    if (((framesCounter/30)%2) == 0) DrawRectangle(128 + 40 + 30 - 4 + 175*selectedModule, 128 + 40 - 70 - 8 - 4, 158, 78, RED);
                }
                else DrawRectangle(128 + 40 + 30 - 4 + 175*selectedModule, 128 + 40 - 70 - 8 - 4, 158, 78, RED);
                
                if (selectedModule != AUDIO)
                {
                    DrawTriangle((Vector2){950 - 40, 685 - 10}, (Vector2){950 - 60, 685}, (Vector2){950 - 40, 685 + 10}, GRAY);
                    DrawTriangle((Vector2){950 - 30, 685 - 10}, (Vector2){950 - 30, 685 + 10}, (Vector2){950 - 10, 685}, GRAY);
                    DrawText("PRESS RIGHT or LEFT to EXPLORE MODULES", 960, 680, 10, GRAY);
                }

                switch (selectedModule)
                {
                    case CORE:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0x5c5a5aff));
                    
                        DrawTextEx(fontRomulus, "Open-Close Window", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x5c5a5aff));
                        DrawTextEx(fontRomulus, "Manage Drawing Area", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x5c5a5aff));
                        DrawTextEx(fontRomulus, "Manage Inputs", (Vector2){ 48, 290 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x5c5a5aff));
                        DrawTextEx(fontRomulus, "Manage Timming", (Vector2){ 48, 320 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x5c5a5aff));
                        DrawTextEx(fontRomulus, "Auxiliar Functions", (Vector2){ 48, 350 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x5c5a5aff));

                        switch (coreWindow)
                        {
                            case 1: DrawTexture(raylibWindow, 520, 220, WHITE); break;
                            case 2: DrawTextureEx(raylibWindow01, (Vector2){ 450, 220 - 45 }, 0.0f, 4.0f, WHITE); break;
                            case 3: DrawTextureEx(raylibWindow02, (Vector2){ 430, 220 - 40 }, 0.0f, 4.0f, WHITE); break;
                            case 4: DrawTextureEx(raylibWindow03, (Vector2){ 470, 220 - 65 }, 0.0f, 4.0f, WHITE); break;
                            default: DrawTexture(raylibWindow, 520, 220, WHITE); break;
                        }
                        
                        if (framesCounter > 140) DrawText("Check the possible windows raylib can run on. PRESS KEY: 1, 2, 3 or 4", 520 + 8 + windowOffset + 160, 220 + windowOffset + 10, 10, LIGHTGRAY);                        
                        
                        DrawText("Compile raylib C code for the folowing platforms:", 48, 400, 10, MAROON);
                        
                        DrawTextureRec(platforms, (Rectangle){ 0, 0, platforms.width, platforms.height}, (Vector2){ 75, 420 }, WHITE);

                        DrawRectangle(520 + 8 + windowOffset, 220 + 31 + windowOffset, 640, 360, RAYWHITE);
                        DrawRectangleLines(520 + 8 + windowOffset - 1, 220 + 31 + windowOffset - 2, 640 + 2, 360 + 2, GRAY);
                        DrawFPS(520 + 8 + windowOffset + 10, 220 + 31 + windowOffset + 10);
                        
                        DrawRectangle(ballPosition.x - 50, ballPosition.y - 50, 100, 100, Fade(MAROON, 0.5f));
                        DrawRectangleRec(GetCollisionRec((Rectangle){ 520 + 8 + windowOffset - 1, 220 + 31 + windowOffset - 1, 640 + 2, 360 + 2 }, (Rectangle){ (int)ballPosition.x - 50, (int)ballPosition.y - 50, 100, 100 }), MAROON);
                        
                        if (framesCounter > 140)
                        {
                            DrawTextEx(fontMecha, "MOVE ME", (Vector2){ ballPosition.x - 26, ballPosition.y - 20 }, GetFontBaseSize(fontMecha), 2, BLACK);
                            DrawTextEx(fontMecha, "[ W A S D ]", (Vector2){ ballPosition.x - 36, ballPosition.y }, GetFontBaseSize(fontMecha), 2, BLACK);
                        }
                    } break;
                    case SHAPES:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0xcd5757ff));
                    
                        DrawTextEx(fontRomulus, "Draw Basic Shapes", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0xcd5757ff));
                        DrawTextEx(fontRomulus, "Basic Collision Detection", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0xcd5757ff));

                        DrawCircle(screenWidth/4, 120 + 240, 35, DARKBLUE);
                        DrawCircleGradient(screenWidth/4, 220 + 240, 60, GREEN, SKYBLUE);
                        DrawCircleLines(screenWidth/4, 340 + 240, 80, DARKBLUE);

                        DrawRectangle(screenWidth/4*2 - 110, 100 + 180, 220, 100, LIME);
                        DrawRectangleGradient(screenWidth/4*2 - 90, 170 + 240, 180, 130, MAROON, GOLD);
                        DrawRectangleLines(screenWidth/4*2 - 80, 320 + 240, 160, 80, ORANGE);

                        DrawTriangle((Vector2){screenWidth/4*3, 60 + 220}, (Vector2){screenWidth/4*3 - 60, 160 + 220}, (Vector2){screenWidth/4*3 + 60, 160 + 220}, VIOLET);

                        DrawTriangleLines((Vector2){screenWidth/4*3, 140 + 220}, (Vector2){screenWidth/4*3 - 60, 210 + 260}, (Vector2){screenWidth/4*3 + 60, 210 + 260}, SKYBLUE);

                        DrawPoly((Vector2){screenWidth/4*3, 320 + 240}, 6, 80, 0, BROWN);

                    } break;
                    case TEXTURES:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0x60815aff));
                    
                        DrawTextEx(fontRomulus, "Load Images and Textures", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x60815aff));
                        DrawTextEx(fontRomulus, "Draw Textures", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x60815aff));

                        DrawRectangle(138, 348, 260, 260, GRAY);
                        DrawTexturePro(lena, (Rectangle){ 0, 0, lena.width, lena.height }, (Rectangle){ 140 + 128, 350 + 128, lena.width/2*scaleFactor, lena.height/2*scaleFactor }, (Vector2){ lena.width/4*scaleFactor, lena.height/4*scaleFactor }, 0.0f, WHITE);

                        DrawTexture(lena, 600, 180, Fade(WHITE, 0.3f));
                        DrawTextureRec(lena, (Rectangle){ 225, 240, 155, 50 }, (Vector2){ 600 + 256 - 82 + 50, 180 + 241 }, PINK);

                        DrawTexturePro(mandrill, (Rectangle){ 0, 0, mandrill.width, mandrill.height }, (Rectangle){ screenWidth/2 - 40, 350 + 128, mandrill.width/2, mandrill.height/2 },
                                        (Vector2){ mandrill.width/4, mandrill.height/4 }, framesCounter, GOLD);

                    } break;
                    case TEXT:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0x377764ff));
                    
                        DrawTextEx(fontRomulus, "Load SpriteFonts", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x377764ff));
                        DrawTextEx(fontRomulus, "Draw Text", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x377764ff));
                        DrawTextEx(fontRomulus, "Text Formatting", (Vector2){ 48, 290 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x377764ff));

                        DrawTexture(texAlagard, 60, 360, WHITE);

                        DrawTextEx(fontMechaC, msg1, (Vector2){ 540 + 168, 210 }, GetFontBaseSize(fontMechaC), -3, WHITE);
                        DrawTextEx(fontAlagardC, msg2, (Vector2){ 460 + 140, 260 }, GetFontBaseSize(fontAlagardC), -2, WHITE);
                        DrawTextEx(fontJupiterC, msg3, (Vector2){ 640 + 70, 300 }, GetFontBaseSize(fontJupiterC), 2, WHITE);

                        DrawTextEx(fontAlagard, "It also includes some...", (Vector2){ 650 + 70, 400 }, GetFontBaseSize(fontAlagard)*2, 2, MAROON);
                        DrawTextEx(fontPixelplay, "...free fonts in rBMF format...", (Vector2){ 705 - 26, 450 }, GetFontBaseSize(fontPixelplay)*2, 4, ORANGE);
                        DrawTextEx(fontMecha, "...to be used even in...", (Vector2){ 700 + 40, 500 }, GetFontBaseSize(fontMecha)*2, 4, DARKGREEN);
                        DrawTextEx(fontSetback, "...comercial projects...", (Vector2){ 710, 550 }, GetFontBaseSize(fontSetback)*2, 4, DARKBLUE);
                        DrawTextEx(fontRomulus, "...completely for free!", (Vector2){ 710 + 17, 600 }, GetFontBaseSize(fontRomulus)*2, 3, DARKPURPLE);
                        
                        DrawText("This is a custom font spritesheet, raylib can load it automatically!", 228, 360 + 295, 10, GRAY);

                    } break;
                    case MODELS:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0x417794ff));
                        
                        DrawTextEx(fontRomulus, "Draw Geometric Models", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x417794ff));
                        DrawTextEx(fontRomulus, "Load 3D Models", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x417794ff));
                        DrawTextEx(fontRomulus, "Draw 3D Models", (Vector2){ 48, 290 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x417794ff));

                        Begin3dMode(camera);

                            DrawCube((Vector3){-4, 0, 2}, 2, 5, 2, RED);
                            DrawCubeWires((Vector3){-4, 0, 2}, 2, 5, 2, GOLD);
                            DrawCubeWires((Vector3){-4, 0, -2}, 3, 6, 2, MAROON);

                            DrawSphere((Vector3){-1, 0, -2}, 1, GREEN);
                            DrawSphereWires((Vector3){1, 0, 2}, 2, 16, 16, LIME);

                            DrawCylinder((Vector3){4, 0, -2}, 1, 2, 3, 4, SKYBLUE);
                            DrawCylinderWires((Vector3){4, 0, -2}, 1, 2, 3, 4, DARKBLUE);
                            DrawCylinderWires((Vector3){4.5, -1, 2}, 1, 1, 2, 6, BROWN);

                            DrawCylinder((Vector3){1, 0, -4}, 0, 1.5, 3, 8, GOLD);
                            DrawCylinderWires((Vector3){1, 0, -4}, 0, 1.5, 3, 8, PINK);

                            DrawModelEx(cat, (Vector3){ 8.0f, 0.0f, 2.0f }, (Vector3){ 0.0f, 0.5f*framesCounter, 0.0f }, (Vector3){ 0.1f, 0.1f, 0.1f }, WHITE);
                            DrawGizmo((Vector3){ 8.0f, 0.0f, 2.0f });

                            DrawGrid(10.0, 1.0);        // Draw a grid

                        End3dMode();

                        DrawFPS(900, 220);

                    } break;
                    case AUDIO:
                    {
                        DrawText("This module give you functions to:", 48, 200, 10, GetColor(0x8c7539ff));
                        
                        DrawTextEx(fontRomulus, "Load and Play Sounds", (Vector2){ 48, 230 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x8c7539ff));
                        DrawTextEx(fontRomulus, "Play Music (streaming)", (Vector2){ 48, 260 }, GetFontBaseSize(fontRomulus)*2, 4, GetColor(0x8c7539ff));

                        DrawText("PRESS SPACE to START PLAYING MUSIC", 135, 350, 20, GRAY);
                        DrawRectangle(150, 390, 400, 12, LIGHTGRAY);
                        DrawRectangle(150, 390, (int)timePlayed, 12, MAROON);

                        if (MusicIsPlaying())
                        {
                            DrawText("PRESS 'S' to STOP PLAYING MUSIC", 165, 425, 20, GRAY);

                            for (int i = 0; i < MAX_BALLS; i++)
                            {
                                if (soundBallsActive[i]) DrawPoly(soundBallsPosition[i], 18, soundBallsRadius[i], 0.0f, Fade(soundBallsColor[i], soundBallsAlpha[i]));
                            }
                        }

                        DrawText("PRESS 'N' to PLAY a SOUND", 200, 540, 20, VIOLET);

                        if ((framesCounter/30)%2) DrawText("PRESS ENTER to CONTINUE", 930, 650, 20, GRAY);

                    } break;
                    default: break;
                }

                // Draw modules menu
                DrawRectangle(128 + 40 + 30, 128 + 40 - 70 - 8, 150, 70, GetColor(0x898888ff));
                DrawRectangle(128 + 40 + 30 + 8, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xe1e1e1ff));
                DrawText("CORE", 128 + 40 + 30 + 8 + 38, 128 + 40 - 50, 20, GetColor(0x5c5a5aff));

                DrawRectangle(128 + 40 + 30 + 175, 128 + 40 - 70 - 8, 150, 70, GetColor(0xe66666ff));
                DrawRectangle(128 + 40 + 30 + 8 + 175, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xf0d6d6ff));
                DrawText("SHAPES", 128 + 40 + 30 + 8 + 175 + 28, 128 + 40 - 50, 20, GetColor(0xcd5757ff));

                DrawRectangle(128 + 40 + 30 + 175*2, 128 + 40 - 70 - 8, 150, 70, GetColor(0x75a06dff));
                DrawRectangle(128 + 40 + 30 + 8 + 175*2, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xc8eabfff));
                DrawText("TEXTURES", 128 + 40 + 30 + 175*2 + 8 + 9, 128 + 40 - 50, 20, GetColor(0x60815aff));

                DrawRectangle(128 + 40 + 30 + 175*3, 128 + 40 - 70 - 8, 150, 70, GetColor(0x52b296ff));
                DrawRectangle(128 + 40 + 30 + 8 + 175*3, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xbef0ddff));
                DrawText("TEXT", 128 + 40 + 30 + 8 + 175*3 + 38, 128 + 40 - 50, 20, GetColor(0x377764ff));

                DrawRectangle(128 + 40 + 30 + 175*4, 128 + 40 - 70 - 8, 150, 70, GetColor(0x5d9cbdff));
                DrawRectangle(128 + 40 + 30 + 8 + 175*4, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xbedce8ff));
                DrawText("MODELS", 128 + 40 + 30 + 8 + 175*4 + 28, 128 + 40 - 50, 20, GetColor(0x417794ff));

                DrawRectangle(128 + 40 + 30 + 175*5, 128 + 40 - 70 - 8, 150, 70, GetColor(0xd3b157ff));
                DrawRectangle(128 + 40 + 30 + 8 + 175*5, 128 + 40 - 70, 150 - 16, 70 - 16, GetColor(0xebddaeff));
                DrawText("AUDIO", 128 + 40 + 30 + 8 + 175*5 + 36, 128 + 40 - 50, 20, GetColor(0x8c7539ff));

            } break;
            case ENDING:
            {
                // Draw ENDING screen
                DrawTextEx(fontAlagard, "LEARN VIDEOGAMES PROGRAMMING", (Vector2){ screenWidth/2 - MeasureTextEx(fontAlagard, "LEARN VIDEOGAMES PROGRAMMING", GetFontBaseSize(fontAlagard)*4, 4).x/2, 80 }, GetFontBaseSize(fontAlagard)*4, 4, MAROON);

                DrawTexture(raylibLogoA, logoPositionX, logoPositionY - 40, WHITE);

                DrawText(msgWeb, screenWidth/2 - MeasureText(msgWeb, 40)/2, 470, 40, DARKGRAY);

                if (framesCounter > 60) DrawText(msgCredits, screenWidth/2 - MeasureText(msgCredits, 30)/2, 550, 30, GRAY);

                if (framesCounter > 120) if ((framesCounter/30)%2) DrawText("PRESS ENTER to CONTINUE", screenWidth/2 - MeasureText("PRESS ENTER to CONTINUE", 20)/2, 640, 20, LIGHTGRAY);

            } break;
            case PONG:
            {
                // Pong
                DrawCircleV(pongBallPosition, 10, LIGHTGRAY);
                DrawRectangleRec(pongPlayerRec, GRAY);
                DrawRectangleRec(pongEnemyRec, GRAY);

                DrawText(FormatText("%02i", pongScorePlayer), 150, 10, 80, LIGHTGRAY);
                DrawText(FormatText("%02i", pongScoreEnemy), screenWidth - MeasureText("00", 80) - 150, 10, 80, LIGHTGRAY);

                if (pongPaused) if ((framesCounter/30)%2) DrawText("GAME PAUSED [P]", screenWidth/2 - 100, 40, 20, MAROON);
            } break;
            default: break;
        }

        if (currentScreen != LOADING) DrawRectangle(0, screenHeight - 10, ((float)timeCounter/(float)totalTime)*screenWidth, 10, LIGHTGRAY);

        if (onTransition) DrawTransition();

    EndDrawing();
    //----------------------------------------------------------------------------------
}
Beispiel #27
0
int main()
{    
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "Floppy Bird");
    
    InitAudioDevice();      // Initialize audio device
    
    Sound coin = LoadSound("resources/coin.wav");
    Sound jump = LoadSound("resources/jump.wav");
    
    Texture2D background = LoadTexture("resources/background.png");
    Texture2D tubes = LoadTexture("resources/tubes.png");
    Texture2D floppy = LoadTexture("resources/floppy.png");
    
    Vector2 floppyPos = { 80, screenHeight/2 - floppy.height/2 };
    
    Vector2 tubesPos[MAX_TUBES];
    int tubesSpeedX = 2;
    
    for (int i = 0; i < MAX_TUBES; i++)
    {
        tubesPos[i].x = 400 + 280*i;
        tubesPos[i].y = -GetRandomValue(0, 120);
    }
    
    Rectangle tubesRecs[MAX_TUBES*2];
    bool tubesActive[MAX_TUBES];
    
    for (int i = 0; i < MAX_TUBES*2; i += 2)
    {
        tubesRecs[i].x = tubesPos[i/2].x;
        tubesRecs[i].y = tubesPos[i/2].y;
        tubesRecs[i].width = tubes.width;
        tubesRecs[i].height = 255;
        
        tubesRecs[i+1].x = tubesPos[i/2].x;
        tubesRecs[i+1].y = 600 + tubesPos[i/2].y - 255;
        tubesRecs[i+1].width = tubes.width;
        tubesRecs[i+1].height = 255;
        
        tubesActive[i/2] = true;
    }
 
    int backScroll = 0;
    
    int score = 0;
    int hiscore = 0;
    
    bool gameover = false;
    bool superfx = false;
    
    SetTargetFPS(60);
    //---------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        backScroll--;
        
        if (backScroll <= -800) backScroll = 0; 
        
        for (int i = 0; i < MAX_TUBES; i++) tubesPos[i].x -= tubesSpeedX;
        
        for (int i = 0; i < MAX_TUBES*2; i += 2)
        {
            tubesRecs[i].x = tubesPos[i/2].x;
            tubesRecs[i+1].x = tubesPos[i/2].x;
        }

        if (IsKeyDown(KEY_SPACE) && !gameover) floppyPos.y -= 3;
        else floppyPos.y += 1;
        
        if (IsKeyPressed(KEY_SPACE) && !gameover) PlaySound(jump);
        
        // Check Collisions
        for (int i = 0; i < MAX_TUBES*2; i++)
        {
            if (CheckCollisionCircleRec((Vector2){ floppyPos.x + floppy.width/2, floppyPos.y + floppy.height/2 }, floppy.width/2, tubesRecs[i])) 
            {
                gameover = true;
            }
            else if ((tubesPos[i/2].x < floppyPos.x) && tubesActive[i/2] && !gameover)
            {
                score += 100;
                tubesActive[i/2] = false;
                PlaySound(coin);
                
                superfx = true;
                
                if (score > hiscore) hiscore = score;
            }
        }
        
        if (gameover && IsKeyPressed(KEY_ENTER))
        {
            for (int i = 0; i < MAX_TUBES; i++)
            {
                tubesPos[i].x = 400 + 280*i;
                tubesPos[i].y = -GetRandomValue(0, 120);
            }
    
            for (int i = 0; i < MAX_TUBES*2; i += 2)
            {
                tubesRecs[i].x = tubesPos[i/2].x;
                tubesRecs[i].y = tubesPos[i/2].y;
                
                tubesRecs[i+1].x = tubesPos[i/2].x;
                tubesRecs[i+1].y = 600 + tubesPos[i/2].y - 255;
                
                tubesActive[i/2] = true;
            }
        
            floppyPos.x = 80;
            floppyPos.y = screenHeight/2 - floppy.height/2;
            
            gameover = false;
            score = 0;
        }
        
        //----------------------------------------------------------------------------------
        
        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();
        
            ClearBackground(RAYWHITE);
            
            DrawTexture(background, backScroll, 0, WHITE);
            DrawTexture(background, screenWidth + backScroll, 0, WHITE);
            
            if (!gameover)
            {
                DrawTextureEx(floppy, floppyPos, 0, 1.0, WHITE);
                //DrawCircleLines(floppyPos.x + floppy.width/2, floppyPos.y + floppy.height/2, floppy.width/2, RED);
            }
            
            for (int i = 0; i < MAX_TUBES; i++)
            {
                if (tubesPos[i].x <= 800) DrawTextureEx(tubes, tubesPos[i], 0, 1.0, WHITE);
            
                //DrawRectangleLines(tubesRecs[i*2].x, tubesRecs[i*2].y, tubesRecs[i*2].width, tubesRecs[i*2].height, RED);
                //DrawRectangleLines(tubesRecs[i*2 + 1].x, tubesRecs[i*2 + 1].y, tubesRecs[i*2 + 1].width, tubesRecs[i*2 + 1].height, RED);
            }
            
            DrawText(FormatText("%04i", score), 20, 20, 40, PINK);
            DrawText(FormatText("HI-SCORE: %04i", hiscore), 20, 70, 20, VIOLET); 
            
            if (gameover)
            {
                DrawText("GAME OVER", 100, 180, 100, MAROON);
                DrawText("PRESS ENTER to RETRY!", 280, 280, 20, RED);    
            }
            
            if (superfx)
            {
                DrawRectangle(0, 0, screenWidth, screenHeight, GOLD);
                superfx = false;
            }
        
        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadTexture(background);  // Texture unloading
    UnloadTexture(tubes);       // Texture unloading
    UnloadTexture(floppy);      // Texture unloading
    
    UnloadSound(coin);          // Unload sound data
    UnloadSound(jump);          // Unload sound data
    
    CloseAudioDevice();         // Close audio device
    
    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------
    
    return 0;
}
Beispiel #28
0
// Update game (one frame)
void UpdateGame(void)
{
    if (!gameOver)
    {
        if (IsKeyPressed('P')) pause = !pause;

        if (!pause)
        {
            switch (wave)
            {
                case FIRST:
                {
                    if (!smooth)
                    {
                        alpha += 0.02f;
                        
                        if (alpha >= 1.0f) smooth = true;
                    }
                    
                    if (smooth) alpha -= 0.02f;
                    
                    if (enemiesKill == activeEnemies)
                    {
                        enemiesKill = 0;

                        for (int i = 0; i < activeEnemies; i++)
                        {
                            if (!enemy[i].active) enemy[i].active = true;
                        }
                        
                        activeEnemies = SECOND_WAVE;
                        wave = SECOND;
                        smooth = false;
                        alpha = 0.0f;
                    }
                } break;
                case SECOND:
                {
                    if (!smooth)
                    {
                        alpha += 0.02f;
                        
                        if (alpha >= 1.0f) smooth = true;
                    }
                    
                    if (smooth) alpha -= 0.02f;
                    
                    if (enemiesKill == activeEnemies)
                    {
                        enemiesKill = 0;

                        for (int i = 0; i < activeEnemies; i++)
                        {
                            if (!enemy[i].active) enemy[i].active = true;
                        }
                        
                        activeEnemies = THIRD_WAVE;
                        wave = THIRD;
                        smooth = false;
                        alpha = 0.0f;
                    }
                } break;
                case THIRD:
                {
                    if (!smooth)
                    {
                        alpha += 0.02f;
                        
                        if (alpha >= 1.0f) smooth = true;
                    }
                    
                    if (smooth) alpha -= 0.02f;
                    
                    if (enemiesKill == activeEnemies) victory = true;
                        
                } break;
                default: break;
            }

            // Player movement
            if (IsKeyDown(KEY_RIGHT)) player.rec.x += player.speed.x;
            if (IsKeyDown(KEY_LEFT)) player.rec.x -= player.speed.x;
            if (IsKeyDown(KEY_UP)) player.rec.y -= player.speed.y;
            if (IsKeyDown(KEY_DOWN)) player.rec.y += player.speed.y;

            // Player collision with enemy
            for (int i = 0; i < activeEnemies; i++)
            {
                if (CheckCollisionRecs(player.rec, enemy[i].rec)) gameOver = true;
            }

             // Enemy behaviour
            for (int i = 0; i < activeEnemies; i++)
            {
                if (enemy[i].active)
                {
                    enemy[i].rec.x -= enemy[i].speed.x;

                    if (enemy[i].rec.x < 0)
                    {
                        enemy[i].rec.x = GetRandomValue(screenWidth, screenWidth + 1000);
                        enemy[i].rec.y = GetRandomValue(0, screenHeight - enemy[i].rec.height);
                    }
                }
            }

            // Wall behaviour
            if (player.rec.x <= 0) player.rec.x = 0;
            if (player.rec.x + player.rec.width >= screenWidth) player.rec.x = screenWidth - player.rec.width;
            if (player.rec.y <= 0) player.rec.y = 0;
            if (player.rec.y + player.rec.height >= screenHeight) player.rec.y = screenHeight - player.rec.height;

            //Shoot initialization
            if (IsKeyDown(KEY_SPACE))
            {
                shootRate += 5;

                for (int i = 0; i < NUM_SHOOTS; i++)
                {
                    if (!shoot[i].active && shootRate%20 == 0)
                    {
                        shoot[i].rec.x = player.rec.x;
                        shoot[i].rec.y = player.rec.y + player.rec.height/4;
                        shoot[i].active = true;
                        break;
                    }
                }
            }

            // Shoot logic
            for (int i = 0; i < NUM_SHOOTS; i++)
            {
                if (shoot[i].active)
                {
                    // Movement
                    shoot[i].rec.x += shoot[i].speed.x;

                    // Collision with enemy
                    for (int j = 0; j < activeEnemies; j++)
                    {
                        if (enemy[j].active)
                        {
                            if (CheckCollisionRecs(shoot[i].rec, enemy[j].rec))
                            {
                                shoot[i].active = false;
                                enemy[j].rec.x = GetRandomValue(screenWidth, screenWidth + 1000);
                                enemy[j].rec.y = GetRandomValue(0, screenHeight - enemy[j].rec.height);
                                shootRate = 0;
                                enemiesKill++;
                                score += 100;
                            }
                            
                            if (shoot[i].rec.x + shoot[i].rec.width >= screenWidth)
                            {
                                shoot[i].active = false;
                                shootRate = 0;
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        if (IsKeyPressed(KEY_ENTER))
        {
            InitGame();
            gameOver = false;
        }
    }
}