Skip to content

Instantly share code, notes, and snippets.

@soyoil
Created July 9, 2021 06:29
Show Gist options
  • Save soyoil/07bf767c13711f003a2636c48a74d802 to your computer and use it in GitHub Desktop.
Save soyoil/07bf767c13711f003a2636c48a74d802 to your computer and use it in GitHub Desktop.
Cによるアナログ時計
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SIZE 40
void set(char *buf, int x, int y, char c) {
x += SIZE;
y += SIZE / 2;
buf[x + y * (SIZE + 1) * 2] = c;
}
void draw(const char *buf) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j <= SIZE * 2; j++) {
putchar(buf[i * (SIZE + 1) * 2 + j]);
}
putchar('\n');
}
}
int aboutCompare(double a, double b, int w) {
return -w <= a - b && a - b <= w;
}
int orthant(double x, double y) {
if (x >= 0) {
if (y > 0)
return 1;
else
return 2;
} else {
if (y >= 0)
return 4;
else
return 3;
}
}
void build(char *canvas, int hour, int minute, int second) {
int xs = (SIZE * 2) * cos(second * M_PI / 30.0 - M_PI_2) * 0.45;
int ys = SIZE * sin(second * M_PI / 30.0 - M_PI_2) * 0.45;
int xm = (SIZE * 2) * cos((60 * minute + second) * M_PI / 1800.0 - M_PI_2) * 0.4;
int ym = SIZE * sin((60 * minute + second) * M_PI / 1800.0 - M_PI_2) * 0.4;
int xh = (SIZE * 2) * cos((3600 * hour + 60 * minute + second) * M_PI / 21600.0 - M_PI_2) * 0.25;
int yh = SIZE * sin((3600 * hour + 60 * minute + second) * M_PI / 21600.0 - M_PI_2) * 0.25;
for (int y = SIZE / 2; y > -SIZE / 2; y--) {
for (int x = -SIZE; x <= SIZE; x++) {
// outline
if ((int)(pow((double)x / SIZE, 2) + pow((double)y * 2 / SIZE, 2)) == 1) {
set(canvas, x, y, 'o');
continue;
}
// hour
if (aboutCompare(xh * y, yh * x, 17) && orthant(x, y) == orthant(xh, yh) && abs(x) <= abs(xh) && abs(y) <= abs(yh)) {
set(canvas, x, y, 'h');
continue;
}
// minute
if (aboutCompare(xm * y, ym * x, 12) && orthant(x, y) == orthant(xm, ym) && abs(x) <= abs(xm) && abs(y) <= abs(ym)) {
set(canvas, x, y, 'm');
continue;
}
// second
if (aboutCompare(xs * y, ys * x, 10) && orthant(x, y) == orthant(xs, ys) && abs(x) <= abs(xs) && abs(y) <= abs(ys)) {
set(canvas, x, y, 's');
continue;
}
// axis
if (x == 0) set(canvas, x, y, '|');
if (y == 0) set(canvas, x, y, '-');
}
}
set(canvas, 0, 0, '@');
}
int main(void) {
char *canvas = (char *)malloc(SIZE * (SIZE + 1) * 2);
memset(canvas, ' ', SIZE * (SIZE + 1) * 2);
build(canvas, 7, 22, 53);
draw(canvas);
free(canvas);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment