Last active
May 2, 2021 08:37
-
-
Save Enchan1207/ee1489c2db2303c511be6b1ed2d22d16 to your computer and use it in GitHub Desktop.
ターミナルでカラフルなイルミネーションを
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ターミナルでカラフルなイルミネーションを | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#include <signal.h> | |
#include <unistd.h> | |
#include <stdbool.h> | |
char colors[5][5] = {"0;31","0;33","0;32", "0;36", "0;35"}; | |
bool endReq = false; | |
// シグナルハンドラ | |
void signalHandler(int signo){ | |
if(signo == SIGINT){ | |
printf("\033[0m\n"); | |
} | |
endReq = true; // ほんとはしっかりシグナル番号見るべき | |
} | |
int main(int argc, char const *argv[]){ | |
// イルミネーションさせる文字列を設定する | |
char const *string; | |
unsigned int length = 0; | |
if (argc > 1){ | |
string = argv[1]; | |
} | |
else{ | |
string = "Hello, World!"; | |
} | |
length = strlen(string); | |
// Ctrl+Cで止めた時にターミナルが汚れないよう、黒背景白文字に戻す | |
if(signal(SIGINT, signalHandler) == SIG_ERR){ | |
printf("Your terminal color won't be reset because SIGINT handling has failed.\n"); | |
} | |
// forで回す | |
unsigned int offset = 0, colorCnt = 0; | |
while (!endReq){ | |
for (unsigned int i = 0; i < length; i++){ | |
// 色を変える | |
printf("\033[%sm", colors[colorCnt]); | |
printf("%c", string[(i + offset) % length]); | |
} | |
fflush(stdout); | |
printf("\r"); | |
offset = (offset % length == 0 && offset > 0) ? 0 : offset + 1; | |
colorCnt = (colorCnt >= 4) ? 0 : colorCnt + 1; | |
usleep(100E+3); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment