c++代码雨
cpp#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
const int SCREEN_WIDTH = 80;
const int SCREEN_HEIGHT = 25;
class Raindrop {
public:
int x, y, speed;
Raindrop() {
x = rand() % SCREEN_WIDTH;
y = -(rand() % SCREEN_HEIGHT);
speed = 1 + rand() % 5;
}
void fall() {
y += speed;
if (y >= SCREEN_HEIGHT) {
y = 0;
x = rand() % SCREEN_WIDTH;
}
}
};
int main() {
srand(time(NULL));
vector<Raindrop> raindrops;
for (int i = 0; i < 100; ++i) {
raindrops.push_back(Raindrop());
}
while (true) {
// Clear screen
system("cls");
// Move and draw raindrops
for (int i = 0; i < raindrops.size(); ++i) {
raindrops[i].fall();
cout << "3[" << raindrops[i].y << ";" << raindrops[i].x << "H" << "|";
}
// Delay to control the speed
// Adjust this value for different speeds
// Decrease for faster raindrops, increase for slower raindrops
// You can also use cross-platform sleep functions for better control
// For Windows, you can use Sleep() function from windows.h
// For POSIX systems, you can use usleep() function
// For example, Sleep(50) for Windows, usleep(50000) for POSIX
// Here, I'll use a simple loop for demonstration purposes
for (int i = 0; i < 10000000; ++i);
}
return 0;
}
这段代码模拟了雨滴在屏幕上落下的效果。编译并运行它,你会看到一系列竖直移动的竖线,就像雨滴一样。
上述代码使用了ASCII字符来模拟雨滴效果。现在我将为您解释一下代码的工作原理:
Raindrop类:这个类代表雨滴,具有属性x、y和speed。构造函数会在随机位置创建一个新的雨滴,并给它一个随机的下落速度。
main函数:在main函数中,首先使用srand函数初始化随机数生成器。然后创建一个包含100个Raindrop对象的vector,每个对象代表一个雨滴。
主循环:程序进入一个无限循环,在每次迭代中都会执行清空屏幕。让每个雨滴对象下落并打印到屏幕上,位置由x和y属性确定。添加一个简单的延迟,以控制雨滴的下落速度。
打印雨滴:每个雨滴在屏幕上表示为一条竖线,由字符"|"表示。通过设置光标位置来控制输出的位置。
延迟:在每次循环迭代之后,通过一个简单的空循环来制造延迟。在实际应用中,可以使用更精确的延迟函数。