Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Converta para C++ puro, que deverá ser executado em ambiente gráfico. // tetris.c…

  1. User

    Converta para C++ puro, que deverá ser executado em ambiente gráfico. // tetris.c #include <gtk/gtk.h> #include <cairo.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <stdio.h> #include <math.h> // Necessário para funções matemáticas #include <SDL2/SDL.h> // Biblioteca SDL2 para áudio

    #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); // Funções para áudio static void init_audio(void); static void play_sound(float frequency, int duration_ms); static void close_audio(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

    // SDL áudio SDL_AudioDeviceID audio_device; SDL_AudioSpec audio_spec;

    float volume = 0.5f; // Volume inicial (50%)

    // 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) const int tetromino_shapes[7][4][4][4] = { // I (Tipo 0) { {{0,0,0,0}, {1,1,1,1}, {0,0,0,0}, {0,0,0,0}}, {{0,0,1,0}, {0,0,1,0}, {0,0,1,0}, {0,0,1,0}}, {{0,0,0,0}, {0,0,0,0}, {1,1,1,1}, {0,0,0,0}}, {{0,1,0,0}, {0,1,0,0}, {0,1,0,0}, {0,1,0,0}} }, // J (Tipo 1) { {{1,0,0}, {1,1,1}, {0,0,0}}, {{0,1,1}, {0,1,0}, {0,1,0}}, {{0,0,0}, {1,1,1}, {0,0,1}}, {{0,1,0}, {0,1,0}, {1,1,0}} }, // L (Tipo 2) { {{0,0,1}, {1,1,1}, {0,0,0}}, {{0,1,0}, {0,1,0}, {0,1,1}}, {{0,0,0}, {1,1,1}, {1,0,0}}, {{1,1,0}, {0,1,0}, {0,1,0}} }, // O (Tipo 3) { {{1,1}, {1,1}}, {{1,1}, {1,1}}, {{1,1}, {1,1}}, {{1,1}, {1,1}} }, // S (Tipo 4) { {{0,1,1}, {1,1,0}, {0,0,0}}, {{0,1,0}, {0,1,1}, {0,0,1}}, {{0,0,0}, {0,1,1}, {1,1,0}}, {{1,0,0}, {1,1,0}, {0,1,0}} }, // T (Tipo 5) { {{0,1,0}, {1,1,1}, {0,0,0}}, {{0,1,0}, {0,1,1}, {0,1,0}}, {{0,0,0}, {1,1,1}, {0,1,0}}, {{0,1,0}, {1,1,0}, {0,1,0}} }, // Z (Tipo 6) { {{1,1,0}, {0,1,1}, {0,0,0}}, {{0,0,1}, {0,1,1}, {0,1,0}}, {{0,0,0}, {1,1,0}, {0,1,1}}, {{0,1,0}, {1,1,0}, {1,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 áudio
    init_audio();
    
    // 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();
    
    // Fechar áudio
    close_audio();
    
    return 0;
    

    }

    // Função para inicializar o áudio static void init_audio(void) { if (SDL_Init(SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Não foi possível inicializar o SDL2: %s\n", SDL_GetError()); exit(1); }

    SDL_zero(audio_spec);
    audio_spec.freq = 44100;
    audio_spec.format = AUDIO_F32SYS;
    audio_spec.channels = 1;
    audio_spec.samples = 1024;
    audio_spec.callback = NULL;
    
    audio_device = SDL_OpenAudioDevice(NULL, 0, &audio_spec, NULL, 0);
    if (audio_device == 0) {
        fprintf(stderr, "Não foi possível abrir o dispositivo de áudio: %s\n", SDL_GetError());
        exit(1);
    }
    
    SDL_PauseAudioDevice(audio_device, 0);
    

    }

    // Função para reproduzir um som (modificada para incluir o volume) static void play_sound(float frequency, int duration_ms) { int sample_count = (audio_spec.freq * duration_ms) / 1000; float *buffer = (float *)malloc(sample_count * sizeof(float));

    if (buffer == NULL) {
        fprintf(stderr, "Falha ao alocar o buffer de áudio\n");
        return;
    }
    
    for (int i = 0; i < sample_count; i++) {
        float time = (float)i / audio_spec.freq;
        buffer[i] = sinf(2 * M_PI * frequency * time) * 0.5f * volume; // Multiplica pela variável volume
    }
    
    SDL_QueueAudio(audio_device, buffer, sample_count * sizeof(float));
    free(buffer);
    

    }

    // Função para fechar o áudio static void close_audio(void) { SDL_CloseAudioDevice(audio_device); SDL_Quit(); }

    // Função para mostrar o menu principal static void show_main_menu(void) { GtkWidget *vbox; GtkWidget *btn_start; GtkWidget *btn_scores; GtkWidget *btn_exit;

    // Limpar o conteúdo da janela (caso haja algo)
    GList *children = gtk_container_get_children(GTK_CONTAINER(window));
    for (GList *iter = children; iter != NULL; iter = g_list_next(iter)) {
        gtk_widget_destroy(GTK_WIDGET(iter->data));
    }
    g_list_free(children);
    
    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
    gtk_container_add(GTK_CONTAINER(window), vbox);
    
    btn_start = gtk_button_new_with_label("Iniciar Jogo");
    btn_scores = gtk_button_new_with_label("Ver Pontuações");
    btn_exit = gtk_button_new_with_label("Sair");
    
    gtk_box_pack_start(GTK_BOX(vbox), btn_start, TRUE, TRUE, 10);
    gtk_box_pack_start(GTK_BOX(vbox), btn_scores, TRUE, TRUE, 10);
    gtk_box_pack_start(GTK_BOX(vbox), btn_exit, TRUE, TRUE, 10);
    
    g_signal_connect(btn_start, "clicked", G_CALLBACK(init_game), NULL);
    g_signal_connect(btn_scores, "clicked", G_CALLBACK(show_high_scores), NULL);
    g_signal_connect(btn_exit, "clicked", G_CALLBACK(gtk_main_quit), NULL);
    
    gtk_widget_show_all(window);
    

    }

    // Função para inicializar o jogo static void init_game(void) { // Limpar o conteúdo da janela (menu) GList *children = gtk_container_get_children(GTK_CONTAINER(window)); for (GList *iter = children; iter != NULL; iter = g_list_next(iter)) { gtk_widget_destroy(GTK_WIDGET(iter->data)); } g_list_free(children);

    // Criar área de desenho
    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);
    
    // Conectar sinais
    g_signal_connect(drawing_area, "draw", G_CALLBACK(on_draw), NULL);
    g_signal_connect(window, "key-press-event", G_CALLBACK(on_key_press), NULL);
    
    // Mostrar a janela
    gtk_widget_show_all(window);
    
    srand(time(NULL));
    
    // 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
    score = 0;
    level = 1;
    fall_speed = 500; // Velocidade inicial
    game_over = FALSE;
    paused = FALSE;
    
    // Limpar mensagem de feedback
    feedback_message[0] = '\0';
    if (feedback_timeout_id != 0) {
        g_source_remove(feedback_timeout_id);
        feedback_timeout_id = 0;
    }
    
    // Criar o primeiro tetromino
    current_tetromino.type = rand() % 7;
    current_tetromino.rotation = 0;
    // Ajustar posição inicial
    current_tetromino.x = (GRID_WIDTH - tetromino_sizes[current_tetromino.type]) / 2;
    current_tetromino.y = 0;
    
    // 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);
    

    }

    // Função de desenho (inclui exibição do volume) static gboolean on_draw(GtkWidget *widget, cairo_t *cr, gpointer data) { // Desenhar o fundo com um gradiente vertical cairo_pattern_t *bg_gradient = cairo_pattern_create_linear(0, 0, 0, WINDOW_HEIGHT); cairo_pattern_add_color_stop_rgb(bg_gradient, 0.0, 0.1, 0.1, 0.1); cairo_pattern_add_color_stop_rgb(bg_gradient, 1.0, 0.3, 0.3, 0.3); cairo_set_source(cr, bg_gradient); cairo_paint(cr); cairo_pattern_destroy(bg_gradient);

    // Desenhar a grade (peças fixas)
    for (int i = 0; i < GRID_HEIGHT; i++) {
        for (int j = 0; j < GRID_WIDTH; j++) {
            if (grid[i][j] != -1) {
                GdkRGBA color = tetromino_colors[grid[i][j]];
                draw_3d_block(cr, j * BLOCK_SIZE, i * BLOCK_SIZE, color);
            }
        }
    }
    
    // Desenhar o tetromino atual
    int size = tetromino_sizes[current_tetromino.type];
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j]) {
                int x = current_tetromino.x + j;
                int y = current_tetromino.y + i;
                if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
                    GdkRGBA color = tetromino_colors[current_tetromino.type];
                    draw_3d_block(cr, x * BLOCK_SIZE, y * BLOCK_SIZE, color);
                }
            }
        }
    }
    
    // Desenhar a pontuação e nível atual
    cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
    cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
    cairo_set_font_size(cr, 20);
    
    char score_text[50];
    snprintf(score_text, sizeof(score_text), "Pontuação: %d", score);
    cairo_move_to(cr, 10, 25);
    cairo_show_text(cr, score_text);
    
    char level_text[50];
    snprintf(level_text, sizeof(level_text), "Nível: %d", level);
    cairo_move_to(cr, 10, 50);
    cairo_show_text(cr, level_text);
    
    // Desenhar o volume atual
    char volume_text[50];
    snprintf(volume_text, sizeof(volume_text), "Volume: %.0f%%", volume * 100.0f);
    cairo_move_to(cr, 10, 75);
    cairo_show_text(cr, volume_text);
    
    // Verificar se o jogo está pausado
    if (paused) {
        // Desenhar uma sobreposição semitransparente
        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);
    
        // Desenhar o texto "Jogo Pausado"
        cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
        cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cr, 40);
        cairo_text_extents_t extents;
        const char *pause_text = "Jogo Pausado";
        cairo_text_extents(cr, pause_text, &extents);
        cairo_move_to(cr, (WINDOW_WIDTH - extents.width) / 2 - extents.x_bearing, WINDOW_HEIGHT / 2);
        cairo_show_text(cr, pause_text);
    }
    
    // Verificar se há uma mensagem de feedback para exibir
    if (feedback_message[0] != '\0') {
        // Desenhar uma sobreposição semitransparente
        cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.6);
        cairo_rectangle(cr, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
        cairo_fill(cr);
    
        // Desenhar o texto da mensagem de feedback
        cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
        cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cr, 30);
        cairo_text_extents_t extents;
        cairo_text_extents(cr, feedback_message, &extents);
        cairo_move_to(cr, (WINDOW_WIDTH - extents.width) / 2 - extents.x_bearing, WINDOW_HEIGHT / 2);
        cairo_show_text(cr, feedback_message);
    }
    
    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) { double x0 = x; double y0 = y; double width = BLOCK_SIZE; double height = BLOCK_SIZE;

    // Cor principal do bloco
    cairo_pattern_t *gradient = cairo_pattern_create_linear(x0, y0, x0, y0 + height);
    cairo_pattern_add_color_stop_rgb(gradient, 0.0, color.red * 0.9, color.green * 0.9, color.blue * 0.9);
    cairo_pattern_add_color_stop_rgb(gradient, 1.0, color.red * 0.6, color.green * 0.6, color.blue * 0.6);
    
    cairo_set_source(cr, gradient);
    cairo_rectangle(cr, x0, y0, width, height);
    cairo_fill(cr);
    cairo_pattern_destroy(gradient);
    
    // Borda do bloco
    cairo_set_line_width(cr, 1.0);
    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_rectangle(cr, x0, y0, width, height);
    cairo_stroke(cr);
    
    // Destaque superior
    cairo_pattern_t *highlight = cairo_pattern_create_linear(x0, y0, x0, y0 + height / 2);
    cairo_pattern_add_color_stop_rgba(highlight, 0.0, 1.0, 1.0, 1.0, 0.4);
    cairo_pattern_add_color_stop_rgba(highlight, 1.0, 1.0, 1.0, 1.0, 0.0);
    
    cairo_set_source(cr, highlight);
    cairo_rectangle(cr, x0, y0, width, height / 2);
    cairo_fill(cr);
    cairo_pattern_destroy(highlight);
    
    // Sombra inferior
    cairo_pattern_t *shadow = cairo_pattern_create_linear(x0, y0 + height / 2, x0, y0 + height);
    cairo_pattern_add_color_stop_rgba(shadow, 0.0, 0.0, 0.0, 0.0, 0.0);
    cairo_pattern_add_color_stop_rgba(shadow, 1.0, 0.0, 0.0, 0.0, 0.4);
    
    cairo_set_source(cr, shadow);
    cairo_rectangle(cr, x0, y0 + height / 2, width, height / 2);
    cairo_fill(cr);
    cairo_pattern_destroy(shadow);
    

    }

    // Manipulação de teclas static gboolean on_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) { // Controle de volume if (event->keyval == GDK_KEY_equal || event->keyval == GDK_KEY_plus) { // Tecla '+' volume += 0.1f; if (volume > 1.0f) volume = 1.0f; // Limitar ao máximo de 1.0

        // Definir a mensagem de feedback
        snprintf(feedback_message, sizeof(feedback_message), "Volume: %.0f%%", volume * 100.0f);
        gtk_widget_queue_draw(widget);
    
        // Configurar o temporizador para limpar a mensagem após 2 segundos
        if (feedback_timeout_id != 0)
            g_source_remove(feedback_timeout_id); // Remover temporizador existente
        feedback_timeout_id = g_timeout_add_seconds(2, clear_feedback_message, NULL);
    
        return TRUE;
    }
    if (event->keyval == GDK_KEY_minus || event->keyval == GDK_KEY_underscore) { // Tecla '-'
        volume -= 0.1f;
        if (volume < 0.0f) volume = 0.0f; // Limitar ao mínimo de 0.0
    
        // Definir a mensagem de feedback
        snprintf(feedback_message, sizeof(feedback_message), "Volume: %.0f%%", volume * 100.0f);
        gtk_widget_queue_draw(widget);
    
        // Configurar o temporizador para limpar a mensagem após 2 segundos
        if (feedback_timeout_id != 0)
            g_source_remove(feedback_timeout_id); // Remover temporizador existente
        feedback_timeout_id = g_timeout_add_seconds(2, clear_feedback_message, NULL);
    
        return TRUE;
    }
    
    // Verificar se a tecla é para pausar/despausar
    if (event->keyval == GDK_KEY_p || event->keyval == GDK_KEY_P) {
        paused = !paused;
        gtk_widget_queue_draw(widget); // Redesenhar a tela
    
        // Tocar som de pausa
        play_sound(262.0f, 100); // Toca um tom de 262Hz por 100ms
    
        return TRUE;
    }
    
    // Verificar se a tecla é para reiniciar o jogo
    if (event->keyval == GDK_KEY_r || event->keyval == GDK_KEY_R) {
        reset_game();
    
        // Definir a mensagem de feedback
        strcpy(feedback_message, "Jogo Reiniciado!");
        gtk_widget_queue_draw(widget);
    
        // Configurar o temporizador para limpar a mensagem após 2 segundos
        if (feedback_timeout_id != 0)
            g_source_remove(feedback_timeout_id); // Remover temporizador existente
        feedback_timeout_id = g_timeout_add_seconds(2, clear_feedback_message, NULL);
    
        return TRUE;
    }
    
    // Verificar se a tecla é para sair do jogo
    if (event->keyval == GDK_KEY_s || event->keyval == GDK_KEY_S) {
        // Definir a mensagem de feedback
        strcpy(feedback_message, "Saindo do Jogo...");
        gtk_widget_queue_draw(widget);
    
        // Configurar o temporizador para sair do jogo após 1 segundo
        g_timeout_add_seconds(1, (GSourceFunc)gtk_main_quit, NULL);
    
        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:
            current_tetromino.x -= 1;
            if (check_collision())
                current_tetromino.x = old_x;
            break;
        case GDK_KEY_Right:
            current_tetromino.x += 1;
            if (check_collision())
                current_tetromino.x = old_x;
            break;
        case GDK_KEY_Down:
            current_tetromino.y += 1;
            if (check_collision())
                current_tetromino.y = old_y;
            break;
        case GDK_KEY_Up:
            current_tetromino.rotation = (current_tetromino.rotation + 1) % 4;
            if (check_collision())
                current_tetromino.rotation = old_rotation;
            break;
    }
    
    gtk_widget_queue_draw(widget);
    return TRUE;
    

    }

    // Função para limpar a mensagem de feedback static gboolean clear_feedback_message(gpointer data) { feedback_message[0] = '\0'; // Limpar a mensagem feedback_timeout_id = 0; gtk_widget_queue_draw(drawing_area); // Redesenhar a tela return G_SOURCE_REMOVE; // Remover o temporizador }

    // 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();
    
        // Tocar som de peça fixada
        play_sound(330.0f, 100); // Toca um tom de 330Hz por 100ms
    
        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 fim de jogo
            play_sound(196.0f, 500); // Toca um tom de 196Hz por 500ms
    
            // Mostrar mensagem de fim de jogo e solicitar nome
            GtkWidget *dialog;
            GtkWidget *content_area;
            GtkWidget *entry;
            GtkWidget *label;
            dialog = gtk_dialog_new_with_buttons("Fim de Jogo",
                                                 GTK_WINDOW(window),
                                                 GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                                 "OK",
                                                 GTK_RESPONSE_OK,
                                                 NULL);
            content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
            label = gtk_label_new("Insira seu nome:");
            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 *player_name = gtk_entry_get_text(GTK_ENTRY(entry));
            if (strlen(player_name) == 0)
                player_name = "Anônimo";
            add_score_entry(player_name, score);
            gtk_widget_destroy(dialog);
    
            // Mostrar pontuações
            show_high_scores();
    
            // Perguntar se o jogador quer reiniciar ou voltar ao menu
            dialog = gtk_message_dialog_new(GTK_WINDOW(window),
                                            GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                            GTK_MESSAGE_INFO,
                                            GTK_BUTTONS_NONE,
                                            "Deseja jogar novamente ou voltar ao menu?");
            gtk_window_set_title(GTK_WINDOW(dialog), "Reiniciar ou Menu");
    
            // Adicionar botões 'Reiniciar', 'Menu' e 'Sair'
            gtk_dialog_add_buttons(GTK_DIALOG(dialog),
                                   "Reiniciar", GTK_RESPONSE_YES,
                                   "Menu", GTK_RESPONSE_APPLY,
                                   "Sair", GTK_RESPONSE_CANCEL,
                                   NULL);
    
            // Mostrar o diálogo e esperar pela resposta
            gint response = gtk_dialog_run(GTK_DIALOG(dialog));
            gtk_widget_destroy(dialog);
            if (response == GTK_RESPONSE_YES) {
                reset_game();
            } else if (response == GTK_RESPONSE_APPLY) {
                show_main_menu();
            } else {
                gtk_main_quit();
            }
            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++) { if (tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j]) { int x = current_tetromino.x + j; int y = current_tetromino.y + i;

                if (x < 0 || x >= GRID_WIDTH || y >= GRID_HEIGHT)
                    return TRUE;
                if (y >= 0 && 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++) { if (tetromino_shapes[current_tetromino.type][current_tetromino.rotation][i][j]) { int x = current_tetromino.x + j; int y = current_tetromino.y + i; if (y >= 0 && y < GRID_HEIGHT && x >= 0 && x < GRID_WIDTH) { 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 } } // Incrementar a pontuação com base nas linhas eliminadas if (lines_cleared > 0) { // Tocar som de linha eliminada play_sound(440.0f, 150); // Toca um tom de 440Hz por 150ms

        int points = 0;
        switch (lines_cleared) {
            case 1:
                points = 100;
                break;
            case 2:
                points = 300;
                break;
            case 3:
                points = 500;
                break;
            case 4:
                points = 800;
                break;
            default:
                points = lines_cleared * 200;
                break;
        }
        score += points;
    
        // Atualizar nível e velocidade
        int new_level = score / 1000 + 1;
        if (new_level > level) {
            level = new_level;
            // Aumentar a velocidade (diminuir o intervalo do timer)
            if (fall_speed > 50) { // Limite mínimo de velocidade
                fall_speed -= 50;
            }
            // Reagendar o timer do jogo
            g_source_remove(game_loop_timer);
            game_loop_timer = g_timeout_add(fall_speed, game_loop, NULL);
        }
    }
    

    }

    // Gerar um novo tetromino static void spawn_new_tetromino(void) { current_tetromino.type = rand() % 7; current_tetromino.rotation = 0; // Ajustar posição inicial 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) { // Resetar a grade for (int i = 0; i < GRID_HEIGHT; i++) for (int j = 0; j < GRID_WIDTH; j++) grid[i][j] = -1;

    // Resetar o tetromino atual
    current_tetromino.type = rand() % 7;
    current_tetromino.rotation = 0;
    current_tetromino.x = (GRID_WIDTH - tetromino_sizes[current_tetromino.type]) / 2;
    current_tetromino.y = 0;
    
    // Resetar pontuação e nível
    score = 0;
    level = 1;
    fall_speed = 500;
    game_over = FALSE;
    paused = FALSE;
    
    gtk_widget_queue_draw(drawing_area);
    
    // Limpar mensagem de feedback
    feedback_message[0] = '\0';
    if (feedback_timeout_id != 0) {
        g_source_remove(feedback_timeout_id);
        feedback_timeout_id = 0;
    }
    
    // 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);
    

    }

    // Função para adicionar uma nova pontuação static void add_score_entry(const char *name, int score_value) { // Verificar se a pontuação entra no top 10 if (score_count < MAX_SCORES) { score_list[score_count].score = score_value; strncpy(score_list[score_count].name, name, sizeof(score_list[score_count].name)); score_list[score_count].name[sizeof(score_list[score_count].name) - 1] = '\0'; // Garantir terminação score_count++; } else if (score_value > score_list[MAX_SCORES - 1].score) { score_list[MAX_SCORES - 1].score = score_value; strncpy(score_list[MAX_SCORES - 1].name, name, sizeof(score_list[MAX_SCORES - 1].name)); score_list[MAX_SCORES - 1].name[sizeof(score_list[MAX_SCORES - 1].name) - 1] = '\0'; // Garantir terminação } else { // A pontuação não entra no top 10 return; }

    // Ordenar a lista de pontuações
    qsort(score_list, score_count, sizeof(ScoreEntry), compare_scores);
    
    // Manter somente as 10 melhores pontuações
    if (score_count > MAX_SCORES)
        score_count = MAX_SCORES;
    
    // Salvar as pontuações no arquivo
    save_scores();
    

    }

    // Função para carregar as pontuações do arquivo static void load_scores(void) { FILE *file = fopen(SCORE_FILE, "r"); if (file) { score_count = 0; while (fscanf(file, "%49[^;];%d\n", score_list[score_count].name, &score_list[score_count].score) == 2) { score_count++; if (score_count >= MAX_SCORES) break; } fclose(file); } }

    // Função para salvar as pontuações no arquivo 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); } }

    // Função de comparação para ordenar as pontuações static int compare_scores(const void *a, const void *b) { ScoreEntry *entryA = (ScoreEntry *)a; ScoreEntry *entryB = (ScoreEntry *)b; return entryB->score - entryA->score; // Ordem decrescente }

    // Função para exibir as pontuações static void show_high_scores(void) { // Se chamada a partir do menu, certifique-se de que a janela está configurada corretamente if (!GTK_IS_WINDOW(window)) { 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); g_signal_connect(window, "destroy", G_CALLBACK(on_destroy), NULL); gtk_widget_show_all(window); }

    GtkWidget *dialog;
    GtkWidget *content_area;
    GtkWidget *label;
    char scores_text[2048] = "Top 10 Pontuações:\n";
    char line[200];
    
    for (int i = 0; i < score_count; i++) {
        snprintf(line, sizeof(line), "%d. %s - %d pontos\n", i + 1, score_list[i].name, score_list[i].score);
        strncat(scores_text, line, sizeof(scores_text) - strlen(scores_text) - 1);
    }
    
    dialog = gtk_dialog_new_with_buttons("Pontuações",
                                         GTK_WINDOW(window),
                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                         "OK",
                                         GTK_RESPONSE_OK,
                                         NULL);
    content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
    label = gtk_label_new(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; }

    // Fechar áudio
    close_audio();
    
    gtk_main_quit();
    

    }

  2. Assistant

    Certamente! Vamos converter seu jogo Tetris de C com GTK3 e SDL2 para C++ puro, utilizando a biblioteca SFML (Simple and Fast Multimedia Library) para o ambiente gráfico e áudio. A SFML é uma biblioteca multimídia escrita em C++ que facilita a criação de aplicações gráficas e jogos.

    A seguir, apresento o código em C++ utilizando a SFML:

    // tetris.cpp
    
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
    #include <vector>
    #include <string>
    #include <fstream>
    #include <iostream>
    #include <cmath>
    #include <ctime>
    #include <cstdlib>
    #include <algorithm>
    
    const int BLOCK_SIZE = 30;
    const int GRID_WIDTH = 10;
    const int GRID_HEIGHT = 20;
    const int WINDOW_WIDTH = BLOCK_SIZE * GRID_WIDTH;
    const int WINDOW_HEIGHT = BLOCK_SIZE * GRID_HEIGHT;
    const int MAX_SCORES = 10;
    const std::string SCORE_FILE = "scores.txt";
    
    // Estrutura para as peças (tetrominos)
    struct Tetromino {
        int x, y;
        int rotation;
        int type;
    };
    
    // Estrutura para armazenar nome e pontuação
    struct ScoreEntry {
        std::string name;
        int score;
    };
    
    // Declaração de funções
    void initGame();
    void gameLoop(sf::RenderWindow& window);
    void handleEvents(sf::RenderWindow& window);
    void updateGame();
    void drawGame(sf::RenderWindow& window);
    bool checkCollision();
    void mergeTetromino();
    void clearLines();
    void spawnNewTetromino();
    void resetGame();
    void addScoreEntry(const std::string& name, int score);
    void loadScores();
    void saveScores();
    void playSound(float frequency, int duration_ms);
    
    // Variáveis globais
    int grid[GRID_HEIGHT][GRID_WIDTH];
    Tetromino currentTetromino;
    bool gameOver = false;
    int score = 0;
    std::vector<ScoreEntry> scoreList;
    int level = 1;
    int fallSpeed = 500; // Velocidade de queda em milissegundos
    bool paused = false;
    float volume = 50.0f; // Volume percentual (0-100)
    
    // Controles de tempo
    sf::Clock fallClock;
    
    // Recursos SFML
    sf::Font font;
    
    // Tamanhos das peças (tetrominos)
    const int tetrominoSizes[7] = {4, 3, 3, 2, 3, 3, 3};
    
    // Matrizes das peças (tetrominos)
    const int tetrominoShapes[7][4][4][4] = {
        // I (Tipo 0)
        {
            {{0,0,0,0},
             {1,1,1,1},
             {0,0,0,0},
             {0,0,0,0}},
            {{0,0,1,0},
             {0,0,1,0},
             {0,0,1,0},
             {0,0,1,0}},
            {{0,0,0,0},
             {0,0,0,0},
             {1,1,1,1},
             {0,0,0,0}},
            {{0,1,0,0},
             {0,1,0,0},
             {0,1,0,0},
             {0,1,0,0}}
        },
        // J (Tipo 1)
        {
            {{1,0,0},
             {1,1,1},
             {0,0,0}},
            {{0,1,1},
             {0,1,0},
             {0,1,0}},
            {{0,0,0},
             {1,1,1},
             {0,0,1}},
            {{0,1,0},
             {0,1,0},
             {1,1,0}}
        },
        // L (Tipo 2)
        {
            {{0,0,1},
             {1,1,1},
             {0,0,0}},
            {{0,1,0},
             {0,1,0},
             {0,1,1}},
            {{0,0,0},
             {1,1,1},
             {1,0,0}},
            {{1,1,0},
             {0,1,0},
             {0,1,0}}
        },
        // O (Tipo 3)
        {
            {{1,1},
             {1,1}},
            {{1,1},
             {1,1}},
            {{1,1},
             {1,1}},
            {{1,1},
             {1,1}}
        },
        // S (Tipo 4)
        {
            {{0,1,1},
             {1,1,0},
             {0,0,0}},
            {{0,1,0},
             {0,1,1},
             {0,0,1}},
            {{0,0,0},
             {0,1,1},
             {1,1,0}},
            {{1,0,0},
             {1,1,0},
             {0,1,0}}
        },
        // T (Tipo 5)
        {
            {{0,1,0},
             {1,1,1},
             {0,0,0}},
            {{0,1,0},
             {0,1,1},
             {0,1,0}},
            {{0,0,0},
             {1,1,1},
             {0,1,0}},
            {{0,1,0},
             {1,1,0},
             {0,1,0}}
        },
        // Z (Tipo 6)
        {
            {{1,1,0},
             {0,1,1},
             {0,0,0}},
            {{0,0,1},
             {0,1,1},
             {0,1,0}},
            {{0,0,0},
             {1,1,0},
             {0,1,1}},
            {{0,1,0},
             {1,1,0},
             {1,0,0}}
        }
    };
    
    // Cores das peças
    const sf::Color tetrominoColors[7] = {
        sf::Color::Cyan,          // I - Ciano
        sf::Color::Blue,          // J - Azul
        sf::Color(255, 165, 0),   // L - Laranja
        sf::Color::Yellow,        // O - Amarelo
        sf::Color::Green,         // S - Verde
        sf::Color(128, 0, 128),   // T - Roxo
        sf::Color::Red            // Z - Vermelho
    };
    
    int main() {
        srand(static_cast<unsigned int>(time(nullptr)));
    
        // Carregar recursos
        if (!font.loadFromFile("arial.ttf")) {
            std::cerr << "Erro ao carregar a fonte.\n";
            return -1;
        }
    
        // Carregar pontuações
        loadScores();
    
        // Criar a janela principal
        sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Tetris em C++ com SFML");
    
        initGame();
    
        // Iniciar o loop do jogo
        while (window.isOpen()) {
            handleEvents(window);
    
            if (!gameOver && !paused) {
                updateGame();
            }
    
            // Limpar a janela
            window.clear(sf::Color(50, 50, 50));
    
            // Desenhar o jogo
            drawGame(window);
    
            // Atualizar a janela
            window.display();
        }
    
        return 0;
    }
    
    // Inicializar o jogo
    void initGame() {
        // 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
        score = 0;
        level = 1;
        fallSpeed = 500;
        gameOver = false;
        paused = false;
    
        // Criar o primeiro tetromino
        currentTetromino.type = rand() % 7;
        currentTetromino.rotation = 0;
        currentTetromino.x = (GRID_WIDTH - tetrominoSizes[currentTetromino.type]) / 2;
        currentTetromino.y = 0;
    
        fallClock.restart();
    }
    
    // Manipular eventos
    void handleEvents(sf::RenderWindow& window) {
        sf::Event event;
        while (window.pollEvent(event)) {
            // Fechar a janela
            if (event.type == sf::Event::Closed) {
                window.close();
            }
    
            // Tecla pressionada
            if (event.type == sf::Event::KeyPressed) {
                // Controle de volume
                if (event.key.code == sf::Keyboard::Add) {
                    volume += 10.0f;
                    if (volume > 100.0f)
                        volume = 100.0f;
                    // Mensagem de feedback ou som podem ser adicionados aqui
                }
                if (event.key.code == sf::Keyboard::Subtract) {
                    volume -= 10.0f;
                    if (volume < 0.0f)
                        volume = 0.0f;
                    // Mensagem de feedback ou som podem ser adicionados aqui
                }
                if (event.key.code == sf::Keyboard::P) {
                    paused = !paused;
                    // Tocar som de pausa
                    playSound(262.0f, 100);
                }
                if (event.key.code == sf::Keyboard::R) {
                    resetGame();
                    // Mensagem de feedback ou som podem ser adicionados aqui
                }
                if (event.key.code == sf::Keyboard::S) {
                    window.close();
                }
    
                if (!gameOver && !paused) {
                    int oldX = currentTetromino.x;
                    int oldY = currentTetromino.y;
                    int oldRotation = currentTetromino.rotation;
    
                    if (event.key.code == sf::Keyboard::Left) {
                        currentTetromino.x -= 1;
                        if (checkCollision())
                            currentTetromino.x = oldX;
                    }
                    if (event.key.code == sf::Keyboard::Right) {
                        currentTetromino.x += 1;
                        if (checkCollision())
                            currentTetromino.x = oldX;
                    }
                    if (event.key.code == sf::Keyboard::Down) {
                        currentTetromino.y += 1;
                        if (checkCollision())
                            currentTetromino.y = oldY;
                    }
                    if (event.key.code == sf::Keyboard::Up) {
                        currentTetromino.rotation = (currentTetromino.rotation + 1) % 4;
                        if (checkCollision())
                            currentTetromino.rotation = oldRotation;
                    }
                }
            }
        }
    }
    
    // Atualizar o jogo
    void updateGame() {
        if (fallClock.getElapsedTime().asMilliseconds() >= fallSpeed) {
            currentTetromino.y += 1;
    
            if (checkCollision()) {
                currentTetromino.y -= 1;
                mergeTetromino();
                playSound(330.0f, 100);
                clearLines();
                spawnNewTetromino();
                if (checkCollision()) {
                    gameOver = true;
                    std::cout << "Game Over!\n";
                    playSound(196.0f, 500);
                    // Tratar lógica de fim de jogo (por exemplo, solicitar nome e salvar pontuação)
                    // Para simplificar, reiniciamos o jogo
                    resetGame();
                }
            }
    
            fallClock.restart();
        }
    }
    
    // Desenhar o jogo
    void drawGame(sf::RenderWindow& window) {
        // Desenhar a grade
        for (int i = 0; i < GRID_HEIGHT; ++i) {
            for (int j = 0; j < GRID_WIDTH; ++j) {
                if (grid[i][j] != -1) {
                    sf::RectangleShape block(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
                    block.setPosition(j * BLOCK_SIZE, i * BLOCK_SIZE);
                    block.setFillColor(tetrominoColors[grid[i][j]]);
                    block.setOutlineThickness(1);
                    block.setOutlineColor(sf::Color::Black);
                    window.draw(block);
                }
            }
        }
    
        // Desenhar o tetromino atual
        int size = tetrominoSizes[currentTetromino.type];
        for (int i = 0; i < size; ++i) {
            for (int j = 0; j < size; ++j) {
                if (tetrominoShapes[currentTetromino.type][currentTetromino.rotation][i][j]) {
                    int x = currentTetromino.x + j;
                    int y = currentTetromino.y + i;
                    if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
                        sf::RectangleShape block(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
                        block.setPosition(x * BLOCK_SIZE, y * BLOCK_SIZE);
                        block.setFillColor(tetrominoColors[currentTetromino.type]);
                        block.setOutlineThickness(1);
                        block.setOutlineColor(sf::Color::Black);
                        window.draw(block);
                    }
                }
            }
        }
    
        // Desenhar pontuação e nível
        sf::Text scoreText;
        scoreText.setFont(font);
        scoreText.setCharacterSize(20);
        scoreText.setFillColor(sf::Color::White);
        scoreText.setString("Pontuação: " + std::to_string(score));
        scoreText.setPosition(10, 10);
        window.draw(scoreText);
    
        sf::Text levelText;
        levelText.setFont(font);
        levelText.setCharacterSize(20);
        levelText.setFillColor(sf::Color::White);
        levelText.setString("Nível: " + std::to_string(level));
        levelText.setPosition(10, 35);
        window.draw(levelText);
    
        // Desenhar volume
        sf::Text volumeText;
        volumeText.setFont(font);
        volumeText.setCharacterSize(20);
        volumeText.setFillColor(sf::Color::White);
        volumeText.setString("Volume: " + std::to_string(static_cast<int>(volume)) + "%");
        volumeText.setPosition(10, 60);
        window.draw(volumeText);
    
        // Se pausado, desenhar texto de pausa
        if (paused) {
            sf::Text pausedText;
            pausedText.setFont(font);
            pausedText.setCharacterSize(40);
            pausedText.setFillColor(sf::Color::White);
            pausedText.setString("JOGO PAUSADO");
            pausedText.setPosition(WINDOW_WIDTH / 2 - pausedText.getLocalBounds().width / 2, WINDOW_HEIGHT / 2 - pausedText.getLocalBounds().height / 2);
            window.draw(pausedText);
        }
    }
    
    // Verificar colisões
    bool checkCollision() {
        int size = tetrominoSizes[currentTetromino.type];
        for (int i = 0; i < size; ++i) {
            for (int j = 0; j < size; ++j) {
                if (tetrominoShapes[currentTetromino.type][currentTetromino.rotation][i][j]) {
                    int x = currentTetromino.x + j;
                    int y = currentTetromino.y + i;
    
                    if (x < 0 || x >= GRID_WIDTH || y >= GRID_HEIGHT)
                        return true;
                    if (y >= 0 && grid[y][x] != -1)
                        return true;
                }
            }
        }
        return false;
    }
    
    // Fundir tetromino com a grade
    void mergeTetromino() {
        int size = tetrominoSizes[currentTetromino.type];
        for (int i = 0; i < size; ++i) {
            for (int j = 0; j < size; ++j) {
                if (tetrominoShapes[currentTetromino.type][currentTetromino.rotation][i][j]) {
                    int x = currentTetromino.x + j;
                    int y = currentTetromino.y + i;
                    if (y >= 0 && y < GRID_HEIGHT && x >= 0 && x < GRID_WIDTH) {
                        grid[y][x] = currentTetromino.type;
                    }
                }
            }
        }
    }
    
    // Eliminar linhas completas
    void clearLines() {
        int linesCleared = 0;
        for (int i = GRID_HEIGHT - 1; i >= 0; --i) {
            bool 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
                ++linesCleared;
            }
        }
        if (linesCleared > 0) {
            playSound(440.0f, 150);
            int points = 0;
            switch (linesCleared) {
                case 1: points = 100; break;
                case 2: points = 300; break;
                case 3: points = 500; break;
                case 4: points = 800; break;
                default: points = linesCleared * 200; break;
            }
            score += points;
    
            // Atualizar nível e velocidade
            int newLevel = score / 1000 + 1;
            if (newLevel > level) {
                level = newLevel;
                if (fallSpeed > 50)
                    fallSpeed -= 50;
            }
        }
    }
    
    // Gerar um novo tetromino
    void spawnNewTetromino() {
        currentTetromino.type = rand() % 7;
        currentTetromino.rotation = 0;
        currentTetromino.x = (GRID_WIDTH - tetrominoSizes[currentTetromino.type]) / 2;
        currentTetromino.y = 0;
    }
    
    // Reiniciar o jogo
    void resetGame() {
        initGame();
    }
    
    // Adicionar uma nova pontuação
    void addScoreEntry(const std::string& name, int scoreValue) {
        ScoreEntry newEntry = {name, scoreValue};
        scoreList.push_back(newEntry);
    
        // Ordenar pontuações em ordem decrescente
        std::sort(scoreList.begin(), scoreList.end(), [](const ScoreEntry& a, const ScoreEntry& b) {
            return b.score < a.score;
        });
    
        // Manter apenas as top MAX_SCORES pontuações
        if (scoreList.size() > MAX_SCORES)
            scoreList.resize(MAX_SCORES);
    
        saveScores();
    }
    
    // Carregar pontuações do arquivo
    void loadScores() {
        std::ifstream file(SCORE_FILE);
        if (file.is_open()) {
            std::string line;
            while (std::getline(file, line)) {
                size_t sep = line.find(';');
                if (sep != std::string::npos) {
                    std::string name = line.substr(0, sep);
                    int scoreValue = std::stoi(line.substr(sep + 1));
                    scoreList.push_back({name, scoreValue});
                }
            }
            file.close();
        }
    }
    
    // Salvar pontuações no arquivo
    void saveScores() {
        std::ofstream file(SCORE_FILE);
        if (file.is_open()) {
            for (const auto& entry : scoreList) {
                file << entry.name << ";" << entry.score << "\n";
            }
            file.close();
        }
    }
    
    // Reproduzir um som (sinal senoidal simples)
    void playSound(float frequency, int duration_ms) {
        const int SAMPLE_RATE = 44100;
        const int sampleCount = SAMPLE_RATE * duration_ms / 1000;
        sf::Int16* raw = new sf::Int16[sampleCount];
        const float amplitude = 30000.0f * (volume / 100.0f);
    
        for (int i = 0; i < sampleCount; ++i) {
            raw[i] = static_cast<sf::Int16>(amplitude * sin((2 * M_PI * frequency) * i / SAMPLE_RATE));
        }
    
        sf::SoundBuffer buffer;
        if (buffer.loadFromSamples(raw, sampleCount, 1, SAMPLE_RATE)) {
            sf::Sound sound(buffer);
            sound.play();
            sf::sleep(sf::milliseconds(duration_ms));
        }
    
        delete[] raw;
    }
    

    Instruções:

    • Compilação: Para compilar este código, você precisa ter a SFML instalada em seu sistema.
    • Bibliotecas: Certifique-se de linkar as bibliotecas SFML (-lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio).
    • Fontes: Coloque um arquivo de fonte TrueType (por exemplo, arial.ttf) no mesmo diretório do executável ou altere o caminho da fonte no código.

    Exemplo de Compilação (no Linux):

    g++ tetris.cpp -o tetris -lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio
    

    Explicação:

    • O código foi reescrito em C++ puro utilizando a SFML para gráficos e áudio.
    • A lógica do jogo é semelhante ao código original em C, mas adaptada para C++ e para a arquitetura da SFML.
    • As estruturas Tetromino e ScoreEntry são usadas para representar as peças e as pontuações.
    • O array grid representa o tabuleiro do jogo.
    • A função main configura a janela e inicia o loop do jogo.
    • A entrada é manipulada através do sistema de eventos da SFML.
    • A função drawGame renderiza o estado do jogo na janela.
    • O áudio é tratado usando o módulo de áudio da SFML, gerando um buffer de onda senoidal para sons simples.

    Observações Adicionais:

    • Controle de Pontuação: No momento, o código não implementa a entrada do nome do jogador para salvar a pontuação. Você pode expandir esse recurso adicionando uma interface de entrada de texto.
    • Melhorias Visuais: Você pode aprimorar o jogo adicionando gráficos mais elaborados, animações suaves e efeitos sonoros aprimorados.
    • Menus e Interfaces: Adicionar menus para iniciar o jogo, visualizar pontuações e sair pode melhorar a experiência do usuário.
    • Tratamento de Erros: Certifique-se de adicionar tratamento de erros adequado, especialmente ao carregar arquivos e recursos.

    Instalação da SFML:

    Links Úteis:

    Espero que esta conversão atenda às suas necessidades. Se você tiver alguma dúvida ou precisar de mais assistência, fique à vontade para perguntar!