02、C语言--黑客帝国(数字雨)
数字雨效果
在黑客帝国电影场景中,曾出现大量的数字雨特效。在现实的生活中,雨往往给人一种清新的感觉,而雨后的感觉则是新生。
也许,电影中所表达的意思便是对自我的启迪乃至新生的过程。
代码如下所示:
#include <stdio.h>
#include <graphics.h>
// 窗口的宽和高
#define WIDTH 960
#define HEIGHT 640
#define STR_SIZE 25 // 数字雨数组最大存储
#define STR_NUM 128 // 数字雨的串数
#define STR_WIDTH 15 // 字符串宽度
// 雨的结构
struct Rain {
int x;
int y;
int speed; // 下降速度
char str[STR_SIZE]; // 数字雨数组
}rain[STR_NUM];
char CreateCh() {
char temp = 0;
int flag = rand() % 3;
if (flag == 0) {
temp = rand() % 26 + \'a\';
} else if (flag == 1) {
temp = rand() % 26 + \'A\';
} else {
temp = rand() % 10 + \'0\';
}
return temp;
}
void GameInit() {
// 初始化基础数据
for (size_t i = 0; i < STR_NUM; i++) {
rain[i].x = i * STR_WIDTH;
rain[i].y = rand() % HEIGHT;
rain[i].speed = (rand() % 5) + 5;
}
// 初始化字符串
for (size_t i = 0; i < STR_NUM; i++) {
for (size_t j = 0; j < STR_SIZE; j++) {
rain[i].str[j] = CreateCh();
if (rain[i].y > HEIGHT) {
rain[i].y = 0;
}
}
}
}
void GameDraw() {
cleardevice();
for (size_t i = 0; i < STR_NUM; i++) {
for (size_t j = 0; j < STR_SIZE; j++) {
outtextxy(rain[i].x, rain[i].y - STR_WIDTH * j, rain[i].str[j]);
settextcolor(RGB(0, 255 - (13 * j), 0));
}
}
}
void GamePlay() {
for (size_t i = 0; i < STR_NUM; i++) {
rain[i].y += rain[i].speed;
if (rain[i].y - STR_SIZE * STR_WIDTH > WIDTH) {
rain[i].y = 0;
}
}
}
void ChangeCh() {
for (size_t i = 0; i < STR_NUM; i++) {
rain[rand() % STR_NUM].str[rand() % STR_SIZE] = CreateCh();
}
}
int main() {
initgraph(WIDTH, HEIGHT);
srand(GetTickCount());
DWORD t1, t2;
t1 = t2 = GetTickCount();
GameInit();
while (true) {
BeginBatchDraw();
GameDraw();
ChangeCh();
if (t2 - t1 > 20) { // 使游戏下落延时
GamePlay();
t1 = t2;
}
t2 = GetTickCount();
EndBatchDraw();
// Sleep(20); // 使整个程序延时
}
getchar();
closegraph();
return 0;
}