segment finsihed, snake and main started

This commit is contained in:
Noah Swerhun 2021-09-17 21:02:19 -05:00
parent c479b42b33
commit 2229fcd888
6 changed files with 118 additions and 0 deletions

View file

@ -0,0 +1,7 @@
#ifndef MAIN_H
#define MAIN_H
void die(char *, ...);
void free_s(void *);
#endif

View file

@ -0,0 +1,16 @@
#ifndef SEGMENT_H
#define SEGMENT_H
typedef struct segment_T {
int x;
int y;
int prev_x;
int prev_y;
} Segment;
Segment *new_segment(int, int);
void delete_segment(Segment *);
void segment_move(Segment *, int, int);
#endif

View file

@ -0,0 +1,23 @@
#ifndef SNAKE_H
#define SNAKE_H
enum dirn {
UP = 0,
DOWN,
RIGHT,
LEFT
};
typedef struct snake_T {
Segments **n;
size_t len;
int head_dirn;
} Snake;
Snake *new_snake(size_t, int, int, int);
void *delete_snake(Snake *);
void snake_forward(Snake *, int);
int snake_eat(Snake *);
#endif

View file

@ -1,4 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "include/main.h"
void die(char *fmt, ...) {
va_list args;
va_start(args, fmt);
fprintf(stderr, "fatal: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args)
exit(1);
}
void free_s(void *p) {
free(p);
p = NULL;
}

View file

@ -0,0 +1,31 @@
#include <stdlib.h>
#include "include/main.h"
#include "include/segment.h"
Segment *new_segment(int x, int y) {
Segment c;
c = (Segment *)malloc(sizeof(Segment));
if (!c)
die("segment.c: new_segment(): 'c' is null pointer");
c->x = x;
c->y = y;
c->prev_x = EOF;
c->prev_y = EOF;
return c;
}
void delete_segment(Segment *c) {
free_s(c);
}
void segment_move(Segment *c, int x, int y) {
if (!c)
die("segment.c: segment_move(): 'c' is null pointer");
c->prev_x = c->x;
c->x = x;
c->prev_y = c->y;
c->y = y;
}

View file

@ -0,0 +1,23 @@
#include <stdlib.h>
#include "include/main.h"
#include "include/segment.h"
#include "include/snake.h"
Snake *new_snake(size_t len, int head_dirn, int x, int y) {
Snake *s;
s = (Snake *)malloc(sizeof(Snake));
if (!s)
die("snake.c: new_snake(): 's' is null pointer");
s->n = (Segment **)malloc(sizeof(Segment *) * len);
if (!s->n)
die("snake.c: new_snake(): 's->n' is null pointer");
for (size_t i = 0; i < len; i++) {
s->*n[i] = new_segment(x, y--);
}
}
void *delete_snake(Snake *);
void snake_forward(Snake *, int);
int snake_eat(Snake *);