关于可变范围的问题

issue regarding variable scope

本文关键字:问题 范围 于可变      更新时间:2023-10-16

我很难掌握变量范围的概念。什么是可以接受的,什么是不可接受的?我知道我省略了所有与图形相关的代码,我知道我有一个无限的游戏循环,但请耐心等待:

#include "LList.h"
#include "Snake.h"
#undef main

int main()
{
float dt;               // time since last update.
int start_time;
bool paused = false;
float originalTime = 1.0f;
float timer = originalTime;
Snake p1Snake(10, false);

    // Start the 'stopwatch'
    start_time = SDL_GetTicks();
    ///////////////////////
    // The 'game loop'   //
    ///////////////////////
    while (!done)
    {
        //////////////////////
        // Update variables //
        //////////////////////
        // Update the dt value (to be the time since the last update)
        dt = (SDL_GetTicks() - start_time) / 1000.0f;
        start_time = SDL_GetTicks();
            //increment the movement timer
        timer-=dt;
        if(timer<=0) When timer hits zero the snake is moved north.
            {
                p1Snake.goNorth();
                timer = originalTimer; //reset timer.
            }
    }
    return 0;
}

好!所以我的问题是关于变量"原始计时器"。计时器的重置超出了范围,那么我可以做些什么不同的事情?对不起,如果这是一个非常基本的问题。

你使用了不同的名称。 originalTimeoriginalTimer

#include "LList.h"
#include "Snake.h"
#undef main

int main()
{
    float dt;               // time since last update.
    int start_time;
    bool paused = false;
    float originalTimer = 1.0f;  //Changed to originalTimer
    float timer = originalTimer; //Changed to originalTimer
    Snake p1Snake(10, false);
    // Start the 'stopwatch'
    start_time = SDL_GetTicks();
    ///////////////////////
    // The 'game loop'   //
    ///////////////////////
    while (!done)
    {
        //////////////////////
        // Update variables //
        //////////////////////
        // Update the dt value (to be the time since the last update)
        dt = (SDL_GetTicks() - start_time) / 1000.0f;
        start_time = SDL_GetTicks();
        //increment the movement timer
        timer-=dt;
        if(timer<=0) //When timer hits zero the snake is moved north.
        {
            p1Snake.goNorth();
            timer = originalTimer; //reset timer.
        }
    }
    return 0;
}  
可能是

错别字,但有两个不同的变量originalTimeoriginalTimer

更改下面的代码应该对您有用..

timer = originalTime; //reset timer.