Converta o código para C puro: // tetris.c #include <gtk/gtk.h> #include <cairo.h>…
- User
Converta o código para C puro: // 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();}
- Assistant
Claro! Vamos converter o código para uma versão em C puro, sem depender de bibliotecas externas como GTK ou SDL2.
Como o código original utiliza bibliotecas gráficas e de áudio para implementar o jogo Tetris com interface gráfica e sons, precisaremos adaptar a implementação para que funcione no console, utilizando apenas recursos padrão da linguagem C.
Segue abaixo o código do Tetris em C puro, reproduzindo a lógica do jogo no terminal:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #ifdef _WIN32 #include <conio.h> #include <windows.h> #define CLEAR "cls" #else #include <unistd.h> #include <termios.h> #include <sys/time.h> #include <sys/select.h> #define CLEAR "clear" #endif #define GRID_WIDTH 10 #define GRID_HEIGHT 20 // Estrutura para as peças (tetrominos) typedef struct { int x, y; int rotation; int type; } Tetromino; // Declaração de funções void init_game(); void game_loop(); void draw_grid(); void spawn_new_tetromino(); int check_collision(); void merge_tetromino(); void clear_lines(); void process_input(int ch); unsigned long get_time_milliseconds(); void sleep_milliseconds(int milliseconds); // Funções para entrada de teclado int kbhit(void); int getch(void); // Variáveis globais int grid[GRID_HEIGHT][GRID_WIDTH]; Tetromino current_tetromino; int game_over = 0; int score = 0; // Pontuação do jogador int level = 1; // Nível atual do jogo int fall_delay = 500; // Velocidade de queda em milissegundos // 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}} } }; int main(void) { srand(time(NULL)); // Inicializar a semente do rand init_game(); // Loop do jogo game_loop(); printf("Fim de jogo! Sua pontuação: %d\n", score); return 0; } // Função para inicializar o jogo void init_game() { // 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_delay = 500; // Velocidade inicial game_over = 0; // Criar o primeiro tetromino spawn_new_tetromino(); } // Loop principal do jogo void game_loop() { unsigned long last_time = get_time_milliseconds(); while (!game_over) { unsigned long current_time = get_time_milliseconds(); // Processar entrada de teclado if (kbhit()) { int ch = getch(); process_input(ch); } // Verificar se é hora de mover o tetromino para baixo if (current_time - last_time >= fall_delay) { current_tetromino.y += 1; if (check_collision()) { current_tetromino.y -= 1; merge_tetromino(); clear_lines(); spawn_new_tetromino(); if (check_collision()) { game_over = 1; } } last_time = current_time; } // Desenhar a grade draw_grid(); // Aguardar um pouco (para não sobrecarregar o CPU) sleep_milliseconds(50); } } // Função para obter o tempo atual em milissegundos unsigned long get_time_milliseconds() { #ifdef _WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000; #endif } // Função para desenhar a grade void draw_grid() { // Limpar a tela system(CLEAR); // Criar uma grade temporária int temp_grid[GRID_HEIGHT][GRID_WIDTH]; // Copiar a grade atual para a temporária for (int i = 0; i < GRID_HEIGHT; i++) for (int j = 0; j < GRID_WIDTH; j++) temp_grid[i][j] = grid[i][j]; // Sobrepor o tetromino atual na grade temporária 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) { temp_grid[y][x] = current_tetromino.type; } } } } // Imprimir a grade for (int i = 0; i < GRID_HEIGHT; i++) { printf("|"); for (int j = 0; j < GRID_WIDTH; j++) { if (temp_grid[i][j] != -1) printf("#"); // Caracter para bloco preenchido else printf(" "); // Espaço em branco para bloco vazio } printf("|\n"); } // Imprimir a borda inferior printf("+"); for (int j = 0; j < GRID_WIDTH; j++) { printf("-"); } printf("+\n"); // Imprimir pontuação e nível printf("Pontuação: %d Nível: %d\n", score, level); printf("Controles: A-esquerda D-direita S-baixar W-rotacionar Q-sair\n"); } // Função para gerar um novo tetromino void spawn_new_tetromino() { current_tetromino.type = rand() % 7; current_tetromino.rotation = 0; current_tetromino.x = (GRID_WIDTH - tetromino_sizes[current_tetromino.type]) / 2; current_tetromino.y = 0; } // Função para verificar colisões int check_collision() { 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 1; if (y >= 0 && grid[y][x] != -1) return 1; } } } return 0; } // Função para mesclar o tetromino atual na grade void merge_tetromino() { 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; } } } } } // Função para eliminar linhas completas void clear_lines() { int lines_cleared = 0; // Contador de linhas eliminadas for (int i = GRID_HEIGHT - 1; i >= 0; i--) { int full = 1; for (int j = 0; j < GRID_WIDTH; j++) { if (grid[i][j] == -1) { full = 0; 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) { 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 de queda) if (fall_delay > 50) { // Limite mínimo de velocidade fall_delay -= 50; } } } } // Função para processar a entrada de teclado void process_input(int ch) { int old_x = current_tetromino.x; int old_y = current_tetromino.y; int old_rotation = current_tetromino.rotation; switch (ch) { case 'a': case 'A': // Mover para a esquerda current_tetromino.x -= 1; if (check_collision()) current_tetromino.x = old_x; break; case 'd': case 'D': // Mover para a direita current_tetromino.x += 1; if (check_collision()) current_tetromino.x = old_x; break; case 's': case 'S': // Acelerar a queda current_tetromino.y += 1; if (check_collision()) current_tetromino.y = old_y; break; case 'w': case 'W': // Rotacionar current_tetromino.rotation = (current_tetromino.rotation + 1) % 4; if (check_collision()) current_tetromino.rotation = old_rotation; break; case 'q': case 'Q': // Sair do jogo game_over = 1; break; } } // Função para aguardar em milissegundos void sleep_milliseconds(int milliseconds) { #ifdef _WIN32 Sleep(milliseconds); #else usleep(milliseconds * 1000); // usleep recebe microssegundos #endif } // Funções para entrada de teclado // Verificar se uma tecla foi pressionada int kbhit(void) { #ifdef _WIN32 return _kbhit(); #else struct timeval tv = {0L, 0L}; fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); // Não espera após verificar o status do file descriptor select(1, &fds, NULL, NULL, &tv); return FD_ISSET(0, &fds); #endif } // Ler um caractere sem bloquear int getch(void) { #ifdef _WIN32 return _getch(); #else int ch; struct termios oldt, newt; // Obter configurações atuais do terminal tcgetattr(STDIN_FILENO, &oldt); // Desabilitar entrada canônica e eco newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); // Ler um caractere ch = getchar(); // Restaurar configurações antigas tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; #endif }Instruções para compilar e executar o código:
-
Em sistemas Unix/Linux (gcc instalado):
Abra um terminal e salve o código em um arquivo chamado
tetris.c.Compile o código com o comando:
gcc tetris.c -o tetrisExecute o jogo:
./tetris -
Em sistemas Windows (MinGW instalado):
Abra o Prompt de Comando e salve o código em um arquivo chamado
tetris.c.Compile o código com o comando:
gcc tetris.c -o tetris.exeExecute o jogo:
tetris.exe
Observações:
-
Este código utiliza apenas recursos padrão da linguagem C, com algumas funções específicas de sistema para manipulação de entrada de teclado sem bloqueio (como
kbhitegetch), e para limpar a tela (funçãosystem("cls")no Windows ousystem("clear")no Unix). -
A interface é baseada em texto, desenhando a grade do Tetris no console. Os controles estão indicados no jogo:
Aoua: Move o tetromino para a esquerdaDoud: Move o tetromino para a direitaSous: Acelera a queda do tetrominoWouw: Rotaciona o tetrominoQouq: Sai do jogo
-
A lógica do jogo, incluindo colisões, eliminação de linhas, pontuação e níveis, foi preservada do código original.
-
Como estamos trabalhando em um ambiente de console, não é possível reproduzir efeitos sonoros ou gráficos avançados. O foco é na funcionalidade básica do jogo Tetris.
Espero que esta versão atenda às suas expectativas de um código em C puro!
-