FlappyBird/game.c

126 lines
2.6 KiB
C

#include "game.h"
game* game_create(){
/* Allocate memory */
game* g = malloc(sizeof(game));
/* Set vars */
g->bird = bird_create();
g->num_pipes = WIDTH/PIPE_DISTANCE + 1;
g->pipes = malloc(sizeof(pipe*)*g->num_pipes);
for(int i=0; i<g->num_pipes; i++){
g->pipes[i] = pipe_create();
}
g->score = 0;
g->highscore = 0;
/* Reset level */
game_reset_level(g);
return g;
}
void game_reset_level(game* g){
/* Reset bird */
bird_destroy(g->bird);
g->bird = bird_create();
/* Reset pipes */
for(int i=0; i<g->num_pipes; i++){
g->pipes[i]->pos_x = WIDTH + PIPE_DISTANCE*i;
g->pipes[i]->pos_y = rand()%(HEIGHT-PIPE_HEIGHT-2)+1;
g->pipes[i]->height = PIPE_HEIGHT;
}
/* Reset other vars */
g->score = 0;
}
void game_destroy(game* g){
/* Free memory */
bird_destroy(g->bird);
for(int i=0; i<g->num_pipes; i++){
pipe_destroy(g->pipes[i]);
}
free(g->pipes);
free(g);
}
void game_key_pressed(game* g, char key){
if(key == KEY_JUMP){
g->bird->vel_y = BIRD_VEL_Y_JUMP;
}
}
int game_update(game* g, float dt){
/* Update bird position */
g->bird->vel_y += BIRD_ACC_Y * dt;
g->bird->pos_x += g->bird->vel_x * dt;
g->bird->pos_y += g->bird->vel_y * dt;
/* Check for collisions */
int bird_x = g->bird->pos_x;
for(int i=0; i<g->num_pipes; i++){
if(bird_x == g->pipes[i]->pos_x){
int bird_y = g->bird->pos_y;
if(bird_y < g->pipes[i]->pos_y || bird_y >= g->pipes[i]->pos_y + g->pipes[i]->height){
/* Collision */
return STATE_COLLISION;
}
}
}
if(g->bird->pos_y < 0){
return STATE_COLLISION;
}
/* Move pipes */
for(int i=0; i<g->num_pipes; i++){
/* Check if off screen */
if(g->pipes[i]->pos_x < g->bird->pos_x-CAM_OFFSET_X){
/* Move */
g->pipes[i]->pos_x += g->num_pipes*PIPE_DISTANCE;
g->pipes[i]->pos_y = rand()%(HEIGHT-PIPE_HEIGHT-2)+1;
/* Adjust score */
g->score++;
}
}
return STATE_OKAY;
}
void game_render(game* g){
/* Clear screen */
clear();
/* Init vars */
int delta_x = g->bird->pos_x - CAM_OFFSET_X;
/* Draw ground */
move(HEIGHT, 0);
for(int x=0; x<WIDTH; x++){
addch('=');
}
/* Draw pipes */
for(int i=0; i<g->num_pipes; i++){
/* Only draw if in screen */
if(g->pipes[i]->pos_x >= delta_x && g->pipes[i]->pos_x < delta_x + WIDTH){
int x = g->pipes[i]->pos_x - delta_x;
for(int y=0; y<g->pipes[i]->pos_y; y++){
mvaddch(HEIGHT-1-y, x, '#');
}
for(int y=g->pipes[i]->pos_y+g->pipes[i]->height+1; y<HEIGHT; y++){
mvaddch(HEIGHT-1-y, x, '#');
}
}
}
/* Draw bird */
mvaddch(HEIGHT-1-g->bird->pos_y, CAM_OFFSET_X, 'v');
/* Draw score */
char text[50];
sprintf(text, "Score: %d\tBest: %d", g->score, g->highscore);
mvaddstr(HEIGHT+1, 1, text);
}