跳动爱心代码c++代码可运行
时间: 2025-02-18 17:07:39 浏览: 47
### 可运行的 C++ 跳动爱心动画代码
为了创建一个跳动的心形图案,可以通过调整心形大小并刷新屏幕来模拟心跳的效果。下面是一个完整的C++程序示例,该程序会在控制台显示一个不断变化尺寸的心形图形。
```cpp
#include <iostream>
#include <conio.h> // For _getch()
#include <windows.h> // For Sleep()
using namespace std;
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// Function to clear the console screen.
void clrscr() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
int heart[] = {
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17,
};
char* shapes[] = {
" *** ",
" ***** **** ",
" ** ********** ",
"*** *********** ",
"** ************ ",
"* ************* ",
" * ************ ",
" ** ********** ",
" ************",
" ********** ",
" ******** ",
" ******* ",
" **** "
};
void drawHeart(float scale) {
for (size_t i = 0; i < sizeof(shapes)/sizeof(char*) ; ++i){
string line = shapes[i];
float scaledLength = static_cast<float>(line.length()) * scale;
int newLength = min(static_cast<int>(scaledLength), static_cast<int>(shapes[0]));
cout << line.substr(0, newLength).c_str();
cout << endl;
}
Sleep(100); // Delay between frames
}
int main(){
while(true){
clrscr();
for(auto size : heart){
float scale = size / 10.0f;
gotoxy((80 - strlen(shapes[size]))/2 , 10-size);
drawHeart(scale);
if (_kbhit()){
break;
}
}
for(auto rSize = end(heart)-1; rSize >= begin(heart); --rSize){
float scale = (*rSize) / 10.0f;
gotoxy((80 - strlen(shapes[*rSize]))/2 , 10-*rSize);
drawHeart(scale);
if(_kbhit()){
break;
}
}
if (_kbhit())
break;
}
}
```
此代码通过改变`drawHeart()`函数中的比例参数来绘制不同大小的心脏形状,并利用循环交替增大和减小心脏图像以形成脉搏效果[^2]。
阅读全文
相关推荐

















