Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // main.c
- #include <stdbool.h>
- #include "map.h"
- int main(void) {
- map_init(true);
- map_display();
- map_put(MAP_HORIZONTAL / 2, MAP_VERTICAL / 2, 'x');
- map_display();
- map_move(MAP_HORIZONTAL / 2, MAP_VERTICAL / 2, 0, 0);
- map_display();
- map_delete();
- }
- // map.h
- #ifndef MAP_H_
- #define MAP_H_
- #include <stdbool.h>
- #include <stddef.h>
- #define MAP_HORIZONTAL 7
- #define MAP_VERTICAL 7
- void map_init(bool);
- void map_delete(void);
- void map_display(void);
- void map_put(size_t, size_t, char);
- char map_get(size_t, size_t);
- void map_move(size_t, size_t, size_t, size_t);
- #endif /* MAP_H_ */
- // map_inner.h
- #ifndef MAP_INNER_H_
- #define MAP_INNER_H_
- #ifdef IN_MAP
- #include <stdbool.h>
- #include <stddef.h>
- static char *map;
- static bool map_invalid_coord(size_t, size_t);
- #endif /* IN_MAP */
- #endif /* MAP_INNER_H_ */
- // map.c
- #include <stdio.h>
- #include <stdlib.h>
- #define IN_MAP
- #include "map.h"
- #include "map_inner.h"
- void map_init(bool force) {
- if (!force) {
- return;
- }
- map = malloc(MAP_HORIZONTAL * MAP_VERTICAL);
- char c;
- for (size_t j = 0; j < MAP_VERTICAL; ++j) {
- for (size_t i = 0; i < MAP_HORIZONTAL; ++i) {
- if (j == 0 || j == MAP_VERTICAL - 1) {
- c = '*';
- } else if (i == 0 || i == MAP_HORIZONTAL - 1) {
- c = '*';
- } else {
- c = ' ';
- }
- map_put(i, j, c);
- }
- }
- }
- void map_delete(void) {
- free(map);
- }
- void map_put(size_t x, size_t y, char c) {
- if (map_invalid_coord(x, y)) {
- return;
- }
- map[y * MAP_HORIZONTAL + x] = c;
- }
- void map_display(void) {
- for (size_t j = 0; j < MAP_VERTICAL; ++j) {
- for (size_t i = 0; i < MAP_HORIZONTAL; ++i) {
- printf("%c", map_get(i, j));
- }
- puts("");
- }
- puts("");
- }
- char map_get(size_t x, size_t y) {
- if (map_invalid_coord(x, y)) {
- return '#'; // for error
- }
- return map[y * MAP_HORIZONTAL + x];
- }
- void map_move(size_t x1, size_t y1, size_t x2, size_t y2) {
- if (map_invalid_coord(x1, y1) || map_invalid_coord(x2, y2)) {
- return;
- }
- map_put(x2, y2, map_get(x1, y1));
- map_put(x1, y1, ' ');
- }
- static bool map_invalid_coord(size_t x, size_t y) {
- return x < 0 && MAP_HORIZONTAL <= x && y < 0 && MAP_VERTICAL <= y;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement