Add player

pull/2/head
Nakidai 2023-10-29 23:14:51 +03:00
parent c7797f1f41
commit fac72a00ed
Signed by untrusted user who does not match committer: nakidai
GPG Key ID: 914675D395210A97
3 changed files with 92 additions and 1 deletions

View File

@ -7,7 +7,7 @@ LD = ld
RM = rm -f
SRCDIR = src
OBJDIR = obj
SRC = main.c screen.c input.c
SRC = main.c screen.c input.c player.c
OBJ = $(addprefix $(OBJDIR)/,$(SRC:.c=.o))
default: $(OUT)

33
include/player.h Normal file
View File

@ -0,0 +1,33 @@
#ifndef __PLAYER_H__
#define __PLAYER_H__
#include <stdbool.h>
#define UP 0
#define RIGHT 1
#define DOWN 2
#define LEFT 3
typedef int Direction;
typedef struct player_node_t PlayerNode;
typedef struct player_t Player;
struct player_node_t
{
int x, y;
PlayerNode *next;
};
struct player_t
{
PlayerNode *tail, *head;
Direction direction;
int score;
};
Player *playerCreate(Direction direction, int x, int y, int score);
void playerFree(Player *player);
void playerDoTick(Player *player, bool food_collision);
#endif /* __PLAYER_H__ */

58
src/player.c Normal file
View File

@ -0,0 +1,58 @@
#include "player.h"
#include <stdlib.h>
Player *playerCreate(Direction direction, int x, int y, int score)
{
Player *player = (Player *)malloc(sizeof(Player));
PlayerNode *head = (PlayerNode *)malloc(sizeof(PlayerNode));
player->tail = head;
player->head = head;
player->score = score;
player->direction = direction;
head->x = x;
head->y = y;
head->next = NULL;
}
void playerFree(Player *player)
{
}
void playerDoTick(Player *player, bool food_collision)
{
PlayerNode *new_head = (PlayerNode *)malloc(sizeof(PlayerNode));
int head_x = player->head->x;
int head_y = player->head->y;
switch(player->direction)
{
case UP:
new_head->x = head_x;
new_head->y = head_y - 1;
break;
case DOWN:
new_head->x = head_x;
new_head->y = head_y + 1;
break;
case LEFT:
new_head->x = head_x - 1;
new_head->y = head_y;
break;
case RIGHT:
new_head->x = head_x + 1;
new_head->y = head_y;
break;
}
player->head->next = new_head;
player->head = new_head;
if (!food_collision)
{
PlayerNode *new_tail = player->tail->next;
free(player->tail);
player->tail = new_tail;
}
}