From 2e33bf65621b6ae22e88dae6e1053a6f59786172 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 21 Feb 2015 12:37:48 +0000 Subject: scanf.c --- scanf.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 scanf.c diff --git a/scanf.c b/scanf.c new file mode 100644 index 0000000..67fdc9b --- /dev/null +++ b/scanf.c @@ -0,0 +1,13 @@ +#include +#include + +int main(void) +{ + char *input; + scanf("%ms", &input); + + printf("%s", input); + free(input); + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From 5881b8c79e89742a7ea6f9d1716b7e63fbe5686a Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 21 Feb 2015 12:44:47 +0000 Subject: strcmp.c --- strcmp.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 strcmp.c diff --git a/strcmp.c b/strcmp.c new file mode 100644 index 0000000..7633d80 --- /dev/null +++ b/strcmp.c @@ -0,0 +1,19 @@ +#include +#include +#include + +int main(void) +{ + char *input; + + scanf("%ms", &input); + + if (strcmp(input, "Test") == 0) + printf("Match\n"); + else + printf("Fail\n"); + + free(input); + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From c3ab178996b6ee87b8358d5cfe48807789b0483d Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 21 Feb 2015 12:45:14 +0000 Subject: scanf.c: style --- scanf.c | 1 + 1 file changed, 1 insertion(+) diff --git a/scanf.c b/scanf.c index 67fdc9b..80577f6 100644 --- a/scanf.c +++ b/scanf.c @@ -4,6 +4,7 @@ int main(void) { char *input; + scanf("%ms", &input); printf("%s", input); -- cgit v1.2.3-54-g00ecf From d52c2a2c319ff866906f5072cc5730bf05e4bf35 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 9 Mar 2015 13:02:08 +0000 Subject: Update makefile to better standards and practices. Makefile now installs to /usr/local/bin by default. Makefile now uses lower-case bindir and prefix. Makefile name changed from makefile to Makefile. Added DEBUG mode with alternate CFLAGS to makefile. LDLIBS can now be used to specify link libraries. Removed redundant target which now uses implicit target. --- Makefile | 33 +++++++++++++++++++++++++++++++++ makefile | 27 --------------------------- 2 files changed, 33 insertions(+), 27 deletions(-) create mode 100644 Makefile delete mode 100644 makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1d6edc4 --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +CFLAGS = -std=gnu11 -Wall -Wextra +LDFLAGS = -Wl,--as-needed + +ifeq ($(DEBUG), 1) + CFLAGS += -Og -g +else + CFLAGS += -O2 +endif + +INSTALL = install -m755 + +prefix = /usr/local +bindir = $(prefix)/bin + +all: + @echo 'Error, target not specified.' + @echo ' To compile .c `make `' + @echo ' To install `make target= install`' + @echo ' To uninstall `make target= uninstall`' + + +$(DESTDIR)$(bindir)/%: % + $(INSTALL) $^ $(DESTDIR)$(bindir) + +install: $(DESTDIR)$(bindir)/$(target) + +uninstall: + $(RM) "$(DESTDIR)$(bindir)/$(target)" + +clean: + find . -mindepth 1 -maxdepth 1 -executable -type f ! -name "prefix_header" -delete + +.PHONY : all install uninstall clean diff --git a/makefile b/makefile deleted file mode 100644 index 4bffe01..0000000 --- a/makefile +++ /dev/null @@ -1,27 +0,0 @@ -CFLAGS = -Wall -Wextra -Wpedantic -O2 -std=gnu11 - -PREFIX = /usr -BINDIR = /bin -INSPATH = $(DESTDIR)$(PREFIX)$(BINDIR) - -.PHONY : all install uninstall - -all: - @echo 'Error, target not specified.' - @echo ' To compile .c `make `' - @echo ' To install `make target= install`' - @echo ' To uninstall `make target= uninstall`' - -% : %.c - $(CC) $(CFLAGS) -o $@ $^ - -$(DESTDIR)$(PREFIX)$(BINDIR)/% : % - install -Dm755 "$^" "$@" - -install : $(DESTDIR)$(PREFIX)$(BINDIR)/$(target) - -uninstall : - rm "$(DESTDIR)$(PREFIX)$(BINDIR)/$(target)" - -clean : - find . -mindepth 1 -maxdepth 1 -executable -type f ! -name "prefix_header" -delete -- cgit v1.2.3-54-g00ecf From 382d2d431d1f2080d9dae9baadaa00495d903c24 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 9 Mar 2015 13:07:01 +0000 Subject: Minor modifications and new file endianness.c --- endianness.c | 23 +++++++++++++++++++++++ randtest.c | 47 +++++++++++++++++++++++++++++------------------ 2 files changed, 52 insertions(+), 18 deletions(-) create mode 100644 endianness.c diff --git a/endianness.c b/endianness.c new file mode 100644 index 0000000..c893be2 --- /dev/null +++ b/endianness.c @@ -0,0 +1,23 @@ +#include +#include +#include +#include + +int main(void) +{ + bool big_endian; + + union { + uint32_t i; + char c[4]; + } test = {0x01020304}; + + big_endian = test.c[0] == 1; + + if (big_endian) + printf("%s\n", "Big Endian"); + else + printf("%s\n", "Small Endian"); + + return EXIT_SUCCESS; +} diff --git a/randtest.c b/randtest.c index 06a71de..544fc88 100644 --- a/randtest.c +++ b/randtest.c @@ -8,28 +8,39 @@ int8_t randrange(int8_t from, int8_t to) { - int base_random = rand(); - if (RAND_MAX == base_random) return randrange(from, to); - int range = to - from, - remainder = RAND_MAX % range, - bucket = RAND_MAX / range; - if (base_random < RAND_MAX - remainder) { - return from + base_random/bucket; - } else { - return randrange(from, to); - } + int base_random = rand(); + if (RAND_MAX == base_random) return randrange(from, to); + int range = to - from, + remainder = RAND_MAX % range, + bucket = RAND_MAX / range; + if (base_random < RAND_MAX - remainder) { + return from + base_random/bucket; + } else { + return randrange(from, to); + } +} + + +static unsigned rand_to_max(unsigned max) +{ + double random; + + while ((random = rand()) == (double)RAND_MAX); + + return random / (double)RAND_MAX * (double)(max + 1); } int main(int argc, char **argv) { - srand(time(NULL)); - int r; - uint16_t *amounts = calloc(sizeof(uint16_t), (TO - FROM + 1)); - for (int i = 0; i < 1000; i++) - amounts[randrange(FROM, TO) - FROM]++; + srand(time(NULL)); + + uint64_t counter[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + for (int i = 0; i < 1000000; i++) + counter[rand_to_max(9)]++; - for (int i = 0; i < TO - FROM + 1; i++) - printf("%d: %d\n", i, amounts[i]); + for (int i = 0; i < 10; i++) + printf("%d: %lu\n", i, counter[i]); - return 0; + return EXIT_SUCCESS; } -- cgit v1.2.3-54-g00ecf From a4f2f13e2f2943c20bc3bce724a5cc5b63fbf79b Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 9 Mar 2015 13:07:23 +0000 Subject: timer.c no longer gives compiler warnings on incompatible format. --- timer.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/timer.c b/timer.c index 506af50..fa46885 100644 --- a/timer.c +++ b/timer.c @@ -37,11 +37,11 @@ int main(int argc, char **argv) for (int i = 1; i < argc; i++) total_seconds += get_seconds(argv[i]); - printf("Total time: %lu second(s).\nStarted at: %d\n", total_seconds, time(NULL)); + printf("Total time: %lu second(s).\nStarted at: %ld\n", total_seconds, time(NULL)); sleep(total_seconds); - printf("Ended at: %d\n", time(NULL)); + printf("Ended at: %ld\n", time(NULL)); while (1) { printf("Ring!\a\n"); -- cgit v1.2.3-54-g00ecf From 9c9a39f34a3cc66689796b11242e9fb537d4b6c7 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 15:27:10 +0000 Subject: README.md is now formatted to fit an 80 character terminal. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cad70a0..58a9f68 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ c-stuff ======= -This is simply a git repository of a directory in which I store all my small c tests and other things. Don't expect amazing things, however, some things in here (like the brainfuck to c parser) are projects that don't get their own repository because of their size. +This is simply a git repository of a directory in which I store all my +small c tests and other things. Don't expect amazing things, however, +some things in here (like the brainfuck to c parser) are projects that +don't get their own repository because of their size. -- cgit v1.2.3-54-g00ecf From 6a3895598cae5476f386f9f6976fc0475cecfafc Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 15:27:39 +0000 Subject: randtest.c no longer does something idiotic. --- randtest.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/randtest.c b/randtest.c index 544fc88..710377f 100644 --- a/randtest.c +++ b/randtest.c @@ -27,7 +27,7 @@ static unsigned rand_to_max(unsigned max) while ((random = rand()) == (double)RAND_MAX); - return random / (double)RAND_MAX * (double)(max + 1); + return random / (double)RAND_MAX * (double)max; } int main(int argc, char **argv) -- cgit v1.2.3-54-g00ecf From 614ce60ee66189eada508a0bfb9185689c09c601 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 15:27:54 +0000 Subject: snake game, link with -lncurses --- snake.c | 266 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 snake.c diff --git a/snake.c b/snake.c new file mode 100644 index 0000000..019228a --- /dev/null +++ b/snake.c @@ -0,0 +1,266 @@ +#include +#include +#include +#include +#include + +enum colorpair { + C_BLANK = 1, + C_WALL, + C_SEGMENT0, + C_SEGMENT1, + C_APPLE +}; + +enum direction { + D_UP, + D_DOWN, + D_LEFT, + D_RIGHT +}; + +enum state { + S_NORMAL, + S_WON, + S_FAIL +}; + +struct segment { + uint32_t x, y; +}; + +struct snake { + struct segment segments[UINT16_MAX]; + uint16_t head, tail; + enum direction direction; +} snake; + +struct apple { + uint32_t x, y; +}; + +struct { + struct snake snake; + struct apple apple; + uint32_t width, height; + bool running; + enum state state; +} game; + +void init_game(void); +void init_ncurses(void); +void main_loop(void); + +int main(void) +{ + init_ncurses(); + init_game(); + main_loop(); + + return EXIT_SUCCESS; +} + +void init_ncurses(void) +{ + initscr(); + cbreak(); + noecho(); + nonl(); + start_color(); + + intrflush(stdscr, FALSE); + keypad(stdscr, TRUE); + nodelay(stdscr, TRUE); + + init_pair(C_BLANK, COLOR_BLACK, COLOR_BLACK); + init_pair(C_WALL, COLOR_WHITE, COLOR_WHITE); + init_pair(C_SEGMENT0, COLOR_YELLOW, COLOR_YELLOW); + init_pair(C_SEGMENT1, COLOR_GREEN, COLOR_GREEN); + init_pair(C_APPLE, COLOR_RED, COLOR_RED); + + bkgd(COLOR_PAIR(C_BLANK)); +} + +void init_game(void) +{ + game.running = true; + game.state = S_NORMAL; + + game.snake.direction = D_UP; + + getmaxyx(stdscr, game.height, game.width); + + game.snake.head = 1; + game.snake.tail = 0; + + game.snake.segments[game.snake.tail].x = game.width / 2; + game.snake.segments[game.snake.tail].y = game.height / 2; + + game.snake.segments[game.snake.head].x = game.width / 2; + game.snake.segments[game.snake.head].y = game.height / 2 - 1; + + game.apple.x = game.width / 2; + game.apple.y = game.height / 2 + 1; +} + +void print_board(void); +void poll_input(void); +void simulate(void); + +void main_loop(void) +{ + while (true) { + poll_input(); + if (!game.running) + break; + simulate(); + if (!game.running) + break; + print_board(); + usleep(100000); + } +} + + +void print_board(void) +{ + erase(); + + for (uint16_t i = game.snake.tail; i <= game.snake.head; i++) { + chtype ch; + + if (!!(i % 2)) + ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT0); + else + ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT1); + mvaddch(game.snake.segments[i].y, game.snake.segments[i].x, ch); + } + + + mvaddch(game.apple.y, game.apple.x, ACS_BLOCK | COLOR_PAIR(C_APPLE)); + + refresh(); +} + +void redirect(enum direction desired_dir); + +void poll_input(void) +{ + int c; + + while ((c = getch()) != ERR) + switch (c) { + case 'h': redirect(D_LEFT); break; + case 'j': redirect(D_DOWN); break; + case 'k': redirect(D_UP); break; + case 'l': redirect(D_RIGHT); break; + case 'q': game.running = false; break; + } +} + +void redirect(enum direction desired_dir) +{ + struct segment *current = &game.snake.segments[game.snake.head]; + struct segment *previous = &game.snake.segments[game.snake.head - 1]; + + if (desired_dir == game.snake.direction) + return; + + if (current->x == previous->x) + if (current->y > previous->y) { + if (desired_dir == D_UP) + return; + } else { + if (desired_dir == D_DOWN) + return; + } + else if (current->y == previous->y) + if (current->x > previous->x) { + if (desired_dir == D_LEFT) + return; + } else { + if (desired_dir == D_RIGHT) + return; + } + + game.snake.direction = desired_dir; +} + +inline uint16_t rand_to_max(uint16_t max) +{ + double random; + + while ((random = rand()) == (double)RAND_MAX); + return random / (double)RAND_MAX * (double)max; +} + +bool part_of_snake(uint16_t x, uint16_t y); + +void replace_apple(void) +{ + uint16_t x, y; + + while (true) { + x = rand_to_max(game.width); + y = rand_to_max(game.height); + + if (part_of_snake(x, y)) + continue; + + game.apple.x = x; + game.apple.y = y; + + break; + } +} + +void simulate(void) +{ + struct segment *current = &game.snake.segments[game.snake.head]; + int64_t dx = 0, dy = 0, nx, ny; + + switch (game.snake.direction) { + case D_UP: dy = -1; break; + case D_DOWN: dy = 1; break; + case D_LEFT: dx = -1; break; + case D_RIGHT: dx = 1; break; + } + + nx = (int64_t)current->x + dx; + ny = (int64_t)current->y + dy; + + if (nx < 0 || nx >= game.width || ny < 0 || ny >= game.height) { + game.running = false; + game.state = S_FAIL; + return; + } + + if (nx == game.apple.x && ny == game.apple.y) { + game.snake.head++; + game.snake.segments[game.snake.head].x = nx; + game.snake.segments[game.snake.head].y = ny; + + replace_apple(); + return; + } + + if (part_of_snake(nx, ny)) { + game.running = false; + game.state = S_FAIL; + return; + } + + game.snake.head++; + game.snake.segments[game.snake.head].x = nx; + game.snake.segments[game.snake.head].y = ny; + game.snake.tail++; +} + +bool part_of_snake(uint16_t x, uint16_t y) +{ + for (uint16_t i = game.snake.tail; i != game.snake.head; i++) + if (game.snake.segments[i].x == x && game.snake.segments[i].y == y) + return true; + + return false; +} -- cgit v1.2.3-54-g00ecf From efc20a224bb3f9e7636d391296ca9f8c8f371b01 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 15:28:29 +0000 Subject: ncurses_windows: testing a box with max size which always fits in root window. --- ncurses_windows.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 ncurses_windows.c diff --git a/ncurses_windows.c b/ncurses_windows.c new file mode 100644 index 0000000..702aa27 --- /dev/null +++ b/ncurses_windows.c @@ -0,0 +1,57 @@ +// -*- compile-command: "make LDLIBS=-lncurses ncurses_windows" -*- +#include +#include +#include +#include + +#define WIDTH 20 +#define HEIGHT 10 + +int main(void) +{ + WINDOW *box; + int c; + + initscr(); + cbreak(); + noecho(); + nonl(); + intrflush(stdscr, FALSE); + keypad(stdscr, TRUE); + start_color(); + + init_pair(1, COLOR_WHITE, COLOR_BLUE); + init_pair(2, COLOR_WHITE, COLOR_RED); + + box = derwin(stdscr, 10, 10, 10, 10); + + bkgd(COLOR_PAIR(1)); + wbkgd(box, COLOR_PAIR(2)); + + while ((c = getch()) != EOF) { + if (c == KEY_RESIZE) { + int x, y, width, height; + + erase(); + + getmaxyx(stdscr, y, x); + + width = x < WIDTH ? x : WIDTH; + height = y < HEIGHT ? y : HEIGHT; + + wresize(box, height, width); + + mvderwin(box, (y - height) / 2, (x - width) / 2); + + bkgd(COLOR_PAIR(1)); + + wbkgd(box, COLOR_PAIR(2)); + + box(box, 0, 0); + + refresh(); + } + } + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From 6e04d4bb23075ccb35649efd886ba4a3a425f9c7 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 15:39:33 +0000 Subject: snake.c: removed prototypes and git add snake.c --- snake.c | 97 ++++++++++++++++++++++++++++------------------------------------- 1 file changed, 42 insertions(+), 55 deletions(-) diff --git a/snake.c b/snake.c index 019228a..bda1c1d 100644 --- a/snake.c +++ b/snake.c @@ -47,19 +47,6 @@ struct { enum state state; } game; -void init_game(void); -void init_ncurses(void); -void main_loop(void); - -int main(void) -{ - init_ncurses(); - init_game(); - main_loop(); - - return EXIT_SUCCESS; -} - void init_ncurses(void) { initscr(); @@ -103,25 +90,6 @@ void init_game(void) game.apple.y = game.height / 2 + 1; } -void print_board(void); -void poll_input(void); -void simulate(void); - -void main_loop(void) -{ - while (true) { - poll_input(); - if (!game.running) - break; - simulate(); - if (!game.running) - break; - print_board(); - usleep(100000); - } -} - - void print_board(void) { erase(); @@ -129,7 +97,7 @@ void print_board(void) for (uint16_t i = game.snake.tail; i <= game.snake.head; i++) { chtype ch; - if (!!(i % 2)) + if (i % 2) ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT0); else ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT1); @@ -142,22 +110,6 @@ void print_board(void) refresh(); } -void redirect(enum direction desired_dir); - -void poll_input(void) -{ - int c; - - while ((c = getch()) != ERR) - switch (c) { - case 'h': redirect(D_LEFT); break; - case 'j': redirect(D_DOWN); break; - case 'k': redirect(D_UP); break; - case 'l': redirect(D_RIGHT); break; - case 'q': game.running = false; break; - } -} - void redirect(enum direction desired_dir) { struct segment *current = &game.snake.segments[game.snake.head]; @@ -186,6 +138,20 @@ void redirect(enum direction desired_dir) game.snake.direction = desired_dir; } +void poll_input(void) +{ + int c; + + while ((c = getch()) != ERR) + switch (c) { + case 'h': redirect(D_LEFT); break; + case 'j': redirect(D_DOWN); break; + case 'k': redirect(D_UP); break; + case 'l': redirect(D_RIGHT); break; + case 'q': game.running = false; break; + } +} + inline uint16_t rand_to_max(uint16_t max) { double random; @@ -194,7 +160,14 @@ inline uint16_t rand_to_max(uint16_t max) return random / (double)RAND_MAX * (double)max; } -bool part_of_snake(uint16_t x, uint16_t y); +bool part_of_snake(uint16_t x, uint16_t y) +{ + for (uint16_t i = game.snake.tail; i != game.snake.head; i++) + if (game.snake.segments[i].x == x && game.snake.segments[i].y == y) + return true; + + return false; +} void replace_apple(void) { @@ -256,11 +229,25 @@ void simulate(void) game.snake.tail++; } -bool part_of_snake(uint16_t x, uint16_t y) +void main_loop(void) { - for (uint16_t i = game.snake.tail; i != game.snake.head; i++) - if (game.snake.segments[i].x == x && game.snake.segments[i].y == y) - return true; + while (true) { + poll_input(); + if (!game.running) + break; + simulate(); + if (!game.running) + break; + print_board(); + usleep(100000); + } +} - return false; +int main(void) +{ + init_ncurses(); + init_game(); + main_loop(); + + return EXIT_SUCCESS; } -- cgit v1.2.3-54-g00ecf From 269f812561a39e085cc33e864b82e631d8edbb87 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 23:36:32 +0000 Subject: snake.c: Visual enhancements and argument parsing. --- snake.c | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 92 insertions(+), 15 deletions(-) diff --git a/snake.c b/snake.c index bda1c1d..50adaed 100644 --- a/snake.c +++ b/snake.c @@ -1,9 +1,24 @@ +/* + * A simple implementation of the snake game. + * Compile with: `make LDLIBS=-lncurses snake' + * + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include #include #include #include #include #include +#define USEC_SECOND 1000000 + enum colorpair { C_BLANK = 1, C_WALL, @@ -33,7 +48,7 @@ struct snake { struct segment segments[UINT16_MAX]; uint16_t head, tail; enum direction direction; -} snake; +}; struct apple { uint32_t x, y; @@ -45,12 +60,22 @@ struct { uint32_t width, height; bool running; enum state state; + bool alternate_color; } game; +struct arguments { + useconds_t delay; + uint16_t desired_width, desired_height; + bool alternate_color; +} arguments; + +const char *argp_program_version = "1.0rc1"; +const char *argp_program_bug_address = ""; + void init_ncurses(void) { - initscr(); cbreak(); + initscr(); noecho(); nonl(); start_color(); @@ -97,7 +122,7 @@ void print_board(void) for (uint16_t i = game.snake.tail; i <= game.snake.head; i++) { chtype ch; - if (i % 2) + if ((i - game.snake.head * !arguments.alternate_color) % 2) ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT0); else ch = ACS_BLOCK | COLOR_PAIR(C_SEGMENT1); @@ -160,7 +185,7 @@ inline uint16_t rand_to_max(uint16_t max) return random / (double)RAND_MAX * (double)max; } -bool part_of_snake(uint16_t x, uint16_t y) +inline bool part_of_snake(uint16_t x, uint16_t y) { for (uint16_t i = game.snake.tail; i != game.snake.head; i++) if (game.snake.segments[i].x == x && game.snake.segments[i].y == y) @@ -189,7 +214,8 @@ void replace_apple(void) void simulate(void) { - struct segment *current = &game.snake.segments[game.snake.head]; + struct segment *head = &game.snake.segments[game.snake.head]; + struct segment *tail = &game.snake.segments[game.snake.tail]; int64_t dx = 0, dy = 0, nx, ny; switch (game.snake.direction) { @@ -199,8 +225,8 @@ void simulate(void) case D_RIGHT: dx = 1; break; } - nx = (int64_t)current->x + dx; - ny = (int64_t)current->y + dy; + nx = (int64_t)head->x + dx; + ny = (int64_t)head->y + dy; if (nx < 0 || nx >= game.width || ny < 0 || ny >= game.height) { game.running = false; @@ -217,7 +243,7 @@ void simulate(void) return; } - if (part_of_snake(nx, ny)) { + if (part_of_snake(nx, ny) && !(tail->x == nx && tail->y == ny)) { game.running = false; game.state = S_FAIL; return; @@ -226,28 +252,79 @@ void simulate(void) game.snake.head++; game.snake.segments[game.snake.head].x = nx; game.snake.segments[game.snake.head].y = ny; + game.snake.tail++; } void main_loop(void) { - while (true) { + print_board(); + poll_input(); + + while (game.running) { + usleep(arguments.delay); poll_input(); - if (!game.running) - break; simulate(); - if (!game.running) - break; print_board(); - usleep(100000); } } -int main(void) +error_t parse_arg(int key, char *arg, struct argp_state *state) +{ + struct arguments *arguments = state->input; + + switch (key) { + case 'w': + fprintf(stderr, "Width setting is not yet implemented.\n"); + arguments->desired_width = strtol(arg, NULL, 10); + break; + case 'h': + fprintf(stderr, "Height setting is not yet implemented.\n"); + arguments->desired_height = strtol(arg, NULL, 10); + break; + case 'a': + arguments->alternate_color = true; + break; + case 'd': + arguments->delay = strtod(arg, NULL) * (double)USEC_SECOND; + break; + default: + return ARGP_ERR_UNKNOWN; + } + + return 0; +} + +void parse_args(int argc, char **argv) +{ + char *doc = "An ncurses implementation of snake in c."; + + struct argp_option options[] = { + {"width", 'w', "", 0, "Desired width.", 0}, + {"height", 'h', "", 0, "Desired height.", 0}, + {"alternate", 'a', NULL, 0, "Alternate snake colour.", 0}, + {"delay", 'd', "", 0, "Delay between ticks in seconds. (default: 0.1)", 0}, + {0} + }; + + struct argp argp = {options, parse_arg, NULL, doc, NULL, NULL, NULL}; + + arguments.desired_width = 0; + arguments.desired_height = 0; + arguments.alternate_color = false; + arguments.delay = (double)USEC_SECOND * 0.1; + + argp_parse(&argp, argc, argv, 0, 0, &arguments); +} + +int main(int argc, char **argv) { + parse_args(argc, argv); init_ncurses(); init_game(); + main_loop(); + endwin(); return EXIT_SUCCESS; } -- cgit v1.2.3-54-g00ecf From bfd19395defe94e3eeb12a31af4656b12fb0e3d3 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 22 Mar 2015 23:40:44 +0000 Subject: snake.c: Additional braces to silence warnings. --- snake.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/snake.c b/snake.c index 50adaed..ee290ed 100644 --- a/snake.c +++ b/snake.c @@ -143,7 +143,7 @@ void redirect(enum direction desired_dir) if (desired_dir == game.snake.direction) return; - if (current->x == previous->x) + if (current->x == previous->x) { if (current->y > previous->y) { if (desired_dir == D_UP) return; @@ -151,7 +151,7 @@ void redirect(enum direction desired_dir) if (desired_dir == D_DOWN) return; } - else if (current->y == previous->y) + } else if (current->y == previous->y) { if (current->x > previous->x) { if (desired_dir == D_LEFT) return; @@ -159,6 +159,7 @@ void redirect(enum direction desired_dir) if (desired_dir == D_RIGHT) return; } + } game.snake.direction = desired_dir; } -- cgit v1.2.3-54-g00ecf From 804b114e5547b6a054bdc5ee860911d1107f9104 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Mar 2015 18:04:47 +0200 Subject: Moved simplx to its own project. --- simple_x.c | 83 -------------------------------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 simple_x.c diff --git a/simple_x.c b/simple_x.c deleted file mode 100644 index 98ddbbe..0000000 --- a/simple_x.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SimplX - Proposed name if not taken already. - * - * Copyright (C) 2014 Tomasz Kramkowski - * - * This program is free software. It is licensed under version 3 of the - * GNU General Public License. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see [http://www.gnu.org/licenses/]. - */ -#include -#include -#include - -/* - * TODO: Figure out the alignment of these things fix the arrangement. - * Find a good name for this. - */ -typedef struct sx_gc { - /*struct {*/ - xcb_connection_t *connection; - xcb_screen_t *screen; - xcb_drawable_t window; - xcb_pixmap_t pixmap; - xcb_image_t *image; - xcb_gcontext_t gc; - /*} xcb;*/ -} SX; - -SX *sx_new_gc(uint16_t width, uint16_t height) -{ - SX *sx = malloc(sizeof(SX)); - - sx->connection = xcb_connect(NULL, NULL); - - sx->screen = xcb_setup_roots_iterator(xcb_get_setup(sx->connection)).data; - - uint32_t mask = XCB_CW_BACK_PIXEL; /* Needs events */ - uint32_t values[] = {sx->screen->black_pixel}; - - sx->window = xcb_generate_id(sx->connection); - xcb_create_window(sx->connection, - 24, - sx->window, - sx->screen->root, - 0, 0, - width, height, - 1, - XCB_WINDOW_CLASS_INPUT_OUTPUT, - sx->screen->root_visual, - mask, values); - - sx->pixmap = xcb_generate_id(sx->connection); - xcb_create_pixmap(sx->connection, - 24, - sx->pixmap, - sx->window, - width, height); - - uint8_t *img = malloc(width * height * 4); - xcb_image_t *image = xcb_image_create(width, height, - XCB_IMAGE_FORMAT_Z_PIXMAP, - 8, 24, 32, - 0, - XCB_IMAGE_ORDER_MSB_FIRST, - XCB_IMAGE_ORDER_LSB_FIRST, - img, - width * height * 4, - img); - - mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND; - values[0] = sx->screen->black_pixel; - values[1] = 0xFFFFFF; - - sx->gc = xcb_generate_id(sx->connection); - xcb_create_gc(sx->connection, - sx->gc, - sx->pixmap, - mask, values); - - return sx; -} -- cgit v1.2.3-54-g00ecf From 073eba1b7a55f58bd0aede785495db8b231c773a Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Mar 2015 18:05:01 +0200 Subject: Formatting old source. --- xcb_colormaps.c | 313 +++++++++++++++++++++++++++-------------------------- xcb_imagereading.c | 126 ++++++++++----------- 2 files changed, 221 insertions(+), 218 deletions(-) diff --git a/xcb_colormaps.c b/xcb_colormaps.c index 1aacea0..f417fdc 100644 --- a/xcb_colormaps.c +++ b/xcb_colormaps.c @@ -22,174 +22,175 @@ void perlin(uint8_t * const, uint16_t, uint16_t); int main(int arg, char **argv) { - srand(time(NULL)); - xcb_connection_t *connection = xcb_connect(NULL, NULL); - - xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; - - xcb_colormap_t colormap = screen->default_colormap; - - xcb_drawable_t window = xcb_generate_id(connection); - uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; - uint32_t values[] = {screen->black_pixel, XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS}; - xcb_create_window(connection, - /*screen->root_depth,*/ - 24, - window, - screen->root, - 0, 0, - WIDTH, HEIGHT, - 1, - XCB_WINDOW_CLASS_INPUT_OUTPUT, - screen->root_visual, - mask, values); - - xcb_pixmap_t pixmap = xcb_generate_id(connection); - xcb_create_pixmap(connection, - 24, - pixmap, - window, - WIDTH, HEIGHT); - - uint8_t *img = malloc(WIDTH * HEIGHT * 4); - - uint8_t *limg = img; - /*for (int y = 0; y < HEIGHT; y++)*/ - /*for (int x = 0; x < WIDTH; x++) {*/ - /**(limg++) = 128;*/ - /**(limg++) = 128;*/ - /**(limg++) = 128;*/ - /*limg++;*/ - /*}*/ - perlin(img, WIDTH, HEIGHT); - - xcb_image_t *image = xcb_image_create(WIDTH, HEIGHT, - XCB_IMAGE_FORMAT_Z_PIXMAP, - 8, 24, 32, - 0, - /*xcb_get_setup(connection)->image_byte_order,*/ - XCB_IMAGE_ORDER_MSB_FIRST, - XCB_IMAGE_ORDER_LSB_FIRST, - img, - WIDTH * HEIGHT * 4, - img); - - xcb_gcontext_t gc = xcb_generate_id(connection); - xcb_create_gc(connection, - gc, - pixmap, - 0, NULL); - - xcb_image_put(connection, pixmap, gc, image, 0, 0, 0); - - xif_write(image, "test.xif"); - - xcb_map_window(connection, window); - xcb_flush(connection); - - xcb_generic_event_t *event; - while ((event = xcb_wait_for_event(connection))) { - switch (event->response_type & ~0x80) { - case XCB_EXPOSE: ; - xcb_expose_event_t *expose = (xcb_expose_event_t *)event; - xcb_copy_area(connection, - pixmap, - window, - gc, - expose->x, expose->y, - expose->x, expose->y, - expose->width, expose->height); - xcb_flush(connection); - break; - case XCB_BUTTON_PRESS: - goto end; - break; - default: - break; - } - free(event); - } + srand(time(NULL)); + xcb_connection_t *connection = xcb_connect(NULL, NULL); + + xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; + + xcb_colormap_t colormap = screen->default_colormap; + + xcb_drawable_t window = xcb_generate_id(connection); + uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + uint32_t values[] = {screen->black_pixel, XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS}; + xcb_create_window(connection, + /*screen->root_depth,*/ + 24, + window, + screen->root, + 0, 0, + WIDTH, HEIGHT, + 1, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + screen->root_visual, + mask, values); + + xcb_pixmap_t pixmap = xcb_generate_id(connection); + xcb_create_pixmap(connection, + 24, + pixmap, + window, + WIDTH, HEIGHT); + + uint8_t *img = malloc(WIDTH * HEIGHT * 4); + + uint8_t *limg = img; + /*for (int y = 0; y < HEIGHT; y++)*/ + /*for (int x = 0; x < WIDTH; x++) {*/ + /**(limg++) = 128;*/ + /**(limg++) = 128;*/ + /**(limg++) = 128;*/ + /*limg++;*/ + /*}*/ + perlin(img, WIDTH, HEIGHT); + + xcb_image_t *image = xcb_image_create(WIDTH, HEIGHT, + XCB_IMAGE_FORMAT_Z_PIXMAP, + 8, 24, 32, + 0, + /*xcb_get_setup(connection)->image_byte_order,*/ + XCB_IMAGE_ORDER_MSB_FIRST, + XCB_IMAGE_ORDER_LSB_FIRST, + img, + WIDTH * HEIGHT * 4, + img); + + xcb_gcontext_t gc = xcb_generate_id(connection); + xcb_create_gc(connection, + gc, + pixmap, + 0, NULL); + + xcb_image_put(connection, pixmap, gc, image, 0, 0, 0); + + xif_write(image, "test.xif"); + + xcb_map_window(connection, window); + xcb_flush(connection); + + xcb_generic_event_t *event; + xcb_expose_event_t *expose; + while ((event = xcb_wait_for_event(connection))) { + switch (event->response_type & ~0x80) { + case XCB_EXPOSE: + expose = (xcb_expose_event_t *)event; + xcb_copy_area(connection, + pixmap, + window, + gc, + expose->x, expose->y, + expose->x, expose->y, + expose->width, expose->height); + xcb_flush(connection); + break; + case XCB_BUTTON_PRESS: + goto end; + break; + default: + break; + } + free(event); + } end: - xcb_free_pixmap(connection, pixmap); - xcb_disconnect(connection); + xcb_free_pixmap(connection, pixmap); + xcb_disconnect(connection); - xcb_image_destroy(image); + xcb_image_destroy(image); - return 0; + return 0; } int8_t randrange(int8_t from, int8_t to) { - int base_random = rand(); - if (RAND_MAX == base_random) return randrange(from, to); - int range = to - from, - remainder = RAND_MAX % range, - bucket = RAND_MAX / range; - if (base_random < RAND_MAX - remainder) { - return from + base_random/bucket; - } else { - return randrange(from, to); - } + int base_random = rand(); + if (RAND_MAX == base_random) return randrange(from, to); + int range = to - from, + remainder = RAND_MAX % range, + bucket = RAND_MAX / range; + if (base_random < RAND_MAX - remainder) { + return from + base_random/bucket; + } else { + return randrange(from, to); + } } #define lerp(t, a, b) (a + t * (b - a)) void perlin(uint8_t * const img, uint16_t width, uint16_t height) { - uint8_t *limg = img; - for (int y = 0; y < HEIGHT; y++) - for (int x = 0; x < WIDTH; x++) { - *(limg++) = 128; - *(limg++) = 128; - *(limg++) = 128; - limg++; - } - - int8_t *mipmap = malloc(sizeof(int8_t) * (2 * 2 + 4 * 4 + 8 * 8 + 16 * 16) * 4); - - int8_t *lmipmap = mipmap; - for (int s = 2; s <= 16; s*=2) - for (int x = 0; x < s * s; x++) { - *(lmipmap++) = randrange(-128 / s, 128 / s); - *(lmipmap++) = randrange(-128 / s, 128 / s); - *(lmipmap++) = randrange(-128 / s, 128 / s); - lmipmap++; - printf("S: %d X: %d Y: %d R: %d G: %d B: %d\n", s, x / s, x, *(lmipmap-4), *(lmipmap-3), *(lmipmap-2)); - }; - - limg = img; - lmipmap = mipmap; - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) - for (int bit = 0; bit < 2; bit ++) { - for (int s = 2; s <= 16; s*=2) { - size_t offset = 0; - for (int i = s / 2; i >= 2; i/=2) - offset += i * i; - lmipmap = mipmap + offset; - uint16_t xblock = width / (s - 1); - uint16_t yblock = height / (s - 1); - - uint8_t xbpos = (float)x / (float)xblock; - uint8_t ybpos = (float)y / (float)yblock; - - float xmul = (float)x / (float)width - (float)xbpos; - float ymul = (float)y / (float)height - (float)ybpos; - - int8_t valtl, valtr, valbl, valbr; - valtl = lmipmap[bit + 4 * (ybpos * s + xbpos)]; - valtr = lmipmap[bit + 4 * (ybpos * s + xbpos + 1)]; - valbl = lmipmap[bit + 4 * ((ybpos + 1) * s + xbpos)]; - valbr = lmipmap[bit + 4 * ((ybpos + 1) * s + xbpos + 1)]; - - int8_t wlerpu = lerp(xmul, valtl, valtr); - int8_t wlerpl = lerp(xmul, valbl, valbr); - - int8_t endval = lerp(ymul, wlerpl, wlerpu); - - limg[bit + 4 * (y * width + x)] = limg[bit + 4 * (y * width + x)] + endval; - } - } - free(mipmap); + uint8_t *limg = img; + for (int y = 0; y < HEIGHT; y++) + for (int x = 0; x < WIDTH; x++) { + *(limg++) = 128; + *(limg++) = 128; + *(limg++) = 128; + limg++; + } + + int8_t *mipmap = malloc(sizeof(int8_t) * (2 * 2 + 4 * 4 + 8 * 8 + 16 * 16) * 4); + + int8_t *lmipmap = mipmap; + for (int s = 2; s <= 16; s*=2) + for (int x = 0; x < s * s; x++) { + *(lmipmap++) = randrange(-128 / s, 128 / s); + *(lmipmap++) = randrange(-128 / s, 128 / s); + *(lmipmap++) = randrange(-128 / s, 128 / s); + lmipmap++; + printf("S: %d X: %d Y: %d R: %d G: %d B: %d\n", s, x / s, x, *(lmipmap-4), *(lmipmap-3), *(lmipmap-2)); + }; + + limg = img; + lmipmap = mipmap; + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) + for (int bit = 0; bit < 2; bit ++) { + for (int s = 2; s <= 16; s*=2) { + size_t offset = 0; + for (int i = s / 2; i >= 2; i/=2) + offset += i * i; + lmipmap = mipmap + offset; + uint16_t xblock = width / (s - 1); + uint16_t yblock = height / (s - 1); + + uint8_t xbpos = (float)x / (float)xblock; + uint8_t ybpos = (float)y / (float)yblock; + + float xmul = (float)x / (float)width - (float)xbpos; + float ymul = (float)y / (float)height - (float)ybpos; + + int8_t valtl, valtr, valbl, valbr; + valtl = lmipmap[bit + 4 * (ybpos * s + xbpos)]; + valtr = lmipmap[bit + 4 * (ybpos * s + xbpos + 1)]; + valbl = lmipmap[bit + 4 * ((ybpos + 1) * s + xbpos)]; + valbr = lmipmap[bit + 4 * ((ybpos + 1) * s + xbpos + 1)]; + + int8_t wlerpu = lerp(xmul, valtl, valtr); + int8_t wlerpl = lerp(xmul, valbl, valbr); + + int8_t endval = lerp(ymul, wlerpl, wlerpu); + + limg[bit + 4 * (y * width + x)] = limg[bit + 4 * (y * width + x)] + endval; + } + } + free(mipmap); } diff --git a/xcb_imagereading.c b/xcb_imagereading.c index 26e5852..4a3e18c 100644 --- a/xcb_imagereading.c +++ b/xcb_imagereading.c @@ -19,78 +19,80 @@ int main(int arg, char **argv) { - xcb_connection_t *connection = xcb_connect(NULL, NULL); + xcb_connection_t *connection = xcb_connect(NULL, NULL); - xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; + xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; - xcb_colormap_t colormap = screen->default_colormap; + xcb_colormap_t colormap = screen->default_colormap; - xcb_drawable_t window = xcb_generate_id(connection); - uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; - uint32_t values[] = {screen->black_pixel, XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS}; - xcb_create_window(connection, - /*screen->root_depth,*/ - 24, - window, - screen->root, - 0, 0, - WIDTH, HEIGHT, - 1, - XCB_WINDOW_CLASS_INPUT_OUTPUT, - screen->root_visual, - mask, values); + xcb_drawable_t window = xcb_generate_id(connection); + uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + uint32_t values[] = {screen->black_pixel, XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS}; + xcb_create_window(connection, + /*screen->root_depth,*/ + 24, + window, + screen->root, + 0, 0, + WIDTH, HEIGHT, + 1, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + screen->root_visual, + mask, values); - xcb_pixmap_t pixmap = xcb_generate_id(connection); - xcb_create_pixmap(connection, - 24, - pixmap, - window, - WIDTH, HEIGHT); - xcb_image_t *image; - if (!(image = xif_read("test.xif"))) { - fputs("Error: xif_read returned null.\n", stderr); - exit(1); - } + xcb_pixmap_t pixmap = xcb_generate_id(connection); + xcb_create_pixmap(connection, + 24, + pixmap, + window, + WIDTH, HEIGHT); + xcb_image_t *image; + if (!(image = xif_read("test.xif"))) { + fputs("Error: xif_read returned null.\n", stderr); + exit(1); + } - xcb_gcontext_t gc = xcb_generate_id(connection); - xcb_create_gc(connection, - gc, - pixmap, - 0, NULL); + xcb_gcontext_t gc = xcb_generate_id(connection); + xcb_create_gc(connection, + gc, + pixmap, + 0, NULL); - xcb_image_put(connection, pixmap, gc, image, 0, 0, 0); + xcb_image_put(connection, pixmap, gc, image, 0, 0, 0); - xcb_map_window(connection, window); - xcb_flush(connection); + xcb_map_window(connection, window); + xcb_flush(connection); - xcb_generic_event_t *event; - while ((event = xcb_wait_for_event(connection))) { - switch (event->response_type & ~0x80) { - case XCB_EXPOSE: ; - xcb_expose_event_t *expose = (xcb_expose_event_t *)event; - xcb_copy_area(connection, - pixmap, - window, - gc, - expose->x, expose->y, - expose->x, expose->y, - expose->width, expose->height); - xcb_flush(connection); - break; - case XCB_BUTTON_PRESS: - goto end; - break; - default: - break; - } - free(event); - } + xcb_generic_event_t *event; + while ((event = xcb_wait_for_event(connection))) { + switch (event->response_type & ~0x80) { + case XCB_EXPOSE: + { + xcb_expose_event_t *expose = (xcb_expose_event_t *)event; + xcb_copy_area(connection, + pixmap, + window, + gc, + expose->x, expose->y, + expose->x, expose->y, + expose->width, expose->height); + xcb_flush(connection); + break; + } + case XCB_BUTTON_PRESS: + goto end; + break; + default: + break; + } + free(event); + } end: - xcb_free_pixmap(connection, pixmap); - xcb_disconnect(connection); + xcb_free_pixmap(connection, pixmap); + xcb_disconnect(connection); - xcb_image_destroy(image); + xcb_image_destroy(image); - return 0; + return 0; } -- cgit v1.2.3-54-g00ecf From 736412ff722a4530d4b6d578aff25300544e5be5 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Mar 2015 18:05:15 +0200 Subject: Simple single function hangman. --- hangman.c | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 hangman.c diff --git a/hangman.c b/hangman.c new file mode 100644 index 0000000..65d59a6 --- /dev/null +++ b/hangman.c @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include + +#define ALPHABET_CHARS 26 +#define MAX_GUESS 5 + +enum state { + NONE, + WIN, + LOSS +}; + +int main(int argc, char **argv) +{ + bool guessed[ALPHABET_CHARS] = {0}, in_secret[ALPHABET_CHARS] = {0}; + char *secret; + int bad_guesses = 0, c; + size_t dest, length; + enum state state = NONE; + + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return EXIT_FAILURE; + } + + secret = argv[1]; + dest = 0; + length = strlen(secret); + for (size_t i = 0; i < length; i++) + if (isalpha(secret[i]) || isspace(secret[i])) + secret[dest++] = toupper(secret[i]); + + length = dest; + for (size_t i = 0; i < length; i++) + if (isalpha(secret[i])) + in_secret[secret[i] - 'A'] = true; + + printf("Hangman\n=======\n\n"); + for (size_t i = 0; i < length; i++) + if (isalpha(secret[i]) && !guessed[secret[i] - 'A']) + putchar('_'); + else + putchar(secret[i]); + putchar('\n'); + + while ((c = getchar()) != EOF) { + if (!isalpha(c)) + continue; + + c = toupper(c); + + if (guessed[c - 'A']) + continue; + + if (!in_secret[c - 'A']) { + bad_guesses++; + printf("Wrong!"); + continue; + } + + guessed[c - 'A'] = true; + + for (size_t i = 0; i < length; i++) + if (isalpha(secret[i]) && !guessed[secret[i] - 'A']) + putchar('_'); + else + putchar(secret[i]); + putchar('\n'); + + for (unsigned i = 0; i < ALPHABET_CHARS; i++) + if (in_secret[i] && !guessed[i]) + goto cont; + + state = WIN; + + break; +cont:; + if (bad_guesses > MAX_GUESS) { + state = LOSS; + break; + } + } + + switch (state) { + case WIN: + printf("You won.\n"); + break; + case LOSS: + printf("You lost, the secret word was: %s\n", secret); + break; + case NONE: + printf("Something weird happened.\n"); + break; + } +} -- cgit v1.2.3-54-g00ecf From 351527ef70b963b3c3aab1d7d0e59dc02c6c2e0f Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Mar 2015 18:06:36 +0200 Subject: Removed redundant semicolon. --- hangman.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hangman.c b/hangman.c index 65d59a6..10373e2 100644 --- a/hangman.c +++ b/hangman.c @@ -77,7 +77,7 @@ int main(int argc, char **argv) state = WIN; break; -cont:; +cont: if (bad_guesses > MAX_GUESS) { state = LOSS; break; -- cgit v1.2.3-54-g00ecf From aed3ad200d66fc502ab4759ac832cd23e6804029 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Mar 2015 18:17:14 +0200 Subject: Various fixes to hangman.c. --- hangman.c | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/hangman.c b/hangman.c index 10373e2..4cf4c16 100644 --- a/hangman.c +++ b/hangman.c @@ -53,32 +53,33 @@ int main(int argc, char **argv) c = toupper(c); if (guessed[c - 'A']) - continue; + goto print_state; if (!in_secret[c - 'A']) { bad_guesses++; - printf("Wrong!"); - continue; + printf("Wrong!\n"); + goto print_state; } guessed[c - 'A'] = true; + for (unsigned i = 0; i < ALPHABET_CHARS; i++) + if (in_secret[i] && !guessed[i]) + goto print_state; + + state = WIN; + + break; +print_state: for (size_t i = 0; i < length; i++) if (isalpha(secret[i]) && !guessed[secret[i] - 'A']) putchar('_'); else putchar(secret[i]); putchar('\n'); + printf("You have %d guesses left.\n", MAX_GUESS - bad_guesses); - for (unsigned i = 0; i < ALPHABET_CHARS; i++) - if (in_secret[i] && !guessed[i]) - goto cont; - - state = WIN; - - break; -cont: - if (bad_guesses > MAX_GUESS) { + if (bad_guesses >= MAX_GUESS) { state = LOSS; break; } -- cgit v1.2.3-54-g00ecf From 88344ddbd467e20b3f2a3ae833a6370277aa5c82 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 31 Mar 2015 14:47:29 +0200 Subject: Removed imlib2.c because of code copied from somewhere and modified README. --- README.md | 5 +- imlib2.c | 232 -------------------------------------------------------------- 2 files changed, 4 insertions(+), 233 deletions(-) delete mode 100644 imlib2.c diff --git a/README.md b/README.md index 58a9f68..a21b367 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ c-stuff ======= - This is simply a git repository of a directory in which I store all my small c tests and other things. Don't expect amazing things, however, some things in here (like the brainfuck to c parser) are projects that don't get their own repository because of their size. + +Licensing +========= +Only files with a license header are licensed under the GPLv3! The rest are unlicensed for reasons generally specified at the top of the file. diff --git a/imlib2.c b/imlib2.c deleted file mode 100644 index 4b4c72a..0000000 --- a/imlib2.c +++ /dev/null @@ -1,232 +0,0 @@ -// Imlib2 stuff which I think I copied from somewhere. - -#include -#include -#include -#include -#include - -Display *disp; -Window win; -Visual *vis; -Colormap cm; -int depth; - -int main(int argc, char **argv) -{ - XEvent ev; - - Imlib_Updates updates, current_update; - Imlib_Image buffer; - Imlib_Font font; - Imlib_Color_Range range; - int mouse_x = 0, mouse_y = 0; - - disp = XOpenDisplay(NULL); - - vis = DefaultVisual(disp, DefaultScreen(disp)); - depth = DefaultDepth(disp, DefaultScreen(disp)); - cm = DefaultColormap(disp, DefaultScreen(disp)); - - win = XCreateSimpleWindow(disp, DefaultRootWindow(disp), - 0, 0, 640, 480, 0, 0, 0); - - XSelectInput(disp, win, ButtonPressMask | ButtonReleaseMask | - PointerMotionMask | ExposureMask); - - XMapWindow(disp, win); - - imlib_set_cache_size(2048 * 1024); - - imlib_set_font_cache_size(512 * 1024); - - imlib_add_path_to_font_path("./ttfonts"); - - imlib_set_color_usage(128); - - imlib_context_set_dither(1); - - imlib_context_set_display(disp); - imlib_context_set_visual(vis); - imlib_context_set_colormap(cm); - imlib_context_set_drawable(win); - - while(true) { - Imlib_Image image; - int w, h, text_w, text_h; - - updates = imlib_updates_init(); - - do { - XNextEvent(disp, &ev); - switch (ev.type) { - case Expose: - updates = imlib_update_append_rect(updates, - ev.xexpose.x, ev.xexpose.y, - ev.xexpose.width, ev.xexpose.height); - break; - case ButtonPress: - exit(0); - break; - case MotionNotify: - image = imlib_load_image("./test_images/mush.png"); - imlib_context_set_image(image); - w = imlib_image_get_width(); - h = imlib_image_get_height(); - - imlib_context_set_image(image); - imlib_free_image(); - - updates = imlib_update_append_rect(updates, - mouse_x - (w / 2), mouse_y - (h / 2), - w, h); - font = imlib_load_font("notepad/30"); - if (font) { - char text[4096]; - imlib_context_set_font(font); - sprintf(text, "Mouse is at %i, %i", mouse_x, mouse_y); - imlib_get_text_size(text, &text_w, &text_h); - imlib_free_font(); - - updates = imlib_update_append_rect(updates, - 320 - text_w / 2, 240 - text_h / 2, - text_w, text_h); - } - - mouse_x = ev.xmotion.x; - mouse_y = ev.xmotion.y; - - updates = imlib_update_append_rect(updates, - mouse_x - w / 2, mouse_y - h / 2, - w, h); - font = imlib_load_font("notepad/30"); - if (font) { - char text[4096]; - - imlib_context_set_font(font); - sprintf(text, "Mouse is at %i, %i", mouse_x, mouse_y); - imlib_get_text_size(text, &text_w, &text_h); - imlib_free_font(); - updates = imlib_update_append_rect(updates, - 320 - text_w / 2, 240 - text_h / 2, - text_w, text_h); - } - default: - break; - } - } while (XPending(disp)); - - - updates = imlib_updates_merge_for_rendering(updates, 640, 480); - for (current_update = updates; - current_update; - current_update = imlib_updates_get_next(current_update)) { - int up_x, up_y, up_w, up_h; - - imlib_updates_get_coordinates(current_update, &up_x, &up_y, &up_w, &up_h); - - buffer = imlib_create_image(up_w, up_h); - - imlib_context_set_blend(1); - - image = imlib_load_image("./test_images/bg.png"); - - imlib_context_set_image(image); - - w = imlib_image_get_width(); - h = imlib_image_get_height(); - - imlib_context_set_image(buffer); - - if (image) { - imlib_blend_image_onto_image(image, 0, 0, 0, - w, h, -up_x, -up_y, 640, 480); - - imlib_context_set_image(image); - - imlib_free_image(); - } - - image = imlib_load_image("./test_images/mush.png"); - imlib_context_set_image(image); - w = imlib_image_get_width(); - h = imlib_image_get_height(); - imlib_context_set_image(image); - if (image) { - imlib_blend_image_onto_image(image, 0, 0, 0, w, h, - mouse_x - w / 2 - up_x, - mouse_y - h / 2 - up_y, - w, h); - imlib_context_set_image(image); - imlib_free_image(); - } - - range = imlib_create_color_range(); - imlib_context_set_color_range(range); - - imlib_context_set_color(255, 255, 255, 255); - imlib_add_color_to_color_range(0); - - imlib_context_set_color(255, 200, 10, 100); - imlib_add_color_to_color_range(10); - - imlib_context_set_color(0, 0, 0, 0); - imlib_add_color_to_color_range(20); - - imlib_context_set_image(buffer); - imlib_image_fill_color_range_rectangle(-up_x, -up_y, 128, 128, -45); - - imlib_free_color_range(); - - font = imlib_load_font("notepad/30"); - if (font) { - char text[4096]; - - imlib_context_set_font(font); - imlib_context_set_image(buffer); - imlib_context_set_color(0, 0, 0, 255); - sprintf(text, "Mouse is at %i, %i", mouse_x, mouse_y); - imlib_get_text_size(text, &text_w, &text_h); - imlib_text_draw(320 - text_w / 2 - up_x, - 240 - text_h / 2 - up_y, - text); - imlib_free_font(); - } - - imlib_context_set_blend(0); - imlib_context_set_image(buffer); - imlib_render_image_on_drawable(up_x, up_y); - imlib_free_image(); - } - if (updates) - imlib_updates_free(updates); - } - return 0; -} - - /*Imlib_Image image = imlib_create_image(640, 480);*/ - - /*imlib_context_set_image(image);*/ - - /*imlib_context_set_color(255, 255, 255, 255);*/ - - /*imlib_image_fill_rectangle(0, 0, 640, 480);*/ - - /*imlib_context_set_color(255, 128, 0, 255);*/ - - /*ImlibPolygon poly = imlib_polygon_new();*/ - - /*imlib_polygon_add_point(poly, 0, 0);*/ - /*imlib_polygon_add_point(poly, 10, 440);*/ - /*imlib_polygon_add_point(poly, 600, 10);*/ - - /*imlib_image_fill_polygon(poly);*/ - - /*imlib_polygon_free(poly);*/ - - /*imlib_save_image("imlibtest.png");*/ - - /*imlib_free_image();*/ - - /*return 0;*/ -/*}*/ -- cgit v1.2.3-54-g00ecf From cbeac6412840ea0e978f14da08c5a5e02796c7e2 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 31 Mar 2015 14:55:32 +0200 Subject: Pthreads testing. --- pthreads.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 pthreads.c diff --git a/pthreads.c b/pthreads.c new file mode 100644 index 0000000..87945fd --- /dev/null +++ b/pthreads.c @@ -0,0 +1,45 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +#define NUM_THREADS 100 + +typedef void *(* thread_func)(void *); + +void *somefunction(int *arg) +{ + int loops = rand(); + + for (int i = 0; i < loops; i++) { + pthread_yield(); + for (;i < loops; i++); + } + + printf("%d:\t%d\n", *arg, loops); + + return NULL; +} + +int main(void) +{ + srand(time(NULL)); + + pthread_t threads[NUM_THREADS]; + int args[NUM_THREADS]; + + for (int i = 0; i < NUM_THREADS; i++) { + args[i] = i; + if (pthread_create(&threads[i], NULL, (thread_func)somefunction, args + i)) + return EXIT_FAILURE; + } + + for (int i = 0; i < NUM_THREADS; i++) + if (pthread_join(threads[i], NULL)) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From e60bdf760f69760501e826957d6dac053bccede5 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Wed, 1 Apr 2015 11:29:20 +0200 Subject: Improved rot.c error. --- rot.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rot.c b/rot.c index b5b8b00..c7c6771 100644 --- a/rot.c +++ b/rot.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 Tomasz Kramkowski + * Copyright (C) 2014 - 2015 Tomasz Kramkowski * * This program is free software. It is licensed under version 3 of the * GNU General Public License. @@ -16,7 +16,7 @@ int main(int argc, char **argv) { if (argc != 3) { - printf("Incorrect number of arguments.\n"); + fprintf(stderr, "Usage: \a\n"); exit(1); } -- cgit v1.2.3-54-g00ecf From a4a0b84f2765c19eae7d270e1627f4b00fa0a99a Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Thu, 2 Apr 2015 02:23:14 +0200 Subject: Simple implementation of vigenere cipher. (offset of 1 for desired results) --- vigenere.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 vigenere.c diff --git a/vigenere.c b/vigenere.c new file mode 100644 index 0000000..8ed4a6c --- /dev/null +++ b/vigenere.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include + +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +void preprocess(char *str); + +int main(int argc, char **argv) +{ + char *key, *ciphertext, *decodepos, *decodeneg; + long offset; + size_t keylength, textlength; + + if (argc != 4) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + key = argv[1]; + offset = strtol(argv[2], NULL, 10); + ciphertext = argv[3]; + + preprocess(key); + preprocess(ciphertext); + + keylength = strlen(key); + textlength = strlen(ciphertext); + + decodepos = malloc(textlength + 1); + decodeneg = malloc(textlength + 1); + + for (size_t i = 0; i < textlength; i++) { + decodepos[i] = ITOC((CTOI(ciphertext[i]) + offset + CTOI(key[i % keylength])) % 26); + decodeneg[i] = ITOC((CTOI(ciphertext[i]) + 52 - offset - CTOI(key[i % keylength])) % 26); + } + + decodepos[textlength] = '\0'; + decodeneg[textlength] = '\0'; + + printf("+ %s\n- %s\n", decodepos, decodeneg); + + free(decodepos); + free(decodeneg); + + return EXIT_SUCCESS; +} + +void preprocess(char *str) +{ + char *src = str, *dest = str; + + while (*src != '\0') { + if (isalpha(*src)) + *(dest++) = toupper(*src); + src++; + } + + *dest = '\0'; +} -- cgit v1.2.3-54-g00ecf From 940aa9eddf6ccce7df67169a57ca2d23ce9a2977 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 3 Apr 2015 11:30:02 +0200 Subject: advigenere: addition only. --- advigenere.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 advigenere.c diff --git a/advigenere.c b/advigenere.c new file mode 100644 index 0000000..5ada41c --- /dev/null +++ b/advigenere.c @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include +#include +#include +#include + +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +void preprocess(char *str); + +int main(int argc, char **argv) +{ + char *key, *ciphertext, *decoded; + size_t keylength, textlength; + + if (argc != 3) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + ciphertext = argv[1]; + key = argv[2]; + + preprocess(key); + preprocess(ciphertext); + + keylength = strlen(key); + textlength = strlen(ciphertext); + + decoded = malloc(textlength + 1); + + for (size_t i = 0; i < textlength; i++) + decoded[i] = (CTOI(ciphertext[i]) + CTOI(key[i % keylength])) % 26; + + for (unsigned offset = 0; offset < 26; offset++) { + printf("%.2u : ", offset); + for (unsigned i = 0; i < textlength; i++) + putchar(ITOC((decoded[i] + offset) % 26)); + putchar('\n'); + } + + free(decoded); + + return EXIT_SUCCESS; +} + +void preprocess(char *str) +{ + char *src = str, *dest = str; + + while (*src != '\0') { + if (isalpha(*src)) + *(dest++) = toupper(*src); + src++; + } + + *dest = '\0'; +} -- cgit v1.2.3-54-g00ecf From f8b900badcc505af67575d17e6c59abc92961327 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 3 Apr 2015 12:00:50 +0200 Subject: foursquare: various cleanup. --- foursquare.c | 189 +++++++++++++++++++++++++++++------------------------------ vigenere.c | 8 +-- 2 files changed, 98 insertions(+), 99 deletions(-) diff --git a/foursquare.c b/foursquare.c index c5ab68c..6fc894e 100644 --- a/foursquare.c +++ b/foursquare.c @@ -14,119 +14,118 @@ #include #include #include +#include #define Q ('Q'-'A') -typedef struct vec2 { - int x; - int y; -} Vec2; +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +struct vec2 { + int x; + int y; +}; int increinc(int *); -void allupper(char *); +void preprocess(char *); void genkey(char *, char *); -Vec2 *newVec2(const int, const int); +struct vec2 *newVec2(const int, const int); int main(int argc, char **argv) { - int x, y, c=0; - - if(argc!=4){ - printf("Usage: %s ", *argv); - exit(1); - } - - printf("%s, %s ", *(argv+1), *(argv+2)); - - char *trkey = *(argv+1); - allupper(trkey); - char *trfullkey = malloc(26); - genkey(trkey, trfullkey); - - char *blkey = *(argv+2); - allupper(blkey); - char *blfullkey = malloc(26); - genkey(blkey, blfullkey); - - char *cipher = *(argv+3); - allupper(cipher); - - int i=0; - Vec2 *trtable[25]; - for(x=0; x<5; x++) - for(y=0; y<5; y++) - trtable[trfullkey[i++]-'A'] = newVec2(x, y); - free(trfullkey); - - i = 0; - Vec2 *bltable[25]; - for(x=0; x<5; x++) - for(y=0; y<5; y++) - bltable[blfullkey[i++]-'A'] = newVec2(x, y); - free(blfullkey); - - char basetable[5][5]; - for(x=0; x<5; x++) - for(y=0; y<5; y++){ - if(c==Q) - c++; - basetable[x][y] = 'A' + c++; - } - - for(i=0; ix][bltable[c2-'A']->y]); - putchar(basetable[bltable[c2-'A']->x][trtable[c1-'A']->y]); - } - putchar('\n'); - - for(i=0; i++; i<25){ - free(trtable[i]); - free(bltable[i]); - } - - return 0; + int x, y, c = 0, i; + char trfullkey[26], blfullkey[26], *trkey, *blkey, *cipher; + struct vec2 trtable[25], bltable[25]; + + if(argc!=4){ + printf("Usage: %s ", *argv); + exit(1); + } + + printf("%s, %s ", *(argv+1), *(argv+2)); + + trkey = argv[1]; + preprocess(trkey); + genkey(trkey, trfullkey); + + blkey = argv[2]; + preprocess(blkey); + genkey(blkey, blfullkey); + + cipher = argv[3]; + preprocess(cipher); + + i = 0; + for(x=0; x<5; x++) + for(y=0; y<5; y++) { + trtable[CTOI(trfullkey[i])].x = x; + trtable[CTOI(trfullkey[i])].y = y; + i++; + } + + i = 0; + for(x=0; x<5; x++) + for(y=0; y<5; y++) { + bltable[CTOI(blfullkey[i])].x = x; + bltable[CTOI(blfullkey[i])].y = y; + i++; + } + + + char basetable[5][5]; + for (x = 0; x < 5; x++) + for (y = 0; y < 5; y++){ + if (c == Q) + c++; + basetable[x][y] = 'A' + c++; + } + + for(size_t i = 0; i < strlen(cipher) / 2; i++){ + char c1 = cipher[2*i]; + char c2 = cipher[2*i+1]; + + putchar(basetable[trtable[CTOI(c1)].x][bltable[CTOI(c2)].y]); + putchar(basetable[bltable[CTOI(c2)].x][trtable[CTOI(c1)].y]); + } + putchar('\n'); + + return EXIT_SUCCESS; } -int increinc(int *num) +inline int increinc(int *num) { - (*num)++; - return (*num)++; + (*num)++; + return (*num)++; } -void allupper(char *input) +void preprocess(char *str) { - int i; - for(i=0; ix = x; - v->y = y; - return v; + for (size_t i = 0; i < strlen(input); i++) { + if (!dict[CTOI(input[i])]) { + output[ii++] = input[i]; + dict[CTOI(input[i])] = true; + } + } + + for (unsigned i = 0; i < 26; i++) + if (!dict[i] && i != Q) + output[ii++] = ITOC(i); + + output[ii]='\0'; } diff --git a/vigenere.c b/vigenere.c index 8ed4a6c..5db3e18 100644 --- a/vigenere.c +++ b/vigenere.c @@ -15,13 +15,13 @@ int main(int argc, char **argv) size_t keylength, textlength; if (argc != 4) { - fprintf(stderr, "Usage: %s \n", argv[0]); + fprintf(stderr, "Usage: %s \n", argv[0]); exit(EXIT_FAILURE); } - key = argv[1]; - offset = strtol(argv[2], NULL, 10); - ciphertext = argv[3]; + offset = strtol(argv[1], NULL, 10); + ciphertext = argv[2]; + key = argv[3]; preprocess(key); preprocess(ciphertext); -- cgit v1.2.3-54-g00ecf From 70bb06ed33201cb9c420661a5d391f45706109f1 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 3 Apr 2015 12:01:14 +0200 Subject: genkeypairs: now more flexible --- genkeypairs.c | 48 +++++++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/genkeypairs.c b/genkeypairs.c index f6043fe..12f145b 100644 --- a/genkeypairs.c +++ b/genkeypairs.c @@ -13,31 +13,41 @@ #include #include #include +#include #define MAXLIST 1000 #define MAXKEY 100 -int main(int argc, char **argv) +int getword(char *output, int maxlength) { - int c, i, ii, listsize; - char *list[MAXLIST]; - char *word = malloc(MAXKEY+1); - for(i=0; i ", argv[0]); + exit(EXIT_FAILURE); + } + + command = argv[1]; + ciphertext = argv[2]; + + for(i=0; i Date: Sat, 4 Apr 2015 20:34:17 +0200 Subject: guesskeylength: Calculates indices of coincidence for different key width possibilities. --- guesskeylength.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 guesskeylength.c diff --git a/guesskeylength.c b/guesskeylength.c new file mode 100644 index 0000000..7941a93 --- /dev/null +++ b/guesskeylength.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +#define ALPHACHARS 26 + +void preprocess(char *str) +{ + char *src = str, *dest = str; + + while (*src != '\0') { + if (isalpha(*src)) + *(dest++) = toupper(*src); + src++; + } + + *dest = '\0'; +} + +double calc_ic_column(const char *text, size_t length, size_t offset, size_t spacing) +{ + unsigned foundc[ALPHACHARS] = {0}, total_chars = 0; + unsigned long pre_sum = 0; + + for (size_t i = offset; i < length; i += spacing, total_chars++) + foundc[CTOI(text[i])]++; + + for (unsigned i = 0; i < ALPHACHARS; i++) + pre_sum += foundc[i] * (foundc[i] - 1); + + return (double)pre_sum / ((double)total_chars * (double)(total_chars - 1) / ALPHACHARS); +} + +double calc_ic(const char *text, size_t length, size_t width) +{ + double total = 0; + + for (size_t offset = 0; offset < width; offset++) + total += calc_ic_column(text, length, offset, width); + + return total / width; +} + +int main(int argc, char **argv) +{ + char *text; + size_t length; + unsigned long max; + + if (argc != 3) { + fprintf(stderr, "Usage: %s \a\n", argv[0]); + exit(EXIT_FAILURE); + } + + text = argv[1]; + max = strtoul(argv[2], NULL, 10); + + preprocess(text); + length = strlen(text); + + for (unsigned long spacing = 1; spacing <= max; spacing++) { + double ic = calc_ic(text, length, spacing); + unsigned barlen; + + if (ic > 0.8 && ic < 4) + barlen = (ic - 0.8) / 3.2 * 40.0; + else + barlen = ic <= 0.8 ? 0 : 40; + + printf("%3lu - %6.3f ", spacing, ic); + for (unsigned i = 0; i < barlen; i++) + putchar('#'); + putchar('\n'); + } + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From b99f95ef777000743404902c76c9c8f0b207e5ba Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 4 Apr 2015 20:42:29 +0200 Subject: shufflechars: Shuffle characters around. --- shufflechars.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 shufflechars.c diff --git a/shufflechars.c b/shufflechars.c new file mode 100644 index 0000000..84a2c55 --- /dev/null +++ b/shufflechars.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include +#include +#include +#include +#include + +static inline unsigned rand_to_max(unsigned max) +{ + double random; + + while ((random = rand()) == (double)RAND_MAX); + + return random / (double)RAND_MAX * (double)max; +} + +int main(int argc, char **argv) +{ + size_t length; + char *text, *dest; + + srand(time(NULL)); + + if (argc != 2) { + fprintf(stderr, "Usage: %s \a\n", argv[0]); + exit(EXIT_FAILURE); + } + + text = argv[1]; + length = strlen(text); + + bool relocated[length]; + + memset(relocated, 0, length); + dest = malloc(length + 1); + + for (size_t i = 0; i < length; i++) { + size_t index; + while (index = rand_to_max(length), relocated[index]) + ; + + dest[i] = text[index]; + relocated[index] = true; + } + + dest[length] = '\0'; + + printf("%s\n", dest); + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf From d4826bc768f9e66b02b8e1826ad849f549e24b90 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 4 Apr 2015 20:54:39 +0200 Subject: Removed short useless code. --- blocks.c | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 blocks.c diff --git a/blocks.c b/blocks.c deleted file mode 100644 index baf31f6..0000000 --- a/blocks.c +++ /dev/null @@ -1,5 +0,0 @@ -int main(void) -{ - int i = ({ static int i = 3; i + 5; }); - return i; -} -- cgit v1.2.3-54-g00ecf From b1e025a502645cf4478d307708b7282cb834a7a8 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 4 Apr 2015 20:55:23 +0200 Subject: luaing: minor cleanup. --- luaing.c | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/luaing.c b/luaing.c index ac08668..3086921 100644 --- a/luaing.c +++ b/luaing.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ #include #include #include @@ -6,20 +15,18 @@ int main(int argc, char **argv) { - char buffer[256]; - int error; - lua_State *L = luaL_newstate(); - luaL_openlibs(L); + char buffer[256]; - while (fgets(buffer, sizeof(buffer), stdin) != NULL) { - error = luaL_loadbuffer(L, buffer, strlen(buffer), "line") - || lua_pcall(L, 0, 0, 0); - if (error) { - fprintf(stderr, "%s", lua_tostring(L, -1)); - lua_pop(L, 1); - } - } + lua_State *state = luaL_newstate(); + luaL_openlibs(state); - lua_close(L); - return 0; + while (fgets(buffer, sizeof(buffer), stdin) != NULL) { + if (luaL_loadbuffer(state, buffer, strlen(buffer), "line") || lua_pcall(state, 0, 0, 0)) { + fprintf(stderr, "%s", lua_tostring(state, -1)); + lua_pop(state, 1); + } + } + + lua_close(state); + return 0; } -- cgit v1.2.3-54-g00ecf From bec173d6f06f7a83ec0bb2300f7da4b6fcab6784 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 4 Apr 2015 20:55:41 +0200 Subject: Added more license headers. --- guesskeylength.c | 9 +++++++++ hangman.c | 9 +++++++++ ncurses_windows.c | 9 +++++++++ randtest.c | 9 +++++++++ vigenere.c | 9 +++++++++ 5 files changed, 45 insertions(+) diff --git a/guesskeylength.c b/guesskeylength.c index 7941a93..8b4409c 100644 --- a/guesskeylength.c +++ b/guesskeylength.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ #include #include #include diff --git a/hangman.c b/hangman.c index 4cf4c16..dfb75dd 100644 --- a/hangman.c +++ b/hangman.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ #include #include #include diff --git a/ncurses_windows.c b/ncurses_windows.c index 702aa27..4a733ba 100644 --- a/ncurses_windows.c +++ b/ncurses_windows.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ // -*- compile-command: "make LDLIBS=-lncurses ncurses_windows" -*- #include #include diff --git a/randtest.c b/randtest.c index 710377f..fcd394d 100644 --- a/randtest.c +++ b/randtest.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ #include #include #include diff --git a/vigenere.c b/vigenere.c index 5db3e18..9a64c3c 100644 --- a/vigenere.c +++ b/vigenere.c @@ -1,3 +1,12 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ #include #include #include -- cgit v1.2.3-54-g00ecf From baa9a0c6a5ecaac3522f64d8e04aa85d6498dd8c Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 26 Apr 2015 12:21:36 +0100 Subject: addrofmain.c --- addrofmain.c | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 addrofmain.c diff --git a/addrofmain.c b/addrofmain.c new file mode 100644 index 0000000..547909f --- /dev/null +++ b/addrofmain.c @@ -0,0 +1,8 @@ +#include + +int main(void) +{ + printf("%p\n", main); + + return 0; +} -- cgit v1.2.3-54-g00ecf From b6c5b07716105fb4d24a615689b842d5433cd82f Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 26 Apr 2015 14:54:38 +0100 Subject: poly_perim.c --- poly_perim.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 poly_perim.c diff --git a/poly_perim.c b/poly_perim.c new file mode 100644 index 0000000..8f1528f --- /dev/null +++ b/poly_perim.c @@ -0,0 +1,25 @@ +#include +#include + +double poly_perim(unsigned ndims, double *xcoords, double *ycoords) +{ + double retval = 0; + + for (unsigned i = 0; i < ndims; i++) { + double left = xcoords[(i + 1) % ndims] - xcoords[i]; + double right = ycoords[(i + 1) % ndims] - ycoords[i]; + + retval += sqrt(left * left + right * right); + } + + return retval; +} + +int main(void) +{ + printf("Perimiter: %f\n", poly_perim(3, + (double []){1, 1, 4}, + (double []){2, 5, 5})); + + return 0; +} -- cgit v1.2.3-54-g00ecf From 982705cc279fce7591536d23653ed3819dd37f01 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 1 May 2015 13:21:53 +0100 Subject: ant.c: now no longer gives warnings when compiling --- ant.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ant.c b/ant.c index a6b2fa8..0f1f1a0 100644 --- a/ant.c +++ b/ant.c @@ -54,24 +54,24 @@ Ant *ant_new(uint16_t width, uint16_t height, char *actions) return ant; } -void ant_del(Ant *ant) +static void ant_del(Ant *ant) { free(ant->buffer); free(ant->actions); free(ant); } -void inline ant_left(Ant *ant) +static inline void ant_left(Ant *ant) { ant->direction = ant->direction == 0 ? 3 : ant->direction - 1; } -void inline ant_right(Ant *ant) +static inline void ant_right(Ant *ant) { ant->direction = ant->direction == 3 ? 0 : ant->direction + 1; } -void inline ant_forward(Ant *ant) +static inline void ant_forward(Ant *ant) { if (ant->direction & 1) { /* EAST or WEST */ ant->posx = ant->direction == EAST ? ant->posx + 1 : ant->posx - 1; @@ -109,7 +109,7 @@ int main(int argc, char **argv) xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; uint32_t mask = XCB_CW_BACK_PIXEL; - uint32_t values[] = {screen->black_pixel}; + uint32_t values[2] = {screen->black_pixel}; xcb_drawable_t window = xcb_generate_id(connection); xcb_create_window(connection, @@ -194,5 +194,7 @@ int main(int argc, char **argv) ant_simulate(ant); } + + ant_del(ant); return 0; } -- cgit v1.2.3-54-g00ecf From 2b744b571515645456946b58444d68ab47b02659 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 1 May 2015 13:33:58 +0100 Subject: sdl.c, undefined.c, md5.c --- md5.c | 130 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdl.c | 131 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ undefined.c | 10 +++++ 3 files changed, 271 insertions(+) create mode 100644 md5.c create mode 100644 sdl.c create mode 100644 undefined.c diff --git a/md5.c b/md5.c new file mode 100644 index 0000000..359fb94 --- /dev/null +++ b/md5.c @@ -0,0 +1,130 @@ +/* + * This is an attempt at implementing md5 in c, so far it doesn't work :(. + * I took the values from wikipedia (https://en.wikipedia.org/wiki/MD5). + * + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include +#include +#include +#include +#include + +void shuffle_bytes(char *buf, size_t length) +{ + length = length - length % 4; + + for (size_t i = 0; i < length / 4; i++) { + char *bufc = buf + i * 4; + char chars[4] = { + bufc[3], + bufc[2], + bufc[1], + bufc[0] + }; + strncpy(bufc, chars, 4); + } +} + +int main(void) +{ + uint32_t *s, *K, a0, b0, c0, d0, length; + char input[64] = ""; + + length = strlen(input); + + s = (uint32_t []){ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; + + K = (uint32_t []){ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; + + a0 = 0x67452301; + b0 = 0xefcdab89; + c0 = 0x98badcfe; + d0 = 0x10325476; + + input[length] = 128; + + for (uint8_t i = length + 1; i < 56; i++) + input[i] = 0; + + /*((uint64_t *)input)[7] = (uint64_t)length;*/ + input[63] = 0; + + for (uint8_t i = 0; i < 64; i++) + putchar(input[i]); + + /*shuffle_bytes(input, 64);*/ + uint32_t *M = (uint32_t *)input; + + uint32_t A = a0, B = b0, C = c0, D = d0; + + for (uint32_t i = 0; i < 64; i ++) { + uint16_t F, g, dTemp; + + switch (i) { + case 0 ... 15: + F = (B & C) | ((~B) & D); + g = i; + break; + case 16 ... 31: + F = (D & B) | ((~D) & C); + g = (5 * i + 1) % 16; + break; + case 32 ... 47: + F = B ^ C ^ D; + g = (3 * i + 5) % 16; + break; + case 48 ... 63: + F = C ^ (B | (~D)); + g = (7 * i) % 16; + break; + } + + dTemp = D; + + D = C; + C = B; + B += ((A + F + K[i] + M[g]) << s[i]) | ((A + F + K[i] + M[g]) >> (32-s[i])); + A = dTemp; + } + + a0 += A; + b0 += B; + c0 += C; + d0 += D; + + /*shuffle_bytes((char *)&a0, 4);*/ + /*shuffle_bytes((char *)&b0, 4);*/ + /*shuffle_bytes((char *)&c0, 4);*/ + /*shuffle_bytes((char *)&d0, 4);*/ + + printf("%.8x%.8x%.8x%.8x\n", a0, b0, c0, d0); + + return EXIT_SUCCESS; +} diff --git a/sdl.c b/sdl.c new file mode 100644 index 0000000..bc75984 --- /dev/null +++ b/sdl.c @@ -0,0 +1,131 @@ +#include +#include +#include +#include +#include + +#define WIDTH 640 +#define HEIGHT 480 +#define DEPTH 32 + +enum obj_type { + O_QUAD, + O_TRIG, + O_CIRC +}; + +struct quad { + uint32_t x, y, width, height; +}; + +struct circle { + uint32_t x, y, diameter; +}; + +typedef union colour_t { + struct { + uint8_t a, r, g, b; + } comp; + uint32_t colour; +} colour_t; + +struct object { + enum obj_type type; + colour_t colour; + union { + struct quad quad; + struct circle circle; + } obj; +}; + +SDL_Window *window; +SDL_Renderer *renderer; +SDL_Texture *screen; +colour_t *buffer; + +struct object *objects; +uint32_t object_count; + +volatile bool running = true; + +#define QUOTE(text) "`" #text "'" +#define SDL_ASSERT(expr, comp, val) \ + if ((expr) comp val) { \ + fprintf(stderr, "SDL Error: %s - %s\n", QUOTE(expr), SDL_GetError()); \ + exit(EXIT_FAILURE); \ + } + +#define SDL_ASSERT_NN(expr) SDL_ASSERT(expr, ==, NULL) +#define SDL_ASSERT_Z(expr) SDL_ASSERT(expr, !=, 0) + +void prep_objects() +{ + objects = malloc(1 * sizeof *objects); + objects[0] = (struct object){O_QUAD, {{255, 0, 0, 0}}, {.quad = {30, 30, 30, 30}}}; + + object_count = 1; +} + +void draw_screen() +{ + for (size_t i = 0; i < WIDTH * HEIGHT; i++) + buffer[i] = (colour_t){{0, 255, 0, 0}}; + + SDL_UpdateTexture(screen, NULL, buffer, 640 * sizeof *buffer); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, screen, NULL, NULL); + SDL_RenderPresent(renderer); +} + +void poll_for_events() +{ + SDL_Event event; + + while (SDL_PollEvent(&event)) { + switch (event.type) { + case SDL_QUIT: + exit(EXIT_SUCCESS); + break; + case SDL_KEYDOWN: + printf("Key.\n"); + break; + } + } +} + +void simulate(uint32_t difference) +{ + printf("%lu\n", difference); +} + +uint32_t get_time_delta() +{ + static uint32_t old_time; + uint32_t time = SDL_GetTicks(); + uint32_t difference = time - old_time; + old_time = time; + return difference; +} + +int main(void) +{ + SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); + atexit(SDL_Quit); + + window = SDL_CreateWindow("Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL); + renderer = SDL_CreateRenderer(window, -1, 0); + screen = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 640, 480); + buffer = malloc(sizeof *buffer * 640 * 480); + + prep_objects(); + + get_time_delta(); + + while (running) { + draw_screen(); + poll_for_events(); + simulate(get_time_delta()); + } + + return(EXIT_SUCCESS); +} diff --git a/undefined.c b/undefined.c new file mode 100644 index 0000000..38977d8 --- /dev/null +++ b/undefined.c @@ -0,0 +1,10 @@ +#include + +int main(void) +{ + int i = 0; + + printf("%d %d %d %d\n", i, i++, i, i++); + + return 0; +} -- cgit v1.2.3-54-g00ecf From d732b8cea5f301e6879bc2321a777490c8df9d27 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 24 May 2015 20:25:56 +0100 Subject: New and improved timer. --- timer.c | 196 +++++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 162 insertions(+), 34 deletions(-) diff --git a/timer.c b/timer.c index fa46885..d32c9b1 100644 --- a/timer.c +++ b/timer.c @@ -10,70 +10,198 @@ * along with this program. If not, see [http://www.gnu.org/licenses/]. */ +#include +#include +#include +#include #include #include #include +#include #include #include +#include -unsigned long int get_seconds(char *); +#define SEC_SECOND 1 +#define SEC_MINUTE 60 +#define SEC_HOUR 3600 +#define SEC_DAY 86400 +#define SEC_MONTH 2629746 +#define SEC_YEAR 31556940 + +static const unsigned long interval_nsec = 1000000000 / 4; + +unsigned long int get_seconds(char *code) +{ + int length = strlen(code), multiplier = 0; + char suffix = code[length - 1], value[length + 1]; + unsigned long retval; + + if (length < 2) { + return 0; + } + + switch (suffix) { + case 's': multiplier = SEC_SECOND; break; // 1 second + case 'm': multiplier = SEC_MINUTE; break; // 1 minute + case 'h': multiplier = SEC_HOUR; break; // 1 hour + case 'D': multiplier = SEC_DAY; break; // 1 day + case 'M': multiplier = SEC_MONTH; break; // 30.4368 days + case 'Y': multiplier = SEC_YEAR; break; // 365.242 days + default : return 0; + } + + strncpy(value, code, length + 1); + + value[length - 1] = '\0'; + + errno = 0; + + retval = strtoul(value, NULL, 10) * multiplier; + + if (retval == ULONG_MAX && errno != 0) + error(1, errno, "Error converting time specifier %s", code); + + return retval; +} + +void clear_line(void) +{ + struct winsize ws; + + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) + error(1, errno, "IOCTL failed"); + + if (ws.ws_col <= 1) + return; + + for (unsigned short i = 0; i < ws.ws_col - 1; i++) + putchar(' '); + + putchar('\r'); + + if (fflush(stdout) != 0) + error(1, errno, "Failed to flush stdout"); +} + + +void print_time(unsigned long total_sec, bool show_colon) +{ + unsigned long years, months, days, hours, minutes, seconds; + char colon = show_colon ? ':' : ' '; + + years = total_sec / SEC_YEAR; + total_sec %= SEC_YEAR; + + months = total_sec / SEC_MONTH; + total_sec %= SEC_MONTH; + + days = total_sec / SEC_DAY; + total_sec %= SEC_DAY; + + hours = total_sec / SEC_HOUR; + total_sec %= SEC_HOUR; + + minutes = total_sec / SEC_MINUTE; + total_sec %= SEC_MINUTE; + + seconds = total_sec / SEC_SECOND; + total_sec %= SEC_SECOND; + + if (total_sec != 0) + error(1, 0, "An error occured during time formatting"); + + printf(" %luY %luM %luD %.2lu%c%.2lu%c%.2lu\r", years, months, + days, hours, colon, minutes, colon, seconds); + + if (fflush(stdout) != 0) + error(1, errno, "Failed to flush stdout"); +} void usage(char *cmd) { - printf("Usage:\n" - "\t%s {s,m,h,D,M,Y} ...\n", cmd); + printf("Usage:\n\t%s {s,m,h,D,M,Y} ...\n", cmd); } int main(int argc, char **argv) { + bool blink = false; + int sig; + sigset_t sigset; + struct itimerspec its; + struct sigevent sev; + timer_t timerid; + + unsigned long total_seconds = 0; + if (argc < 2) { printf("Not enough arguments.\n"); usage(argv[0]); exit(1); } - unsigned long int total_seconds = 0; - for (int i = 1; i < argc; i++) total_seconds += get_seconds(argv[i]); - printf("Total time: %lu second(s).\nStarted at: %ld\n", total_seconds, time(NULL)); + sev.sigev_notify = SIGEV_SIGNAL; + sev.sigev_signo = SIGRTMIN; + sev.sigev_value.sival_ptr = &timerid; - sleep(total_seconds); + if (timer_create(CLOCK_MONOTONIC, &sev, &timerid) != 0) + error(1, errno, "Could not create timer"); - printf("Ended at: %ld\n", time(NULL)); + its = (struct itimerspec){ + {0, interval_nsec}, + {0, interval_nsec} + }; - while (1) { - printf("Ring!\a\n"); - sleep(1); - } + if (sigemptyset(&sigset) != 0) + error(1, errno, "Could not empty signal set"); - return 0; -} + if (sigaddset(&sigset, SIGRTMIN) != 0) + error(1, errno, "Could not add SIGRTMIN to signal set"); -unsigned long int get_seconds(char *code) -{ - int length = strlen(code); - if (length < 2) { - return 0; - } + if (sigprocmask(SIG_BLOCK, &sigset, NULL) != 0) + error(1, errno, "Could not block SIGRTMIN"); - int multiplier = 0; - char suffix = code[length - 1]; - switch (suffix) { - case 's': multiplier = 1; break; // 1 second - case 'm': multiplier = 60; break; // 1 minute - case 'h': multiplier = 3600; break; // 1 hour - case 'D': multiplier = 86400; break; // 1 day - case 'M': multiplier = 2629746; break; // 30.4368 days - case 'Y': multiplier = 31556940; break; // 365.242 days - default : return 0; + if (timer_settime(timerid, 0, &its, NULL) != 0) + error(1, errno, "Could not set timer"); + + for (unsigned long i = 0; i < total_seconds; i++) + for (int ii = 0; ii < 4; ii++) { + if (sigwait(&sigset, &sig), sig != SIGRTMIN) + error(1, 0, "sigwait returned unexpected signal %d", sig); + if (sigaddset(&sigset, SIGRTMIN) != 0) + error(1, errno, "Could not add signal to set"); + + clear_line(); + print_time(total_seconds - i, ii < 2); + } + + if (sigaddset(&sigset, SIGINT) != 0) + error(1, errno, "Could not add SIGINT to signal set"); + + while (true) { + blink = !blink; + sigwait(&sigset, &sig); + if (sig != SIGRTMIN) + break; + + if (sigaddset(&sigset, SIGRTMIN) != 0) + error(1, errno, "Could not add signal to set"); + + clear_line(); + + if (blink) + printf(" -- BEEP -- \a\r"); + + if (fflush(stdout) != 0) + error(1, errno, "Failed to flush stdout"); } - char value[length + 1]; - strncpy(value, code, length + 1); + timer_delete(timerid); - value[length - 1] = '\0'; + clear_line(); - return strtoul(value, NULL, 10) * multiplier; + return 0; } -- cgit v1.2.3-54-g00ecf From 792ef281df229d5748ef7049f4ffcf678588cfe7 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 24 May 2015 20:26:13 +0100 Subject: Makefile now has a help target as well as the all target --- Makefile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Makefile b/Makefile index 1d6edc4..4f29283 100644 --- a/Makefile +++ b/Makefile @@ -14,9 +14,14 @@ bindir = $(prefix)/bin all: @echo 'Error, target not specified.' + @make --no-print-directory help + +help: + @echo 'Usage:' @echo ' To compile .c `make `' @echo ' To install `make target= install`' @echo ' To uninstall `make target= uninstall`' + @echo ' To clean up `make clean`' $(DESTDIR)$(bindir)/%: % -- cgit v1.2.3-54-g00ecf From b0409caee2e2e13355a883ac0cf1e6addd8adcbe Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 24 May 2015 20:30:05 +0100 Subject: Added -D flag to install --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4f29283..0cb6fcc 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ else CFLAGS += -O2 endif -INSTALL = install -m755 +INSTALL = install -Dm755 prefix = /usr/local bindir = $(prefix)/bin -- cgit v1.2.3-54-g00ecf From 0f981889b3a4d62104383c5a5c0efa3a1e9f5261 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 24 May 2015 20:38:00 +0100 Subject: Makefile no longer installs bin executable --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 0cb6fcc..f5da2e9 100644 --- a/Makefile +++ b/Makefile @@ -25,7 +25,7 @@ help: $(DESTDIR)$(bindir)/%: % - $(INSTALL) $^ $(DESTDIR)$(bindir) + $(INSTALL) $^ $(DESTDIR)$(bindir)/$(target) install: $(DESTDIR)$(bindir)/$(target) -- cgit v1.2.3-54-g00ecf From 7bf25fb8f0e4643a67894417a95d39e5901b1824 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 25 May 2015 22:53:55 +0100 Subject: editor.c: a joke, an editor which writes a c program --- editor.c | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 editor.c diff --git a/editor.c b/editor.c new file mode 100644 index 0000000..afea796 --- /dev/null +++ b/editor.c @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +bool running = true; +size_t position = 0; + +char *program = "#include \n" \ + "\n" \ + "int main(void)\n" \ + "{\n" \ + "\tprintf(\"Hello World\\n\");\n" \ + "\n" \ + "\treturn 0;\n" \ + "}"; + +char *usage = "%sUsage:\n" \ + "\t%s "; + +void print_screen(void) +{ + mvaddnstr(0, 0, program, position); +} + +int getch_nodelay(void) +{ + int retval; + + nodelay(stdscr, TRUE); + retval = getch(); + nodelay(stdscr, FALSE); + + return retval; +} + + +void poll_input(void) +{ + int c = getch(); + + if (c == 27 && getch_nodelay() == ERR) { + running = false; + return; + } + + if (program[position] == c) + position++; +} + +int main(int argc, char **argv) +{ + FILE *file; + + if (argc != 2) + error(1, 0, usage, "Incorrect number of arguments\n", + program_invocation_name); + + cbreak(); + initscr(); + noecho(); + + intrflush(stdscr, FALSE); + + print_screen(); + while (running) { + poll_input(); + print_screen(); + } + + endwin(); + + if (file = fopen(argv[1], "w"), file == NULL) + error(1, errno, "Could not access %s", argv[1]); + + fwrite(program, 1, position, file); + + fclose(file); + + printf("Saved.\n"); + + return 0; +} -- cgit v1.2.3-54-g00ecf