Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/c/alarm/alarm.cpp
363 views
1
#include <iostream>
2
#include <iomanip>
3
#include <cstdlib>
4
#include <ctime>
5
#include <unistd.h>
6
7
#ifdef __MINGW32__
8
#include <windows.h>
9
#include <mmsystem.h> // need to link libwinmm.a
10
#endif
11
12
using namespace std;
13
14
class Alarm {
15
16
static const char bell = 7;
17
unsigned hh, mm, ss;
18
unsigned ah = 25, am = 0, as = 0; // 默认不响
19
int alertCount = 0; // 还需要响几下
20
21
public:
22
int alertLength = 10000; // 闹铃长度
23
24
void setAlarm(unsigned h, unsigned m, unsigned s)
25
{
26
ah = h;
27
am = m;
28
as = s;
29
}
30
31
void print() const // const 方法不修改成员变量
32
{
33
cout << '\r' // 清除当前行
34
<< setw(2) << hh << ':'
35
<< setw(2) << mm << ':'
36
<< setw(2) << ss << flush;
37
}
38
39
void update(time_t cur_sec)
40
{
41
hh = (cur_sec / 3600 + 8) % 24;
42
mm = cur_sec / 60 % 60;
43
ss = cur_sec % 60;
44
}
45
46
void run()
47
{
48
time_t last_sec = time(NULL); // 获取系统时间
49
cout << setfill('0'); // 在 cout 的数字前补 0
50
while (true) {
51
usleep(2000); // 休息 2000 μs
52
#ifdef __MINGW32__
53
if (alertCount > 0) {
54
PlaySound("Alarm07.wav", NULL, SND_FILENAME | SND_ASYNC);
55
alertCount = 0;
56
}
57
#else
58
if (alertCount > 0) {
59
cout << bell << flush;
60
--alertCount;
61
}
62
#endif
63
time_t cur_sec = time(NULL);
64
if (cur_sec != last_sec) {
65
update(cur_sec);
66
print();
67
last_sec = cur_sec;
68
if (ah == hh && am == mm && as == ss) {
69
alertCount = alertLength;
70
}
71
}
72
}
73
}
74
};
75
76
int main(int argc, char **argv)
77
{
78
Alarm a;
79
if (argc > 3) {
80
a.setAlarm(
81
atoi(argv[1]),
82
atoi(argv[2]),
83
atoi(argv[3])
84
);
85
}
86
a.run();
87
return 0;
88
}
89
90