snake/game.c
2020-04-23 17:39:46 +02:00

83 lines
1.8 KiB
C

#include <curses.h>
#include <stdlib.h>
#include <string.h>
#include "world.h"
#include "game.h"
#include "snake.h"
// Start is called one in the beginning
void* init_game(struct world* world){
// Allocate memory for the state
struct state* st = calloc(1,(sizeof(struct state)));
st->snake = NULL;
st->sx = 1;
st->sy = 0;
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);
}
int h = world->height;
int w = world->width;
for (int i = 0; i < 5; i++){
st->foodx[i] = rand() % w;
st->foody[i] = rand() % h;
}
return st;
}
// Step is called in a loop once in interval.
// It should modify the state and draw it.
int world_event(struct world* w,void* game){
// Get state pointer
struct state* st = game;
int key = w->key;
if (key == KEY_RIGHT){
st->sx = 1;
st->sy = 0;
}
else if (key == KEY_LEFT){
st->sx = -1;
st->sy = 0;
}
else if (key == KEY_DOWN){
st->sx = 0;
st->sy = 1;
}
else if (key == KEY_UP){
st->sx = 0;
st->sy = -1;
}
else if (key == KEY_ENTER){
// Non zero means finish the loop and stop the game.
return 1;
}
st->width = w->width;
st->height = w->height;
int r = step_state(st);
// Draw snake
struct snake* sn = st->snake;
while (sn != NULL){
set_cell(w,'x',sn->x,sn->y);
sn = sn->next;
}
for (int i = 0 ; i < FOOD_COUNT; i++){
if (st->foodx[i] >= 0 && st->foody[i] >= 0){
set_cell(w,'*',st->foodx[i],st->foody[i]);
}
}
if (r){
char message[] = "Koniec";
for (int i = 0; i < 6; i++){
set_cell(w,message[i],10+i,10);
}
}
return 0;
}