关于变量范围的问题

时间:2014-01-09 06:00:19

标签: c++ scope

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

#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;
}

好!所以我的问题是变量'originalTimer'。它超出了重置计时器的范围,所以我能做些什么呢?对不起,如果这是一个非常基本的问题。

2 个答案:

答案 0 :(得分:2)

你使用了不同的名字。 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;
}  

答案 1 :(得分:1)

可能是拼写错误,但有两个不同的变量originalTimeoriginalTimer

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

timer = originalTime; //reset timer.