#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
/* 基本类型定义 */
typedef uint32_t gfx_color_t;
/* 图形上下文结构体 */
typedef struct
{
int width;
int height;
char *display_buffer; // 终端模拟的显示缓冲区
gfx_color_t *pixel_buffer; // 像素缓冲区(模拟)
} gfx_context_t;
/* 初始化图形系统 */
gfx_context_t *gfx_init(int width, int height)
{
gfx_context_t *ctx = malloc(sizeof(gfx_context_t));
if (!ctx)
return NULL;
ctx->width = width;
ctx->height = height;
// 分配终端显示缓冲区(每个像素用1字符表示)
ctx->display_buffer = malloc(width * height + height + 1); // +height是为了换行符,+1是终止符
if (!ctx->display_buffer)
{
free(ctx);
return NULL;
}
// 分配像素缓冲区(模拟)
ctx->pixel_buffer = malloc(width * height * sizeof(gfx_color_t));
if (!ctx->pixel_buffer)
{
free(ctx->display_buffer);
free(ctx);
return NULL;
}
return ctx;
}
/* 释放图形系统 */
void gfx_free(gfx_context_t *ctx)
{
if (ctx)
{
free(ctx->display_buffer);
free(ctx->pixel_buffer);
free(ctx);
}
}
/* 清屏 */
void gfx_clear(gfx_context_t *ctx, gfx_color_t color)
{
// 简单实现:清空像素缓冲区
for (int i = 0; i < ctx->width * ctx->height; i++)
{
ctx->pixel_buffer[i] = color;
}
}
/* 绘制像素 */
void gfx_draw_pixel(gfx_context_t *ctx, int x, int y, gfx_color_t color)
{
if (x >= 0 && x < ctx->width && y >= 0 && y < ctx->height)
{
ctx->pixel_buffer[y * ctx->width + x] = color;
}
}
/* 将像素缓冲区渲染到终端 */
void gfx_render(gfx_context_t *ctx)
{
char *ptr = ctx->display_buffer;
for (int y = 0; y < ctx->height; y++)
{
for (int x = 0; x < ctx->width; x++)
{
// 简化:根据颜色值选择不同字符
gfx_color_t color = ctx->pixel_buffer[y * ctx->width + x];
// 简单映射:根据亮度选择字符
uint8_t brightness = (color >> 16) + (color >> 8) + color;
brightness /= 3;
if (brightness < 64)
*ptr++ = ' ';
else if (brightness < 128)
*ptr++ = '.';
else if (brightness < 192)
*ptr++ = '*';
else
*ptr++ = '#';
}
*ptr++ = '\n'; // 每行结束换行
}
*ptr = '\0'; // 字符串终止
// 清屏并输出
system("clear"); // Linux/macOS
// system("cls"); // Windows
printf("%s", ctx->display_buffer);
}
/* 主函数测试 */
int main()
{
// 初始化图形系统(80x25终端大小)
gfx_context_t *gfx = gfx_init(80, 25);
if (!gfx)
{
fprintf(stderr, "Failed to initialize graphics\n");
return 1;
}
// 清屏为黑色
gfx_clear(gfx, 0x000000);
// 绘制一些像素
for (int i = 0; i < 25; i++)
{
gfx_draw_pixel(gfx, i, i, 0xFF0000); // 红色对角线
gfx_draw_pixel(gfx, 40, i, 0x00FF00); // 绿色垂直线
gfx_draw_pixel(gfx, i, 12, 0x0000FF); // 蓝色水平线
}
// 绘制一个白色矩形
for (int y = 5; y < 15; y++)
{
for (int x = 50; x < 70; x++)
{
gfx_draw_pixel(gfx, x, y, 0xFFFFFF);
}
}
// 渲染到终端
gfx_render(gfx);
// 等待用户输入后退出
printf("Press Enter to exit...");
getchar();
// 释放资源
gfx_free(gfx);
return 0;
}