C ++ - 如何创建一个简单的计时器,我将如何使用基于它的if语句?

时间:2017-09-28 09:25:37

标签: c++

我正在制作一种虚拟宠物。在某种程度上我复制了tamagochi。

// VirtualPetProjClassesandObjectsPRCT.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
#include "Vpet.h"

int main()
{
    // Set Name & General Info
    std::string pop;
    std::cout << "What would you like to call your pet?" << std::endl;
    std::cin >> pop;
    std::cout << "List of commands you can do with " << pop << std::endl << "'state'" << std::endl << "'quit'" << std::endl << "'feed'." << std::endl;
    std::cout << "If you feed bob less than quarter his weight he will gain weight but still be hungry!" << std::endl;
    std::cout << "Bob weighs 50 kgs!" << std::endl;

    VPet bob(50, false);
    bob.feedPet(5);
    do
    {
        //input
        std::string input;
        std::cin >> input;

        if (input == "Quit" || input == "quit")
        {
            return 0;
        }

        if (input == "Feed" || input == "feed")
        {
            std::cout << "Enter the amount you would like to feed " << pop << " - ";
            int x;
            std::cin >> x;
            if (x > (bob.getWeight() * 0.5))
            {
                std::cout << "Bob can't eat that much!" << std::endl;
            }
            else
            {
                bob.feedPet(x);
                std::cout << "You have fed " << pop << " " << x << " kgs of food!" << std::endl;
            }
        }

        // State
        if (input == "State" || input == "state")
        {
            std::cout << pop << " weighs: " << bob.getWeight() << std::endl;

            if (bob.getHungry())
            {
                std::cout << pop << " is hungry." << std::endl;
            }
            else
            {
                std::cout << pop << " is not hungry." << std::endl;
            }
        }
    } while (0 != 1);
}

我创造了一个班级和一些功能来喂养宠物,检查它的重量,如果他饿了但我还想制作一个时钟,每隔几分钟或几秒钟检查一下,看看已经过了多少时间,如果一个已经过了一定数量我会使用之前定义的bool变量打印虚拟宠物。感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用库计时器来测量时间跨度,然后采取相应的行动。

#include <chrono>
#include <ctime>
#include <iostream>
#include <thread>

int main () { 
    auto start = std::chrono::system_clock::now();
    auto duration = std::chrono::system_clock::now();

    while (1) {

        std::this_thread::sleep_for(std::chrono::milliseconds(100));

        // In your real code you will perhaps not need the sleep

        auto now = std::chrono::system_clock::now();
        auto duration = now - start;
        if ( duration.count() > 2e9)
            break;
        std::cout << "waiting ..."  << std::endl;
    } 

    std::cout <<"done" << std::endl;
}

time ./chrono_example此输出:

等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 等待...... 完成

真正的0m2.013s

用户0m0.002s

sys 0m0.004s

答案 1 :(得分:1)

main()中,会创建一个计时器,允许宠物在5秒内未动,并检查是否每秒都没有动物。如果在最后一餐之前超过5秒钟,则喂食宠物并记录喂食时间。计时器运行10秒钟,然后作为演示停止。

对于不同的持续时间,请查看std::chrono::duration的{​​{3}}。

#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>

class FeedTimer {
public:
    using Clock = std::chrono::steady_clock;
    using TimePoint = std::chrono::time_point<Clock>;
    using Duration = std::chrono::seconds;

    FeedTimer(Duration limit, Duration tick) : alive(false),
                                               lastFed(Clock::now()),
                                               limit(limit),
                                               tickRate(tick) { }

    ~FeedTimer() {
        // If running, the thread is stopped when it is destroyed.
        if (alive) {
            stop();
        }
    }

    // Starts the timer.
    void start() {
        alive = true;
        thread = std::thread(&FeedTimer::update, this);
        std::cout << "Timer started.\n";
    }

    // Stops the timer.
    void stop() {
        alive = false;
        thread.join();
        std::cout << "Timer stopped.\n";
    }

    void update() {
        while (alive) {
            TimePoint now = Clock::now();

            // Determines if more time has passed than the allowed limit.
            if (now - lastFed > limit) {
                lastFed = now;
                std::cout << "Just fed the pet.\n";
            } else {
                std::cout << "Pet is full.\n";
            }

            std::this_thread::sleep_for(tickRate);
        }
    }

private:
    std::atomic<bool> alive; // Thread stops when this is false.
    std::thread thread;
    TimePoint lastFed; // The last time the pet was fed.
    Duration limit; // Maximum amount of time the pet can go unfed.
    Duration tickRate; // Rate at which the timer runs.
};

int main() {
    FeedTimer timer = FeedTimer(std::chrono::seconds(5),
                                std::chrono::seconds(1));
    timer.start();

    std::this_thread::sleep_for(std::chrono::seconds(10));
    timer.stop();
}

您希望对其进行修改,以便VPet可以与之互动。一种方法是在宠物饥饿时stop()定时器并向用户打印消息,等待用户喂食宠物,将lastFed设置为std::chrono::steady_clock::now(),并{{1再次计时器。