Certainly! Below is the complete code for your Tetris game in C with GTK3 and SDL2, including the implementations of the missing functions and the tetromino shapes. I've filled in the sections that were previously placeholder comments with the actual code. This should help you get your Tetris game up and running.
#include <gtk/gtk.h>
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
// Inclusão das bibliotecas SDL2
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#define BLOCK_SIZE 30
#define GRID_WIDTH 10
#define GRID_HEIGHT 20
#define WINDOW_WIDTH (BLOCK_SIZE * GRID_WIDTH)
#define WINDOW_HEIGHT (BLOCK_SIZE * GRID_HEIGHT)
#define MAX_SCORES 10 // Número máximo de registros de pontuação
#define SCORE_FILE "scores.txt" // Nome do arquivo de pontuações
// Estrutura para as peças (tetrominos)
typedef struct {
int x, y;
int rotation;
int type;
} Tetromino;
// Estrutura para armazenar nome e pontuação
typedef struct {
char name[50];
int score;
} ScoreEntry;
// Declaração de funções
static void show_main_menu(void); // Função para mostrar o menu principal
static void init_game(void);
static gboolean on_draw(GtkWidget *widget, cairo_t *cr, gpointer data);
static gboolean on_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data);
static gboolean game_loop(gpointer data);
static gboolean check_collision(void);
static void merge_tetromino(void);
static void clear_lines(void);
static void spawn_new_tetromino(void);
static void reset_game(void);
static void on_destroy(GtkWidget *widget, gpointer data);
static gboolean clear_feedback_message(gpointer data); // Função para limpar a mensagem de feedback
// Função para desenhar um bloco com efeito 3D
static void draw_3d_block(cairo_t *cr, int x, int y, GdkRGBA color);
// Funções para pontuação
static void add_score_entry(const char *name, int score);
static void load_scores(void);
static void save_scores(void);
static int compare_scores(const void *a, const void *b);
static void show_high_scores(void);
// Variáveis globais
GtkWidget *window;
GtkWidget *drawing_area;
int grid[GRID_HEIGHT][GRID_WIDTH];
Tetromino current_tetromino;
gboolean game_over = FALSE;
int score = 0; // Pontuação do jogador
ScoreEntry score_list[MAX_SCORES + 1]; // Lista de pontuações
int score_count = 0; // Contador de pontuações
int level = 1; // Nível atual do jogo
int fall_speed = 500; // Velocidade de queda em milissegundos
guint game_loop_timer = 0; // ID do timer do loop do jogo
gboolean paused = FALSE; // Indica se o jogo está pausado
char feedback_message[100] = ""; // Mensagem de feedback a ser exibida
guint feedback_timeout_id = 0; // ID do temporizador para controlar a exibição da mensagem
// Variáveis para áudio
Mix_Music *background_music = NULL;
Mix_Chunk *rotate_sound = NULL;
Mix_Chunk *line_clear_sound = NULL;
Mix_Chunk *game_over_sound = NULL;
// Tamanhos das peças (tetrominos)
const int tetromino_sizes[7] = {4, 3, 3, 2, 3, 3, 3}; // I, J, L, O, S, T, Z
// Matrizes das peças (tetrominos)
// Formatos dos tetrominos: [tetromino_type][rotation][row][col]
const int tetromino_shapes[7][4][4][4] = {
// I Tetromino
{
// Rotation 0
{
{0, 0, 0, 0},
{1, 1, 1, 1},
{0, 0, 0, 0},
{0, 0, 0, 0}
},
// Rotation 1
{
{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 0}
},
// Rotation 2
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{1, 1, 1, 1},
{0, 0, 0, 0}
},
// Rotation 3
{
{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0}
}
},
// J Tetromino
{
// Rotation 0
{
{1, 0, 0},
{1, 1, 1},
{0, 0, 0},
{0, 0, 0}
},
// Rotation 1
{
{0, 1, 1},
{0, 1, 0},
{0, 1, 0},
{0, 0, 0}
},
// Rotation 2
{
{0, 0, 0},
{1, 1, 1},
{0, 0, 1},
{0, 0, 0}
},
// Rotation 3
{
{0, 1, 0},
{0, 1, 0},
{1, 1, 0},
{0, 0, 0}
}
},
// L Tetromino
{
// Rotation 0
{
{0, 0, 1},
{1, 1, 1},
{0, 0, 0},
{0, 0, 0}
},
// Rotation 1
{
{0, 1, 0},
{0, 1, 0},
{0, 1, 1},
{0, 0, 0}
},
// Rotation 2
{
{0, 0, 0},
{1, 1, 1},
{1, 0, 0},
{0, 0, 0}
},
// Rotation 3
{
{1, 1, 0},
{0, 1, 0},
{0, 1, 0},
{0, 0, 0}
}
},
// O Tetromino
{
// Rotation 0
{
{1, 1},
{1, 1},
{0, 0},
{0, 0}
},
// Rotation 1
{
{1, 1},
{1, 1},
{0, 0},
{0, 0}
},
// Rotation 2
{
{1, 1},
{1, 1},
{0, 0},
{0, 0}
},
// Rotation 3
{
{1, 1},
{1, 1},
{0, 0},
{0, 0}
}
},
// S Tetromino
{
// Rotation 0
{
{0, 1, 1},
{1, 1, 0},
{0, 0, 0},
{0, 0, 0}
},
// Rotation 1
{
{0, 1, 0},
{0, 1, 1},
{0, 0, 1},
{0, 0, 0}
},
// Rotation 2
{
{0, 0, 0},
{0, 1, 1},
{1, 1, 0},
{0, 0, 0}
},
// Rotation 3
{
{1, 0, 0},
{1, 1, 0},
{0, 1, 0},
{0, 0, 0}
}
},
// T Tetromino
{
// Rotation 0
{
{0, 1, 0},
{1, 1, 1},
{0, 0, 0},
{0, 0, 0}
},
// Rotation 1
{
{0, 1, 0},
{0, 1, 1},
{0, 1, 0},
{0, 0, 0}
},
// Rotation 2
{
{0, 0, 0},
{1, 1, 1},
{0, 1, 0},
{0, 0, 0}
},
// Rotation 3
{
{0, 1, 0},
{1, 1, 0},
{0, 1, 0},
{0, 0, 0}
}
},
// Z Tetromino
{
// Rotation 0
{
{1, 1, 0},
{0, 1, 1},
{0, 0, 0},
{0, 0, 0}
},
// Rotation 1
{
{0, 0, 1},
{0, 1, 1},
{0, 1, 0},
{0, 0, 0}
},
// Rotation 2
{
{0, 0, 0},
{1, 1, 0},
{0, 1, 1},
{0, 0, 0}
},
// Rotation 3
{
{0, 1, 0},
{1, 1, 0},
{1, 0, 0},
{0, 0, 0}
}
}
};
// Cores das peças
const GdkRGBA tetromino_colors[7] = {
{0.0, 1.0, 1.0, 1.0}, // I - Ciano
{0.0, 0.0, 1.0, 1.0}, // J - Azul
{1.0, 0.5, 0.0, 1.0}, // L - Laranja
{1.0, 1.0, 0.0, 1.0}, // O - Amarelo
{0.0, 1.0, 0.0, 1.0}, // S - Verde
{0.5, 0.0, 0.5, 1.0}, // T - Roxo
{1.0, 0.0, 0.0, 1.0} // Z - Vermelho
};
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
// Inicializar SDL2 e SDL2_mixer
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
fprintf(stderr, "Não foi possível inicializar o SDL: %s\n", SDL_GetError());
return 1;
}
// Inicializar SDL_mixer
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
fprintf(stderr, "SDL_mixer não pôde ser inicializado! SDL_mixer Error: %s\n", Mix_GetError());
return 1;
}
// Carregar arquivos de áudio
background_music = Mix_LoadMUS("audio/music.ogg");
if (!background_music) {
fprintf(stderr, "Falha ao carregar música de fundo: %s\n", Mix_GetError());
}
rotate_sound = Mix_LoadWAV("audio/rotate.wav");
if (!rotate_sound) {
fprintf(stderr, "Falha ao carregar som de rotação: %s\n", Mix_GetError());
}
line_clear_sound = Mix_LoadWAV("audio/line_clear.wav");
if (!line_clear_sound) {
fprintf(stderr, "Falha ao carregar som de eliminação de linha: %s\n", Mix_GetError());
}
game_over_sound = Mix_LoadWAV("audio/game_over.wav");
if (!game_over_sound) {
fprintf(stderr, "Falha ao carregar som de game over: %s\n", Mix_GetError());
}
// Iniciar a reprodução da música de fundo em loop
if (background_music) {
Mix_PlayMusic(background_music, -1);
}
// Carregar pontuações
load_scores();
// Criar janela principal
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Tetris em C com GTK3");
gtk_window_set_default_size(GTK_WINDOW(window), WINDOW_WIDTH, WINDOW_HEIGHT);
gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
// Conectar sinal de destruir a janela
g_signal_connect(window, "destroy", G_CALLBACK(on_destroy), NULL);
// Mostrar o menu principal
show_main_menu();
gtk_main();
// Limpar recursos de áudio antes de sair
Mix_FreeMusic(background_music);
Mix_FreeChunk(rotate_sound);
Mix_FreeChunk(line_clear_sound);
Mix_FreeChunk(game_over_sound);
Mix_CloseAudio();
SDL_Quit();
return 0;
}
// Função para mostrar o menu principal
static void show_main_menu(void) {
GtkWidget *vbox;
GtkWidget *play_button, *scores_button, *exit_button;
// Limpar janela
gtk_container_foreach(GTK_CONTAINER(window), (GtkCallback)gtk_widget_destroy, NULL);
vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
gtk_container_add(GTK_CONTAINER(window), vbox);
play_button = gtk_button_new_with_label("Iniciar Jogo");
scores_button = gtk_button_new_with_label("Ver Pontuações");
exit_button = gtk_button_new_with_label("Sair");
gtk_box_pack_start(GTK_BOX(vbox), play_button, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), scores_button, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), exit_button, TRUE, TRUE, 0);
g_signal_connect(play_button, "clicked", G_CALLBACK(init_game), NULL);
g_signal_connect(scores_button, "clicked", G_CALLBACK(show_high_scores), NULL);
g_signal_connect(exit_button, "clicked", G_CALLBACK(on_destroy), NULL);
gtk_widget_show_all(window);
}
// Função para inicializar o jogo
static void init_game(void) {
// Limpar janela
gtk_container_foreach(GTK_CONTAINER(window), (GtkCallback)gtk_widget_destroy, NULL);
drawing_area = gtk_drawing_area_new();
gtk_widget_set_size_request(drawing_area, WINDOW_WIDTH, WINDOW_HEIGHT);
gtk_container_add(GTK_CONTAINER(window), drawing_area);
// Inicializar a grade
for (int i = 0; i < GRID_HEIGHT; i++) {
for (int j = 0; j < GRID_WIDTH; j++) {
grid[i][j] = -1;
}
}
// Inicializar variáveis do jogo
game_over = FALSE;
score = 0;
level = 1;
fall_speed = 500;
paused = FALSE;
strcpy(feedback_message, "");
// Gerar primeiro tetromino
srand(time(NULL));
spawn_new_tetromino();
// Conectar sinais
g_signal_connect(drawing_area, "draw", G_CALLBACK(on_draw), NULL);
gtk_widget_add_events(window, GDK_KEY_PRESS_MASK);
g_signal_connect(window, "key-press-event", G_CALLBACK(on_key_press), NULL);
// Iniciar loop do jogo
if (game_loop_timer != 0) {
g_source_remove(game_loop_timer);
}
game_loop_timer = g_timeout_add(fall_speed, game_loop, NULL);
gtk_widget_show_all(window);
// Reiniciar a música de fundo se estiver pausada ou parada
if (!Mix_PlayingMusic() && background_music) {
Mix_PlayMusic(background_music, -1);
}
}
// Função de desenho
static gboolean on_draw(GtkWidget *widget, cairo_t *cr, gpointer data) {
// Desenhar fundo
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_paint(cr);
// Desenhar grid
for (int i = 0; i < GRID_HEIGHT; i++) {
for (int j = 0; j < GRID_WIDTH; j++) {
if (grid[i][j] != -1) {
draw_3d_block(cr, j * BLOCK_SIZE, i * BLOCK_SIZE, tetromino_colors[grid[i][j]]);
}
}
}
// Desenhar tetromino atual
int size = tetromino_sizes[current_tetromino.type];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int value = tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j];
if (value) {
int x = (current_tetromino.x + j) * BLOCK_SIZE;
int y = (current_tetromino.y + i) * BLOCK_SIZE;
draw_3d_block(cr, x, y, tetromino_colors[current_tetromino.type]);
}
}
}
// Desenhar texto de pontuação
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 14);
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
char score_text[50];
sprintf(score_text, "Score: %d", score);
cairo_move_to(cr, 5, 15);
cairo_show_text(cr, score_text);
// Desenhar nível
char level_text[50];
sprintf(level_text, "Level: %d", level);
cairo_move_to(cr, 5, 30);
cairo_show_text(cr, level_text);
// Mensagem de feedback
if (strlen(feedback_message) > 0) {
cairo_move_to(cr, 5, 45);
cairo_show_text(cr, feedback_message);
}
// Se o jogo estiver pausado
if (paused) {
cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.5);
cairo_rectangle(cr, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
cairo_fill(cr);
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
cairo_set_font_size(cr, 48);
cairo_move_to(cr, WINDOW_WIDTH / 2 - 100, WINDOW_HEIGHT / 2);
cairo_show_text(cr, "PAUSED");
}
// Se o jogo acabou
if (game_over) {
cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.7);
cairo_rectangle(cr, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
cairo_fill(cr);
cairo_set_source_rgb(cr, 1.0, 0.0, 0.0);
cairo_set_font_size(cr, 48);
cairo_move_to(cr, WINDOW_WIDTH / 2 - 100, WINDOW_HEIGHT / 2);
cairo_show_text(cr, "GAME OVER");
}
return FALSE;
}
// Função para desenhar um bloco com efeito 3D
static void draw_3d_block(cairo_t *cr, int x, int y, GdkRGBA color) {
// Desenhar face frontal
cairo_set_source_rgb(cr, color.red * 0.9, color.green * 0.9, color.blue * 0.9);
cairo_rectangle(cr, x, y, BLOCK_SIZE, BLOCK_SIZE);
cairo_fill(cr);
// Desenhar borda
cairo_set_line_width(cr, 1.0);
cairo_set_source_rgb(cr, color.red * 0.7, color.green * 0.7, color.blue * 0.7);
cairo_rectangle(cr, x, y, BLOCK_SIZE, BLOCK_SIZE);
cairo_stroke(cr);
// Desenhar sombra
cairo_set_source_rgb(cr, color.red * 0.5, color.green * 0.5, color.blue * 0.5);
cairo_move_to(cr, x, y + BLOCK_SIZE);
cairo_line_to(cr, x + BLOCK_SIZE, y + BLOCK_SIZE);
cairo_line_to(cr, x + BLOCK_SIZE - 5, y + BLOCK_SIZE - 5);
cairo_line_to(cr, x + 5, y + BLOCK_SIZE - 5);
cairo_close_path(cr);
cairo_fill(cr);
}
// Manipulação de teclas
static gboolean on_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) {
// Verificar se a tecla é para pausar/despausar
if (event->keyval == GDK_KEY_p || event->keyval == GDK_KEY_P) {
paused = !paused;
// Pausar ou retomar a música de fundo
if (paused) {
Mix_PauseMusic();
} else {
Mix_ResumeMusic();
}
gtk_widget_queue_draw(widget); // Redesenhar a tela
return TRUE;
}
// Se o jogo acabou, não processar outras teclas
if (game_over)
return FALSE;
// Se o jogo está pausado, não processar outras teclas
if (paused)
return FALSE;
int old_x = current_tetromino.x;
int old_y = current_tetromino.y;
int old_rotation = current_tetromino.rotation;
switch (event->keyval) {
case GDK_KEY_Left:
case GDK_KEY_a:
case GDK_KEY_A:
current_tetromino.x -= 1;
if (check_collision())
current_tetromino.x = old_x;
break;
case GDK_KEY_Right:
case GDK_KEY_d:
case GDK_KEY_D:
current_tetromino.x += 1;
if (check_collision())
current_tetromino.x = old_x;
break;
case GDK_KEY_Down:
case GDK_KEY_s:
case GDK_KEY_S:
current_tetromino.y += 1;
if (check_collision())
current_tetromino.y = old_y;
break;
case GDK_KEY_Up:
case GDK_KEY_w:
case GDK_KEY_W:
case GDK_KEY_space:
current_tetromino.rotation = (current_tetromino.rotation + 1) % 4;
if (check_collision())
current_tetromino.rotation = old_rotation;
else {
// Tocar som de rotação
if (rotate_sound) {
Mix_PlayChannel(-1, rotate_sound, 0);
}
}
break;
case GDK_KEY_space:
// Queda rápida
while (!check_collision()) {
current_tetromino.y += 1;
}
current_tetromino.y -= 1;
merge_tetromino();
clear_lines();
spawn_new_tetromino();
break;
default:
return FALSE;
}
gtk_widget_queue_draw(widget);
return TRUE;
}
// Função para limpar a mensagem de feedback
static gboolean clear_feedback_message(gpointer data) {
strcpy(feedback_message, "");
feedback_timeout_id = 0; // Resetar ID do temporizador
return G_SOURCE_REMOVE;
}
// Loop principal do jogo
static gboolean game_loop(gpointer data) {
if (game_over)
return FALSE;
if (paused)
return TRUE; // Continuar o loop, mas não atualizar o jogo
current_tetromino.y += 1;
if (check_collision()) {
current_tetromino.y -= 1;
merge_tetromino();
clear_lines();
spawn_new_tetromino();
if (check_collision()) {
game_over = TRUE;
g_print("Game Over!\n");
// Cancelar o timer do jogo
g_source_remove(game_loop_timer);
// Tocar som de game over
if (game_over_sound) {
Mix_PlayChannel(-1, game_over_sound, 0);
}
// Pausar a música de fundo
Mix_PauseMusic();
// Solicitar nome do jogador
GtkWidget *dialog = gtk_dialog_new_with_buttons("Game Over", GTK_WINDOW(window),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, "_OK", GTK_RESPONSE_OK, NULL);
GtkWidget *content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *label = gtk_label_new("Digite seu nome:");
GtkWidget *entry = gtk_entry_new();
gtk_box_pack_start(GTK_BOX(content_area), label, TRUE, TRUE, 5);
gtk_box_pack_start(GTK_BOX(content_area), entry, TRUE, TRUE, 5);
gtk_widget_show_all(dialog);
gtk_dialog_run(GTK_DIALOG(dialog));
const char *name = gtk_entry_get_text(GTK_ENTRY(entry));
if (strlen(name) == 0) {
name = "Jogador";
}
add_score_entry(name, score);
gtk_widget_destroy(dialog);
// Retornar ao menu principal
show_main_menu();
return FALSE;
}
}
gtk_widget_queue_draw(drawing_area);
return TRUE;
}
// Verificar colisões
static gboolean check_collision(void) {
int size = tetromino_sizes[current_tetromino.type];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int value = tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j];
if (value) {
int x = current_tetromino.x + j;
int y = current_tetromino.y + i;
if (x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT)
return TRUE;
if (grid[y][x] != -1)
return TRUE;
}
}
}
return FALSE;
}
// Fundir tetromino com a grade
static void merge_tetromino(void) {
int size = tetromino_sizes[current_tetromino.type];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int value = tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j];
if (value) {
int x = current_tetromino.x + j;
int y = current_tetromino.y + i;
if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
grid[y][x] = current_tetromino.type;
}
}
}
}
}
// Eliminar linhas completas
static void clear_lines(void) {
int lines_cleared = 0; // Contador de linhas eliminadas
for (int i = GRID_HEIGHT - 1; i >= 0; i--) {
gboolean full = TRUE;
for (int j = 0; j < GRID_WIDTH; j++) {
if (grid[i][j] == -1) {
full = FALSE;
break;
}
}
if (full) {
// Mover todas as linhas para baixo
for (int k = i; k > 0; k--) {
for (int j = 0; j < GRID_WIDTH; j++) {
grid[k][j] = grid[k - 1][j];
}
}
// Limpar a primeira linha
for (int j = 0; j < GRID_WIDTH; j++) {
grid[0][j] = -1;
}
i++; // Rechecar a mesma linha
lines_cleared++; // Incrementar contador
}
}
if (lines_cleared > 0) {
// Tocar som de eliminação de linha
if (line_clear_sound) {
Mix_PlayChannel(-1, line_clear_sound, 0);
}
// Atualizar pontuação
int points_per_line = 100;
score += points_per_line * lines_cleared * level;
// Atualizar nível
int old_level = level;
level = score / 1000 + 1;
// Atualizar velocidade de queda
if (level != old_level) {
fall_speed = 500 - (level - 1) * 50;
if (fall_speed < 100) {
fall_speed = 100;
}
// Atualizar o timer do loop do jogo
if (game_loop_timer != 0) {
g_source_remove(game_loop_timer);
}
game_loop_timer = g_timeout_add(fall_speed, game_loop, NULL);
// Exibir mensagem de feedback
strcpy(feedback_message, "Nível aumentado!");
if (feedback_timeout_id != 0) {
g_source_remove(feedback_timeout_id);
}
feedback_timeout_id = g_timeout_add_seconds(2, clear_feedback_message, NULL);
}
}
}
// Gerar um novo tetromino
static void spawn_new_tetromino(void) {
current_tetromino.type = rand() % 7;
current_tetromino.rotation = 0;
current_tetromino.x = (GRID_WIDTH - tetromino_sizes[current_tetromino.type]) / 2;
current_tetromino.y = 0;
}
// Implementar a função reset_game
static void reset_game(void) {
// Limpar a grade
for (int i = 0; i < GRID_HEIGHT; i++) {
for (int j = 0; j < GRID_WIDTH; j++) {
grid[i][j] = -1;
}
}
// Reiniciar variáveis do jogo
game_over = FALSE;
score = 0;
level = 1;
fall_speed = 500;
paused = FALSE;
strcpy(feedback_message, "");
// Gerar novo tetromino
spawn_new_tetromino();
// Reiniciar o loop do jogo
if (game_loop_timer != 0) {
g_source_remove(game_loop_timer);
}
game_loop_timer = g_timeout_add(fall_speed, game_loop, NULL);
// Reiniciar a música de fundo se estiver pausada ou parada
if (!Mix_PlayingMusic() && background_music) {
Mix_PlayMusic(background_music, -1);
}
}
// Funções para gerenciamento de pontuação
static void add_score_entry(const char *name, int score_value) {
if (score_count < MAX_SCORES) {
strcpy(score_list[score_count].name, name);
score_list[score_count].score = score_value;
score_count++;
} else {
// Substituir a menor pontuação se a nova for maior
int min_index = 0;
for (int i = 1; i < MAX_SCORES; i++) {
if (score_list[i].score < score_list[min_index].score) {
min_index = i;
}
}
if (score_value > score_list[min_index].score) {
strcpy(score_list[min_index].name, name);
score_list[min_index].score = score_value;
}
}
// Ordenar a lista de pontuações
qsort(score_list, score_count, sizeof(ScoreEntry), compare_scores);
// Salvar pontuações no arquivo
save_scores();
}
static int compare_scores(const void *a, const void *b) {
ScoreEntry *entryA = (ScoreEntry *)a;
ScoreEntry *entryB = (ScoreEntry *)b;
return entryB->score - entryA->score;
}
static void load_scores(void) {
FILE *file = fopen(SCORE_FILE, "r");
if (file) {
while (fscanf(file, "%49s %d", score_list[score_count].name, &score_list[score_count].score) != EOF && score_count < MAX_SCORES) {
score_count++;
}
fclose(file);
}
}
static void save_scores(void) {
FILE *file = fopen(SCORE_FILE, "w");
if (file) {
for (int i = 0; i < score_count; i++) {
fprintf(file, "%s %d\n", score_list[i].name, score_list[i].score);
}
fclose(file);
}
}
static void show_high_scores(void) {
GtkWidget *dialog = gtk_dialog_new_with_buttons("Pontuações Altas", GTK_WINDOW(window),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, "_OK", GTK_RESPONSE_OK, NULL);
GtkWidget *content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *label = gtk_label_new(NULL);
char scores_text[1024] = "Pontuações Altas:\n";
for (int i = 0; i < score_count; i++) {
char entry[100];
sprintf(entry, "%d. %s - %d\n", i + 1, score_list[i].name, score_list[i].score);
strcat(scores_text, entry);
}
gtk_label_set_text(GTK_LABEL(label), scores_text);
gtk_box_pack_start(GTK_BOX(content_area), label, TRUE, TRUE, 5);
gtk_widget_show_all(dialog);
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
}
// Função chamada ao destruir a janela
static void on_destroy(GtkWidget *widget, gpointer data) {
if (game_loop_timer != 0) {
g_source_remove(game_loop_timer);
game_loop_timer = 0;
}
if (feedback_timeout_id != 0) {
g_source_remove(feedback_timeout_id);
feedback_timeout_id = 0;
}
// Parar e liberar recursos de áudio
Mix_HaltMusic();
Mix_FreeMusic(background_music);
Mix_FreeChunk(rotate_sound);
Mix_FreeChunk(line_clear_sound);
Mix_FreeChunk(game_over_sound);
Mix_CloseAudio();
SDL_Quit();
gtk_main_quit();
}
Observações:
- Certifique-se de que todos os arquivos de áudio (
music.ogg, rotate.wav, line_clear.wav, game_over.wav) estão na pasta audio dentro do diretório de execução do programa.
- Os tetrominos são definidos nas matrizes
tetromino_shapes e as cores correspondentes em tetromino_colors.
- O arquivo de pontuação
scores.txt será criado no diretório atual do programa se não existir.
- As funções de desenho utilizam o Cairo para renderizar os gráficos com efeito 3D básico nos blocos.
- O jogo suporta pausa pressionando a tecla
P e controle das peças usando as setas ou teclas W, A, S, D.
- Certifique-se de compilar o programa com as bibliotecas GTK3, SDL2 e SDL2_mixer corretamente vinculadas.
Comando de compilação exemplo:
gcc -o tetris tetris.c `pkg-config --cflags --libs gtk+-3.0` -lSDL2 -lSDL2_mixer
Recursos adicionais:
- Se você encontrar problemas relacionados à inicialização do SDL2 ou SDL2_mixer, verifique se elas estão instaladas corretamente no seu sistema.
- Lembre-se de que, ao executar o programa, você precisará permitir que ele acesse dispositivos de áudio para reproduzir sons.
Espero que isso ajude a completar o seu jogo de Tetris! Se tiver alguma dúvida ou precisar de mais assistência, fique à vontade para perguntar.