pvjc25/a3/main.c

135 lines
3.6 KiB
C

#include "world.h"
#include <stdlib.h>
#include <curses.h>
#include <stdlib.h>
#include <string.h>
#include "snake.h"
// This file contains functions for drawing the the game and changing the state
// Start is called one in the beginning
void* init_game(){
// Allocate memory for the state
struct state* st = calloc(1,(sizeof(struct state)));
return st;
}
// The first event
// Initialize game state
// - borders
// - snake position
// - food position
void init_snake(struct event* world, struct state* st){
st->width = world->width;
st->height = world->height;
int cx = st->width / 2;
int cy = st->height / 2;
st->snake = NULL;
// Place snake horizontally, centered, away from borders
int start_x = cx - 2;
int y = cy;
for (int i = 0; i < 5; i++) {
st->snake = add_snake(st->snake, start_x + i, y);
}
int placed = 0;
while (placed < FOOD_COUNT) {
int fx = rand() % (st->width - 2) + 1; // avoid border
int fy = rand() % (st->height - 2) + 1; // avoid border
if (!is_snake(st->snake, fx, fy)) {
st->foodx[placed] = fx;
st->foody[placed] = fy;
placed++;
}
}
// Initial game vector: right
st->sx = 1;
st->sy = 0;
}
// Step is called in a loop once in interval.
// It should modify the state and draw it.
int world_event(struct event* w,void* game){
static int game_over = 0;
struct state* st = game;
if (w->type == EVENT_START){
game_over = 0;
init_snake(w,st);
}
if (game_over) {
// Ignore all events except EVENT_START and EVENT_ESC
if (w->type != EVENT_ESC && w->type != EVENT_START) {
return 0;
}
}
// Called on key press
else if (w->type == EVENT_KEY){
int key = w->key;
// Modifies vector of snake movement
if (key == KEY_RIGHT){
if (!(st->sx == -1 && st->sy == 0)) { // Prevent reverse
st->sx = 1;
st->sy = 0;
}
}
else if (key == KEY_LEFT){
if (!(st->sx == 1 && st->sy == 0)) { // Prevent reverse
st->sx = -1;
st->sy = 0;
}
}
else if (key == KEY_DOWN){
if (!(st->sx == 0 && st->sy == -1)) { // Prevent reverse
st->sx = 0;
st->sy = 1;
}
}
else if (key == KEY_UP){
if (!(st->sx == 0 && st->sy == 1)) { // Prevent reverse
st->sx = 0;
st->sy = -1;
}
}
}
// Called on esc key
else if (w->type == EVENT_ESC){
// Non zero means finish the loop and stop the game.
return 1;
}
// Called on interval timeout
else if (w->type == EVENT_TIMEOUT){
clear_screen();
// Copy screen size
st->width = w->width;
st->height = w->height;
// Change game state
int r = step_state(st);
// Draw snake
struct snake* sn = st->snake;
while (sn != NULL){
set_cell('x',sn->x,sn->y);
sn = sn->next;
}
// Draw food
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]);
}
}
// Stop the game
if (r){
char message[] = "Koniec";
set_message(message,10,10);
game_over = 1;
}
}
return 0;
}
int main(int argc, char** argv){
start_world(init_game,world_event,free);
return 0;
}