// tetris.cpp
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
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";
struct Tetromino {
int x, y;
int rotation;
int type;
};
struct ScoreEntry {
std::string name;
int score;
};
// Function declarations
void init_game();
void reset_game();
void spawn_new_tetromino();
bool check_collision();
void merge_tetromino();
void clear_lines();
void draw_game(sf::RenderWindow& window);
void draw_3d_block(sf::RenderWindow& window, int x, int y, sf::Color color);
void handle_input(sf::RenderWindow& window, sf::Event& event);
void update_game();
void load_scores();
void save_scores();
void add_score_entry(const std::string& name, int score_value);
void show_high_scores(sf::RenderWindow& window);
int compare_scores(const ScoreEntry& a, const ScoreEntry& b);
void play_sound(float frequency, int duration_ms);
// Global variables
int grid[GRID_HEIGHT][GRID_WIDTH];
Tetromino current_tetromino;
bool game_over = false;
int score = 0;
int level = 1;
int fall_speed = 500; // in milliseconds
bool paused = false;
float volume = 0.5f;
std::string feedback_message = "";
sf::Font font;
sf::Clock fall_timer;
sf::Clock feedback_timer;
std::vector<ScoreEntry> score_list;
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Tetris in C++ with SFML");
sf::SoundBuffer sound_buffer;
sf::Sound sound;
// Tetrimino sizes
const int tetromino_sizes[7] = {4, 3, 3, 2, 3, 3, 3};
// Tetromino shapes
const int tetromino_shapes[7][4][4][4] = {
// I (Type 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 (Type 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 (Type 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 (Type 3)
{
{{1,1},
{1,1}},
{{1,1},
{1,1}},
{{1,1},
{1,1}},
{{1,1},
{1,1}}
},
// S (Type 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 (Type 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 (Type 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}}
}
};
// Tetromino colors
const sf::Color tetromino_colors[7] = {
sf::Color::Cyan, // I
sf::Color::Blue, // J
sf::Color(255, 165, 0), // L (Orange)
sf::Color::Yellow, // O
sf::Color::Green, // S
sf::Color(128, 0, 128), // T (Purple)
sf::Color::Red // Z
};
int main() {
window.setFramerateLimit(60);
// Load font
if (!font.loadFromFile("arial.ttf")) {
std::cerr << "Failed to load font.\n";
return 1;
}
// Initialize game
load_scores();
init_game();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
// Handle window close event
if (event.type == sf::Event::Closed) {
window.close();
}
// Handle input
handle_input(window, event);
}
// Update game logic
update_game();
// Render game
window.clear(sf::Color(30, 30, 30));
draw_game(window);
window.display();
}
return 0;
}
void init_game() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
// Clear the grid
for (int i = 0; i < GRID_HEIGHT; ++i)
for (int j = 0; j < GRID_WIDTH; ++j)
grid[i][j] = -1;
// Reset variables
score = 0;
level = 1;
fall_speed = 500;
game_over = false;
paused = false;
feedback_message = "";
// Initialize the first 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;
fall_timer.restart();
}
void reset_game() {
init_game();
}
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;
}
bool 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 true;
if (y >= 0 && grid[y][x] != -1)
return true;
}
}
}
return false;
}
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;
}
}
}
}
}
void clear_lines() {
int lines_cleared = 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) {
for (int k = i; k > 0; --k) {
for (int j = 0; j < GRID_WIDTH; ++j) {
grid[k][j] = grid[k - 1][j];
}
}
for (int j = 0; j < GRID_WIDTH; ++j) {
grid[0][j] = -1;
}
++i;
++lines_cleared;
}
}
if (lines_cleared > 0) {
// Update score
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;
// Update level and speed
int new_level = score / 1000 + 1;
if (new_level > level) {
level = new_level;
if (fall_speed > 50) {
fall_speed -= 50;
}
}
// Play line clear sound
play_sound(440.0f, 150);
}
}
void draw_game(sf::RenderWindow& window) {
// Draw grid
for (int i = 0; i < GRID_HEIGHT; ++i) {
for (int j = 0; j < GRID_WIDTH; ++j) {
if (grid[i][j] != -1) {
sf::Color color = tetromino_colors[grid[i][j]];
draw_3d_block(window, j * BLOCK_SIZE, i * BLOCK_SIZE, color);
}
}
}
// Draw current 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 (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
sf::Color color = tetromino_colors[current_tetromino.type];
draw_3d_block(window, x * BLOCK_SIZE, y * BLOCK_SIZE, color);
}
}
}
}
// Draw score and level
sf::Text score_text;
score_text.setFont(font);
score_text.setCharacterSize(20);
score_text.setFillColor(sf::Color::White);
score_text.setPosition(10, 5);
std::stringstream ss;
ss << "Score: " << score;
score_text.setString(ss.str());
window.draw(score_text);
sf::Text level_text;
level_text.setFont(font);
level_text.setCharacterSize(20);
level_text.setFillColor(sf::Color::White);
level_text.setPosition(10, 30);
ss.str("");
ss << "Level: " << level;
level_text.setString(ss.str());
window.draw(level_text);
// Draw volume
sf::Text volume_text;
volume_text.setFont(font);
volume_text.setCharacterSize(20);
volume_text.setFillColor(sf::Color::White);
volume_text.setPosition(10, 55);
ss.str("");
ss << "Volume: " << static_cast<int>(volume * 100) << "%";
volume_text.setString(ss.str());
window.draw(volume_text);
// Draw pause overlay
if (paused) {
sf::RectangleShape overlay(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT));
overlay.setFillColor(sf::Color(0, 0, 0, 150));
window.draw(overlay);
sf::Text pause_text;
pause_text.setFont(font);
pause_text.setCharacterSize(40);
pause_text.setFillColor(sf::Color::White);
pause_text.setString("Game Paused");
sf::FloatRect textRect = pause_text.getLocalBounds();
pause_text.setOrigin(textRect.left + textRect.width / 2.0f,
textRect.top + textRect.height / 2.0f);
pause_text.setPosition(WINDOW_WIDTH / 2.0f, WINDOW_HEIGHT / 2.0f);
window.draw(pause_text);
}
// Draw feedback message
if (!feedback_message.empty() && feedback_timer.getElapsedTime().asSeconds() < 2) {
sf::RectangleShape overlay(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT));
overlay.setFillColor(sf::Color(0, 0, 0, 150));
window.draw(overlay);
sf::Text feedback_text;
feedback_text.setFont(font);
feedback_text.setCharacterSize(30);
feedback_text.setFillColor(sf::Color::White);
feedback_text.setString(feedback_message);
sf::FloatRect textRect = feedback_text.getLocalBounds();
feedback_text.setOrigin(textRect.left + textRect.width / 2.0f,
textRect.top + textRect.height / 2.0f);
feedback_text.setPosition(WINDOW_WIDTH / 2.0f, WINDOW_HEIGHT / 2.0f);
window.draw(feedback_text);
}
}
void draw_3d_block(sf::RenderWindow& window, int x, int y, sf::Color color) {
sf::RectangleShape block(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
block.setPosition(static_cast<float>(x), static_cast<float>(y));
// Main color with gradient
sf::VertexArray quad(sf::Quads, 4);
quad[0].position = sf::Vector2f(static_cast<float>(x), static_cast<float>(y));
quad[1].position = sf::Vector2f(static_cast<float>(x + BLOCK_SIZE), static_cast<float>(y));
quad[2].position = sf::Vector2f(static_cast<float>(x + BLOCK_SIZE), static_cast<float>(y + BLOCK_SIZE));
quad[3].position = sf::Vector2f(static_cast<float>(x), static_cast<float>(y + BLOCK_SIZE));
quad[0].color = color;
quad[1].color = color;
quad[2].color = sf::Color(color.r / 2, color.g / 2, color.b / 2);
quad[3].color = sf::Color(color.r / 2, color.g / 2, color.b / 2);
window.draw(quad);
// Outline
block.setFillColor(sf::Color::Transparent);
block.setOutlineThickness(1);
block.setOutlineColor(sf::Color::Black);
window.draw(block);
}
void handle_input(sf::RenderWindow& window, sf::Event& event) {
if (event.type == sf::Event::KeyPressed) {
// Control volume
if (event.key.code == sf::Keyboard::Add || event.key.code == sf::Keyboard::Equal) {
volume += 0.1f;
if (volume > 1.0f) volume = 1.0f;
feedback_message = "Volume: " + std::to_string(static_cast<int>(volume * 100)) + "%";
feedback_timer.restart();
}
if (event.key.code == sf::Keyboard::Subtract || event.key.code == sf::Keyboard::Hyphen) {
volume -= 0.1f;
if (volume < 0.0f) volume = 0.0f;
feedback_message = "Volume: " + std::to_string(static_cast<int>(volume * 100)) + "%";
feedback_timer.restart();
}
if (event.key.code == sf::Keyboard::P) {
paused = !paused;
feedback_message = paused ? "Game Paused" : "Game Resumed";
feedback_timer.restart();
// Play pause sound
play_sound(262.0f, 100);
}
if (event.key.code == sf::Keyboard::R) {
reset_game();
feedback_message = "Game Reset!";
feedback_timer.restart();
}
if (event.key.code == sf::Keyboard::S) {
feedback_message = "Exiting Game...";
feedback_timer.restart();
window.close();
}
if (!game_over && !paused) {
int old_x = current_tetromino.x;
int old_y = current_tetromino.y;
int old_rotation = current_tetromino.rotation;
if (event.key.code == sf::Keyboard::Left) {
current_tetromino.x -= 1;
if (check_collision())
current_tetromino.x = old_x;
}
if (event.key.code == sf::Keyboard::Right) {
current_tetromino.x += 1;
if (check_collision())
current_tetromino.x = old_x;
}
if (event.key.code == sf::Keyboard::Down) {
current_tetromino.y += 1;
if (check_collision())
current_tetromino.y = old_y;
}
if (event.key.code == sf::Keyboard::Up) {
current_tetromino.rotation = (current_tetromino.rotation + 1) % 4;
if (check_collision())
current_tetromino.rotation = old_rotation;
}
}
}
}
void update_game() {
if (game_over || paused) return;
if (fall_timer.getElapsedTime().asMilliseconds() > fall_speed) {
current_tetromino.y += 1;
if (check_collision()) {
current_tetromino.y -= 1;
merge_tetromino();
// Play lock sound
play_sound(330.0f, 100);
clear_lines();
spawn_new_tetromino();
if (check_collision()) {
game_over = true;
std::cout << "Game Over!\n";
// Play game over sound
play_sound(196.0f, 500);
// Ask for player name
std::string player_name;
std::cout << "Enter your name: ";
std::getline(std::cin, player_name);
if (player_name.empty())
player_name = "Anonymous";
add_score_entry(player_name, score);
// Show high scores
show_high_scores(window);
// Ask to restart or quit
std::cout << "Press R to restart, Q to quit.\n";
// Wait for input
while (true) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::R) {
reset_game();
return;
} else if (event.key.code == sf::Keyboard::Q) {
window.close();
return;
}
}
if (event.type == sf::Event::Closed) {
window.close();
return;
}
}
}
}
}
fall_timer.restart();
}
}
void load_scores() {
std::ifstream file(SCORE_FILE);
if (file.is_open()) {
score_list.clear();
std::string line;
while (std::getline(file, line) && score_list.size() < MAX_SCORES) {
size_t delimiter = line.find(';');
if (delimiter != std::string::npos) {
ScoreEntry entry;
entry.name = line.substr(0, delimiter);
entry.score = std::stoi(line.substr(delimiter + 1));
score_list.push_back(entry);
}
}
file.close();
}
}
void save_scores() {
std::ofstream file(SCORE_FILE);
if (file.is_open()) {
for (const auto& entry : score_list) {
file << entry.name << ";" << entry.score << "\n";
}
file.close();
}
}
void add_score_entry(const std::string& name, int score_value) {
ScoreEntry entry;
entry.name = name;
entry.score = score_value;
score_list.push_back(entry);
// Sort scores
std::sort(score_list.begin(), score_list.end(),
[](const ScoreEntry& a, const ScoreEntry& b) {
return b.score < a.score;
});
// Keep only top MAX_SCORES
if (score_list.size() > MAX_SCORES) {
score_list.resize(MAX_SCORES);
}
// Save scores
save_scores();
}
void show_high_scores(sf::RenderWindow& window) {
// Create a string with the scores
std::stringstream ss;
ss << "Top 10 Scores:\n";
for (size_t i = 0; i < score_list.size(); ++i) {
ss << i + 1 << ". " << score_list[i].name << " - " << score_list[i].score << " points\n";
}
sf::Text scores_text;
scores_text.setFont(font);
scores_text.setCharacterSize(20);
scores_text.setFillColor(sf::Color::White);
scores_text.setString(ss.str());
window.clear(sf::Color(30, 30, 30));
window.draw(scores_text);
window.display();
// Wait for key press
while (true) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::KeyPressed) {
return;
}
if (event.type == sf::Event::Closed) {
window.close();
return;
}
}
}
}
void play_sound(float frequency, int duration_ms) {
const int sample_rate = 44100;
int sample_count = (sample_rate * duration_ms) / 1000;
std::vector<sf::Int16> samples(sample_count);
for (int i = 0; i < sample_count; ++i) {
float time = static_cast<float>(i) / sample_rate;
samples[i] = static_cast<sf::Int16>(std::sin(2 * M_PI * frequency * time) * 32767 * volume);
}
if (!sound_buffer.loadFromSamples(&samples[0], sample_count, 1, sample_rate)) {
std::cerr << "Failed to load sound buffer.\n";
return;
}
sound.setBuffer(sound_buffer);
sound.play();
}
Notas:
-
Este código converte fielmente o original em C para C++, utilizando a biblioteca SFML para gráficos e áudio, que é uma das bibliotecas mais avançadas e populares em C++ para desenvolvimento multimídia.
-
As funcionalidades foram mantidas, incluindo a representação dos tetrominos, o gerenciamento da grade, pontuação, níveis, controle de volume, pausas, reinicialização do jogo e exibição das pontuações.
-
A função play_sound foi adaptada para gerar sons em tempo de execução, similar ao original em C. No entanto, em vez de utilizar ondas senoidais via SDL, utilizamos a SFML para gerar o áudio.
-
Certifique-se de ter a fonte arial.ttf no mesmo diretório do programa ou ajuste o caminho para uma fonte disponível para que os textos sejam exibidos corretamente.
-
Para compilar este código, você precisará das bibliotecas SFML instaladas em seu sistema. No Linux, você pode instalá-las usando o gerenciador de pacotes e compilar com um comando similar a:
g++ tetris.cpp -o tetris -lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio -lm
-
No Windows, você pode baixar as bibliotecas SFML do site oficial e seguir as instruções de configuração do ambiente.
-
Este código é auto-contido e não requer arquivos adicionais, exceto a fonte mencionada.
Espero que este código atenda às suas necessidades e que você possa continuar aprimorando o jogo conforme desejar!