用c语言写一个爱心会动的程序
时间: 2023-10-07 21:06:55 浏览: 75
以下是一个使用C语言和SDL图形库编写的爱心动画程序:
```c
#include <SDL2/SDL.h>
#include <stdio.h>
// 窗口大小
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
// 爱心坐标
int heart_x = 0;
int heart_y = 0;
// 爱心大小
int heart_width = 100;
int heart_height = 100;
// 爱心颜色
Uint8 heart_r = 0;
Uint8 heart_g = 0;
Uint8 heart_b = 0;
// 初始化SDL和窗口
bool init();
// 载入媒体文件
bool loadMedia();
// 释放媒体文件和SDL
void close();
// 主函数
int main(int argc, char* args[]) {
// 初始化SDL和窗口
if (!init()) {
printf("Failed to initialize!\n");
return 1;
}
// 载入媒体文件
if (!loadMedia()) {
printf("Failed to load media!\n");
return 2;
}
// 循环更新爱心属性和绘制爱心
bool quit = false;
SDL_Event e;
while (!quit) {
// 处理事件
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
// 更新爱心位置
heart_x = (heart_x + 5) % (SCREEN_WIDTH - heart_width);
heart_y = (heart_y + 5) % (SCREEN_HEIGHT - heart_height);
// 更新爱心大小
heart_width = (heart_width + 1) % 200;
heart_height = (heart_height + 1) % 200;
// 更新爱心颜色
heart_r = (heart_r + 1) % 256;
heart_g = (heart_g + 2) % 256;
heart_b = (heart_b + 3) % 256;
// 清空屏幕
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
// 绘制爱心
SDL_Rect heartRect = { heart_x, heart_y, heart_width, heart_height };
SDL_SetRenderDrawColor(gRenderer, heart_r, heart_g, heart_b, 0xFF);
SDL_RenderFillRect(gRenderer, &heartRect);
// 更新屏幕
SDL_RenderPresent(gRenderer);
}
// 释放资源
close();
return 0;
}
bool init() {
// 初始化SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return false;
}
// 创建窗口
gWindow = SDL_CreateWindow("爱心动画", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == NULL) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return false;
}
// 创建渲染器
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
if (gRenderer == NULL) {
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
// 设置渲染器颜色
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
return true;
}
bool loadMedia() {
return true;
}
void close() {
// 销毁渲染器
SDL_DestroyRenderer(gRenderer);
gRenderer = NULL;
// 销毁窗口
SDL_DestroyWindow(gWindow);
gWindow = NULL;
// 退出SDL
SDL_Quit();
}
```
在这个程序中,我们通过SDL图形库实现了爱心的移动、大小变化和颜色变化。具体实现方法是,在循环中不断更新爱心的属性(位置、大小、颜色)并重新绘制爱心,然后在每次循环结束后更新屏幕以显示出动画效果。
阅读全文