Cześć!
Mam na zadanie napisać program w C, który wyświetli godzinę w konsoli.
Aktualnie godzina jest symulowana.
Moją gorącą proźbą jest to, abyście rzucili okiem na kod i go ocenili.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <stdarg.h>
#define WIDTH 20
#define HEIGHT 20
typedef struct map_t{
int width, height;
char data[];
} MAP;
#define ABS(x) ( (x) < 0 ? (-(x)) : (x) )
#define ASSERT(x) \
if(!(x)){ \
fprintf(stderr, "%s:%d ERROR %s\n", __FUNCTION__, __LINE__, #x); \
exit(-1); \
}
void map_set(struct map_t * map, int x, int y, char v){
ASSERT(x < map->width && y < map->height);
map->data[x + map->width * y] = v;
}
char map_get(const struct map_t * map, int x, int y){
ASSERT(x < map->width && y < map->height);
return map->data[x + map->width * y];
}
void map_clear(struct map_t * map){
memset(map->data, ' ', map->width * map->height);
}
struct map_t * map_alloc(int width, int height){
struct map_t * map = (struct map_t*) malloc(sizeof(struct map_t) + width * height);
map->width = width;
map->height = height;
return map;
}
void map_print(const struct map_t * map){
int x, y;
for(y=0; y<map->height; ++y){
for(x=0; x<map->width; ++x)
putchar(map_get(map, x, y));
printf("\n");
}
fflush(stdout);
}
void map_draw_line(struct map_t * map, int x1, int y1, int x2, int y2, char v){
int dx = x2 - x1;
int dy = y2 - y1;
int dl = ABS(ABS(dx) > ABS(dy) ? dx : dy);
int i;
for(i=0; i<dl; ++i)
map_set(map, round(x1 + (float)dx*i/dl), round(y1 + (float)dy*i/dl), v);
}
void map_puts(struct map_t * map, int x, int y, const char * str){
while(*str)
map_set(map, x++, y, *str++);
}
void map_printf(struct map_t * map, int x, int y, const char * fmt, ...){
char text[64];
va_list ap;
va_start(ap, fmt);
vsnprintf(text, sizeof(text), fmt, ap);
va_end(ap);
map_puts(map, x, y, text);
}
// test
void draw_clock(struct map_t * map, int hour, int minut, int second){
int cx = map->width/2;
int cy = map->height/2;
int d = cx > cy ? cy : cx;
int x, y, i;
for(i=0; i<12; ++i)
map_printf(
map,
cx + 0.9*d*sin(2*M_PI*i/12.),
cy - 0.9*d*cos(2*M_PI*i/12.),
"%d", i == 0 ? 12 : i
);
map_draw_line(
map,
cx,
cy,
round(cx + 0.3*d*sin(2*M_PI * hour / 12.)),
round(cy - 0.3*d*cos(2*M_PI * hour / 12.)),
'#'
);
map_draw_line(
map,
cx,
cy,
round(cx + 0.6*d*sin(2*M_PI * minut / 60.)),
round(cy - 0.6*d*cos(2*M_PI * minut / 60.)),
'*'
);
map_draw_line(
map,
cx,
cy,
round(cx + 0.8*d*sin(2*M_PI * second / 60.)),
round(cy - 0.8*d*cos(2*M_PI * second / 60.)),
'.'
);
}
int main(){
int i;
MAP * map = map_alloc(WIDTH, HEIGHT);
map_clear(map);
// test
for(i=0; i<60*60; ++i){
map_clear(map);
draw_clock(map, 3 + i / 60 / 60, (i / 60) % 60, i % 60);
map_print(map);
usleep(1000*10);
}
free(map);
return 0;
}
Wszystkie uwagi mile widziane,
Dzięki!