基于EasyX和Raylib的字符阵

字符阵是 EasyX 的经典样例程序: https://codebus.cn/yangw/character-matrix

使用 raylib 替代 easyx. 除了常规的 API 替换, 还需要额外调用 SwapScreenBuffer().
由于 DrawText() / DrawTextEx() 并不会检测已经绘制文字的位置, 会存在字体重叠的问题
Raylib 默认的字体显示效果不太理想, 需要额外准备 ttf 字体文件加载使用

基于 Raylib 的实现

#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#include "raylib_helper.hpp"
#include <time.h>
#include <math.h>

#include <string>

const int width = 640;
const int height = 480;
int x[3];
int y[3];
int c[3];
char s[2] = { 0 };

Font font;

void startup()
{
	InitWindow(width, height, "Character Matrix");
	SetTargetFPS(60);

	srand((unsigned)time(NULL));
	// anonymous_pro_bold.ttf
	font = LoadFontEx("anonymous_pro_bold.ttf", 96, 0, 0);
}

void update()
{
	for (int j = 0; j < 3; j++)
	{
		x[j] = (rand() % 80) * 8;
		y[j] = (rand() % 20) * 24;
		c[j] = (rand() % 26) + 'a';
	}
}

void show()
{
	static int i = 0;
	BeginDrawing();
	{
		ClearBackground(BLACK);
		for (int j = 0; j < 3; j++)
		{
			//DrawText(s, x[j], y[j], 30, GREEN);
			Vector2 pos = make_vector(x[j], y[j]);
			int fontsize = 16;
			int spacing = 10;
			s[0] = c[j];
			DrawTextEx(font, s, pos, fontsize, spacing, GREEN);
			//DrawRectangle(x[j], y[j], 8, 16, GREEN);
		}

		i = (i + 1) % height;
		Vector2 startPos = make_vector(0, i);
		Vector2 endPos = make_vector(width - 1, i);
		int thick = 2;
		DrawLineEx(startPos, endPos, thick, BLACK);

		SwapScreenBuffer(); //! 确保相邻两帧的内容都被正确绘制。若没有这句,则当前帧绘制的文字在下一帧不显示,在第三帧才显示
	}
	EndDrawing();
}

int main()
{
	startup();
	while (!WindowShouldClose())
	{
		update();
		show();
	}
	CloseWindow();

	return 0;
}

基于 EasyX 的实现

// 程序名称:字符阵
// 编译环境:Visual C++ 6.0 / 2010,EasyX_20200902
// 发布日期:2009-2-22
//
#include <graphics.h>
#include <time.h>
#include <conio.h>

int main()
{
	// 设置随机函数种子
	srand((unsigned)time(NULL));

	// 初始化图形模式
	initgraph(640, 480);

	int x, y;
	TCHAR c;

	settextstyle(16, 8, _T("Courier"));	// 设置文字样式
	settextcolor(GREEN);				// 设置文字颜色
	setlinecolor(BLACK);				// 设置画线颜色

	while (!_kbhit())
	{
		for (int i = 0; i < 479; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				x = (rand() % 80) * 8;
				y = (rand() % 20) * 24;
				c = (rand() % 26) + 65;
				outtextxy(x, y, c);
			}

			line(0, i, 639, i);

			Sleep(10);
			if (_kbhit()) break;
		}
	}

	// 关闭图形模式
	closegraph();
	return 0;
}
posted @ 2023-01-25 21:19  ChrisZZ  阅读(108)  评论(0编辑  收藏  举报