How to write code for a snow animation in the C languag…

Here is a simple code example for a snow animation in C language.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h> // 用于Sleep函数

#define WIDTH 80      // 屏幕宽度
#define HEIGHT 25     // 屏幕高度
#define SNOW_NUM 100  // 雪花数量

typedef struct {
    int x;
    int y;
} Snowflake;

Snowflake snowflakes[SNOW_NUM]; // 雪花数组

// 初始化雪花位置
void initSnowflakes() {
    int i;
    for (i = 0; i < SNOW_NUM; i++) {
        snowflakes[i].x = rand() % WIDTH;
        snowflakes[i].y = rand() % HEIGHT;
    }
}

// 更新雪花位置
void updateSnowflakes() {
    int i;
    for (i = 0; i < SNOW_NUM; i++) {
        snowflakes[i].y++;
        if (snowflakes[i].y >= HEIGHT) {
            snowflakes[i].y = 0;
            snowflakes[i].x = rand() % WIDTH;
        }
    }
}

// 绘制雪花
void drawSnowflakes() {
    int i;
    for (i = 0; i < SNOW_NUM; i++) {
        COORD coord = {snowflakes[i].x, snowflakes[i].y};
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
        printf("*");
    }
}

int main() {
    initSnowflakes(); // 初始化雪花位置

    while (1) {
        updateSnowflakes(); // 更新雪花位置
        system("cls");      // 清屏
        drawSnowflakes();   // 绘制雪花
        Sleep(100);         // 延时
    }

    return 0;
}

The code uses the COORD structure and SetConsoleCursorPosition function from the windows.h library to achieve the effect of drawing snowflakes in the console. In the initSnowflakes function, the random positions of SNOW_NUM snowflakes are initialized. In the updateSnowflakes function, the y-coordinate of each snowflake is incremented by 1 each time, and when the y-coordinate exceeds the screen height, the position is randomly reassigned. In the drawSnowflakes function, the SetConsoleCursorPosition function is used to move the cursor to the specified position and print “*” to represent the snowflake. In the main function, an infinite loop is used to continuously update, clear the screen, and draw the snowflake effect, and the animation delay is controlled by the Sleep function.

bannerAds