字符陣是 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;
}