2024-12-13 18:06:49 +01:00

136 lines
3.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
// #include <termios.h>
// #include <fcntl.h>
#ifdef __linux__
#include "kbhit_linux.h"
#elif _WIN32
#include <windows.h>
#include <conio.h>
#endif
#define GRID_GROESSE_X 200
#define GRID_GROESSE_Y 60
#define SLEEP_TIME 10000
/*
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
*/
void print_at(int x, int y, char c[4])
{
printf("\033[%d;%dH%s", y, x, c);
}
void print_grid(char **grid){
for (int i = 0; i < GRID_GROESSE_Y; i++) {
for (int j = 0; j < GRID_GROESSE_X; j++) {
printf("%i", grid[i][j]);
// printf(" ");
}
printf("\n");
}
}
char print_pipe(int *x, int *y, int x_max, int y_max, int length, char direction, char direction_old){
bool start = true;
for(int i = 0; i < length; i++){
if (start && direction != direction_old){
switch (direction_old){
case 0: *y -= 1; if (*y <= 0){ *y = y_max; } break; // up
case 1: *y += 1; if (*y >= y_max){ *y = 0; } break; // down
case 2: *x -= 1; if (*x <= 0){ *x = x_max; } break; // left
case 3: *x += 1; if (*x >= x_max){ *x = 0; } break; // rigth
}
if (direction == 2 && direction_old == 0 || direction == 1 && direction_old == 3){
print_at(*x, *y, "");
} else if (direction == 0 && direction_old == 2 || direction == 3 && direction_old == 1) {
print_at(*x, *y, "");
} else if (direction == 3 && direction_old == 0 || direction == 1 && direction_old == 2) {
print_at(*x, *y, "");
} else if (direction == 0 && direction_old == 3 || direction == 2 && direction_old == 1) {
print_at(*x, *y, "");
} // else { printf("\nd = %i | d_o = %i\n", direction, direction_old); }
start = false;
} else {
switch (direction){
case 0: *y -= 1; if (*y <= 0){ *y = y_max; } break; // up
case 1: *y += 1; if (*y >= y_max){ *y = 0; } break; // down
case 2: *x -= 1; if (*x <= 0){ *x = x_max; } break; // left
case 3: *x += 1; if (*x >= x_max){ *x = 0; } break; // rigth
}
if (direction <= 1) {
print_at(*x, *y, "");
} else {
print_at(*x, *y, "");
}
}
fflush(stdout);
usleep(SLEEP_TIME);
}
return direction;
}
int randome(int max){
return rand() % max;
}
void clear_terminal2(){
printf("\e[1;1H\e[2J");
}
int pipes_2(int width, int height){
int x_max = width;
int y_max =height;
int x = width / 2;
int y = height / 2;
char direction_old = 0;
int start_time = 0;
srand(time(0));
while(!kbhit()){
if (start_time + 20 <= time(0)){
clear_terminal2();
start_time = time(0);
}
direction_old = print_pipe(&x, &y, x_max, y_max, randome(height / 2), randome(4), direction_old);
}
// ist dazu da um "\n" aus dem buffer zu entfernen!
getchar();
return 0;
}