C - 如何制作一个简单的计时器,以及如何使用基于语句的语句使用

C++ - How to make a simple timer and how would I go about using if statements based on it?

本文关键字:语句 于语句 何使用 一个 简单 何制作 计时器      更新时间:2023-10-16

im制作一种虚拟宠物。在某种程度上,我要复制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);
}

ive创建了一个班级和一些功能来喂养宠物,检查其体重,如果他饿了,但我也想制作一个时钟一定的数量已经过去了,我会打印出使用前面定义的bool变量的虚拟宠物饿了。谢谢。

您可以使用库Chrono测量时间板,然后采取相应的行动。

#include <chrono>
#include <ctime>
#include <iostream>
#include <thread>
int main () { 
    auto start = 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
        const auto now = std::chrono::system_clock::now();
        const 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

main()中,创建了一个计时器,该计时器允许PET未燃料5秒,并检查是否每秒未露面。如果在最后一顿饭之前超过5秒钟,则喂宠物并记录喂养时间。计时器运行10秒,然后作为演示停止。

在不同的持续时间内,请查看std::chrono::duration的助手类型。

#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可以与之交互。一种方法是在PET饥饿并向用户打印消息后,将计时器 stop()等待,等待用户喂食宠物,将lastFed设置为std::chrono::steady_clock::now(),然后再次将计时器设置为start()