pvjc24/a2/snake.c

92 lines
2.2 KiB
C
Raw Normal View History

2024-04-18 12:43:32 +00:00
#include <stdlib.h>
#include <curses.h>
#include <string.h>
2024-04-26 12:05:00 +00:00
#include "world.h"
// Game state structure
struct state {
int width;
int height;
int sx;
int sy;
struct snake* snake;
int foodx[5];
int foody[5];
};
2024-04-18 12:39:13 +00:00
2024-04-26 12:05:00 +00:00
// Initialize game state
void* init_game() {
struct state* st = calloc(1, sizeof(struct state));
2024-04-18 12:43:32 +00:00
return st;
2024-04-18 12:39:13 +00:00
}
2024-04-18 12:43:32 +00:00
// Initialize game state
2024-04-26 12:05:00 +00:00
void init_snake(struct event* world, struct state* st) {
int cy = world->height / 2;
int cx = world->width / 2 - 5;
for (int i = 0; i < 5; i++) {
st->snake = add_snake(st->snake, cx + i, cy);
2024-04-18 12:39:13 +00:00
}
2024-04-18 12:43:32 +00:00
int h = world->height;
int w = world->width;
2024-04-26 12:05:00 +00:00
for (int i = 0; i < 5; i++) {
2024-04-18 12:43:32 +00:00
st->foodx[i] = rand() % w;
st->foody[i] = rand() % h;
2024-04-18 12:39:13 +00:00
}
2024-04-18 12:43:32 +00:00
st->sx = 1;
st->sy = 0;
2024-04-18 12:39:13 +00:00
}
2024-04-26 12:05:00 +00:00
// Handle game events
int world_event(struct event* w, void* game) {
2024-04-18 12:43:32 +00:00
struct state* st = game;
2024-04-26 12:05:00 +00:00
if (w->type == EVENT_START) {
init_snake(w, st);
} else if (w->type == EVENT_KEY) {
2024-04-18 12:43:32 +00:00
int key = w->key;
2024-04-26 12:05:00 +00:00
if (key == KEY_RIGHT) {
st->sx = 1;
st->sy = 0;
} else if (key == KEY_LEFT) {
2024-04-18 12:43:32 +00:00
st->sx = -1;
st->sy = 0;
2024-04-26 12:05:00 +00:00
} else if (key == KEY_DOWN) {
2024-04-18 12:43:32 +00:00
st->sx = 0;
st->sy = 1;
2024-04-26 12:05:00 +00:00
} else if (key == KEY_UP) {
2024-04-18 12:43:32 +00:00
st->sx = 0;
st->sy = -1;
}
2024-04-26 12:05:00 +00:00
} else if (w->type == EVENT_ESC) {
return 1;
} else if (w->type == EVENT_TIMEOUT) {
2024-04-18 12:43:32 +00:00
clear_screen();
st->width = w->width;
st->height = w->height;
int r = step_state(st);
char ms[200];
2024-04-26 12:05:00 +00:00
sprintf(ms, "r %d\n", r);
set_message(ms, 9, 9);
2024-04-18 12:43:32 +00:00
struct snake* sn = st->snake;
2024-04-26 12:05:00 +00:00
while (sn != NULL) {
set_cell('x', sn->x, sn->y);
2024-04-18 12:43:32 +00:00
sn = sn->next;
}
2024-04-26 12:05:00 +00:00
for (int i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] >= 0 && st->foody[i] >= 0) {
set_cell('*', st->foodx[i], st->foody[i]);
2024-04-18 12:43:32 +00:00
}
}
2024-04-26 12:05:00 +00:00
if (r) {
2024-04-18 12:43:32 +00:00
char message[] = "Koniec";
2024-04-26 12:05:00 +00:00
set_message(message, 10, 10);
2024-04-18 12:39:13 +00:00
}
}
return 0;
}
2024-04-26 12:05:00 +00:00
int main(int argc, char** argv) {
start_world(init_game, world_event, free);
2024-04-18 12:43:32 +00:00
return 0;
2024-04-26 12:05:00 +00:00
}