forked from nakidai/csnake
1
0
Fork 0
csnake/src/main.c

93 lines
2.4 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
2023-10-30 02:51:46 +03:00
#include <threads.h>
#include <time.h>
#include "input.h"
2023-10-29 20:03:23 +03:00
#include "screen.h"
#include "player.h"
#include "food.h"
2023-10-30 03:09:32 +03:00
#include "config.h"
void drawPlayer(Player *player, Screen *screen)
{
PlayerNode *node;
for (node = player->tail; node != NULL; node = node->next)
*screenGetPoint(screen, node->x, node->y) = '#';
}
2023-10-29 20:03:23 +03:00
Food generateFood(Player *player)
{
Food food;
do
{
2023-10-31 06:07:03 +03:00
food = (Food){rand() % SIZE, rand() % SIZE};
} while (playerCheckFoodCollision(player, food));
return food;
}
2023-10-30 14:24:34 +03:00
void resetCoordinates(void)
{
printf("\e[1;1H\e[2J");
2023-10-30 14:24:34 +03:00
}
2023-10-29 20:03:23 +03:00
int main(int argc, char **argv)
{
2023-10-31 06:07:03 +03:00
srand(time(NULL));
2023-10-30 03:09:32 +03:00
Player *player = playerCreate(DOWN, DEFX, DEFY, 0);
Screen *screen = screenCreate(SIZE, SIZE, ' ');
PlayerNode *node;
2023-10-30 02:51:46 +03:00
thrd_t input_thread;
2023-10-30 03:53:48 +03:00
int i;
int head_x, head_y;
Food food = generateFood(player);
bool *running = malloc(sizeof(bool)); *running = true;
char *key = malloc(sizeof(char)); *key = 0;
InputArgs input_args = (InputArgs){ key, running };
2023-10-30 02:51:46 +03:00
thrd_create(&input_thread, input, &input_args);
while (*running)
{
switch (*key)
{
case 'q':
*running = false; return 0;
case 'w':
2023-10-31 05:05:10 +03:00
if (player->direction == DOWN) break;
player->direction = UP; break;
case 'd':
2023-10-31 05:05:10 +03:00
if (player->direction == LEFT) break;
player->direction = RIGHT; break;
case 's':
2023-10-31 05:05:10 +03:00
if (player->direction == UP) break;
player->direction = DOWN; break;
case 'a':
2023-10-31 05:05:10 +03:00
if (player->direction == RIGHT) break;
player->direction = LEFT; break;
}
if (playerDoTick(player, food) && player->score >= SIZE*SIZE - 1)
food = generateFood(player);
head_x = player->head->x;
head_y = player->head->y;
2023-11-01 13:27:42 +03:00
if (head_x >= SIZE || head_x < 0 || head_y >= SIZE || head_y < 0 || playerCheckSelfCollision(player))
{
*running = false;
break;
}
screenSet(screen, ' ');
drawPlayer(player, screen);
*screenGetPoint(screen, food.x, food.y) = '@';
2023-10-30 14:24:34 +03:00
resetCoordinates();
screenShow(screen);
2023-10-30 15:52:25 +03:00
for (i = 0; i < SIZE*2; ++i) putchar('-');
2023-10-30 03:53:48 +03:00
printf("\nScore: %d\n", player->score);
2023-10-30 02:51:46 +03:00
thrd_sleep(&(struct timespec){.tv_sec=1}, NULL);
}
2023-10-29 20:03:23 +03:00
return 0;
}