diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e2cae22 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/build/ +/dist/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cb461a8 --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +CXX ?= g++ +MINGW_CXX ?= x86_64-w64-mingw32-g++ +VERSION ?= 0.1 +BUILD_DIR ?= build +DIST_DIR ?= dist +SDL2_CROSS_ROOT ?= /usr/x86_64-w64-mingw32 +APP := 3dtetris +VERSION_FLAG := -DGAME_VERSION=\"$(VERSION)\" +COMMON_FLAGS := -std=c++17 -Wall -Wextra -pedantic +SDL2_CFLAGS := $(shell pkg-config --cflags sdl2 gl) +SDL2_LIBS := $(shell pkg-config --libs sdl2 gl) +SDL2_CROSS_CFLAGS := -I$(SDL2_CROSS_ROOT)/include/SDL2 +SDL2_CROSS_LIBS := -L$(SDL2_CROSS_ROOT)/lib -lmingw32 -lSDL2main -lSDL2 \ + -mwindows -lopengl32 -limm32 -lversion -lole32 -loleaut32 -luuid \ + -lsetupapi -lwinmm -luser32 -lgdi32 -lshell32 -ladvapi32 + +.PHONY: all clean bundle-windows + +all: $(BUILD_DIR)/$(APP) + +$(BUILD_DIR): + mkdir -p $@ + +$(BUILD_DIR)/$(APP): main.cpp | $(BUILD_DIR) + @pkg-config --exists sdl2 gl || { echo "SDL2 and OpenGL development packages are required (pkg-config: sdl2 gl)." >&2; exit 1; } + $(CXX) $(COMMON_FLAGS) $(SDL2_CFLAGS) $(VERSION_FLAG) -O2 $< -o $@ $(SDL2_LIBS) + +$(BUILD_DIR)/$(APP).exe: main.cpp | $(BUILD_DIR) + @test -f "$(SDL2_CROSS_ROOT)/include/SDL2/SDL.h" && \ + test -f "$(SDL2_CROSS_ROOT)/lib/libSDL2.a" || { \ + echo "Set SDL2_CROSS_ROOT to a MinGW-w64 SDL2 development package root." >&2; exit 1; } + $(MINGW_CXX) $(COMMON_FLAGS) $(SDL2_CROSS_CFLAGS) $(VERSION_FLAG) \ + -Os -s -static -static-libgcc -static-libstdc++ $< -o $@ $(SDL2_CROSS_LIBS) + +bundle-windows: $(BUILD_DIR)/$(APP).exe + mkdir -p $(DIST_DIR) + cd $(BUILD_DIR) && zip -j ../$(DIST_DIR)/$(APP)-v$(VERSION)-windows-x64.zip $(APP).exe + +clean: + rm -rf $(BUILD_DIR) $(DIST_DIR) diff --git a/README.md b/README.md index e69de29..a749cc5 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,51 @@ +# 3D Tetris + +A C++17 3D Tetris game rendered with SDL2 and OpenGL. The playfield is six +cells wide, six cells deep, and twelve layers high. Fill a complete horizontal +layer to clear it. Drag with the left mouse button to orbit the 3D view and use +the mouse wheel to zoom. + +## Build and run + +Install SDL2 and OpenGL development libraries, plus `pkg-config`, then build +and run on Linux: + +```sh +make +./build/3dtetris +``` + +On Windows, install SDL2 development libraries and compile `main.cpp` with a +C++17 compiler, SDL2, and OpenGL. To cross-compile from Linux, install the +x86_64 MinGW-w64 compiler and download/unpack the SDL2 MinGW development +package. Point `SDL2_CROSS_ROOT` at its `x86_64-w64-mingw32` directory (the +directory containing `include/SDL2` and `lib`): + +```sh +make SDL2_CROSS_ROOT=/path/to/SDL2/x86_64-w64-mingw32 bundle-windows +``` + +The `bundle-windows` target cross-compiles a stripped, statically linked +x86_64 Windows executable and packages only that executable as +`dist/3dtetris-v0.1-windows-x64.zip`. Override `VERSION` to change the version +shown in the window title and used in the archive name, for example: + +```sh +make VERSION=0.2 bundle-windows +``` + +The SDL2 MinGW development package and `zip` must be installed to create the +Windows bundle. + +## Controls + +- **A / D** or **Left / Right**: move left / right +- **W / S** or **Up / Down**: move across the depth; Down soft-drops +- **Q / E**: rotate +- **Space**: hard drop +- **P**: pause / resume +- **R**: restart +- **Esc**: quit +- **Left mouse drag / wheel**: orbit / zoom the camera + +`--help` and `--version` print usage and version information. diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..6426e71 --- /dev/null +++ b/main.cpp @@ -0,0 +1,515 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef GAME_VERSION +#define GAME_VERSION "0.1" +#endif + +namespace { + +constexpr int WIDTH = 6; +constexpr int DEPTH = 6; +constexpr int HEIGHT = 12; + +struct Cell { + int x; + int y; + int z; +}; + +struct Piece { + std::array cells; +}; + +const std::array PIECES = {{ + {{{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {3, 0, 0}}}}, + {{{{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {1, 1, 0}}}}, + {{{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {1, 1, 0}}}}, + {{{{0, 0, 0}, {0, 1, 0}, {1, 1, 0}, {2, 1, 0}}}}, + {{{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {2, 1, 0}}}}, + {{{{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {2, 1, 0}}}}, + {{{{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {1, 0, 1}}}}, + {{{{0, 0, 0}, {0, 0, 1}, {0, 0, 2}, {0, 0, 3}}}}, +}}; + +const std::array, PIECES.size()> COLORS = {{ + {{0.10f, 0.78f, 0.96f}}, + {{0.98f, 0.79f, 0.18f}}, + {{0.67f, 0.32f, 0.94f}}, + {{0.24f, 0.86f, 0.44f}}, + {{0.96f, 0.47f, 0.17f}}, + {{0.95f, 0.28f, 0.42f}}, + {{0.25f, 0.49f, 0.97f}}, + {{0.21f, 0.87f, 0.82f}}, +}}; + +using Layer = std::array, DEPTH>; +using Board = std::array; + +std::runtime_error sdlFailure(const std::string& operation) { + return std::runtime_error(operation + ": " + SDL_GetError()); +} + +class Game { +public: + Game() : random_(std::random_device{}()) { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { + throw sdlFailure("SDL_Init failed"); + } + + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); + + window_ = SDL_CreateWindow( + "3D Tetris", + SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, + 1100, + 800, + SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + if (window_ == nullptr) { + const auto error = sdlFailure("Could not create SDL window"); + SDL_Quit(); + throw error; + } + + context_ = SDL_GL_CreateContext(window_); + if (context_ == nullptr) { + const auto error = sdlFailure("Could not create OpenGL context"); + SDL_DestroyWindow(window_); + window_ = nullptr; + SDL_Quit(); + throw error; + } + + SDL_GL_SetSwapInterval(1); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + start(); + } + + ~Game() { + if (context_ != nullptr) { + SDL_GL_DeleteContext(context_); + } + if (window_ != nullptr) { + SDL_DestroyWindow(window_); + } + SDL_Quit(); + } + + Game(const Game&) = delete; + Game& operator=(const Game&) = delete; + + void run() { + using Clock = std::chrono::steady_clock; + auto lastFall = Clock::now(); + bool running = true; + while (running) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + handleEvent(event, running); + } + + const auto now = Clock::now(); + if (!gameOver_ && !paused_ && + now - lastFall >= std::chrono::milliseconds(fallDelay())) { + if (!move(0, 0, -1)) { + lockPiece(); + } + lastFall = now; + } + + draw(); + SDL_Delay(8); + } + } + +private: + Board board_{}; + std::mt19937 random_; + SDL_Window* window_ = nullptr; + SDL_GLContext context_ = nullptr; + Piece piece_{}; + int pieceType_ = 0; + int x_ = 0; + int y_ = 0; + int z_ = 0; + int score_ = 0; + int clearedLayers_ = 0; + float cameraYaw_ = 35.0f; + float cameraPitch_ = 24.0f; + float cameraDistance_ = 19.0f; + bool gameOver_ = false; + bool paused_ = false; + bool dragging_ = false; + + int fallDelay() const { + return std::max(100, 700 - (clearedLayers_ / 5) * 50); + } + + void start() { + for (auto& layer : board_) { + for (auto& row : layer) { + row.fill(0); + } + } + score_ = 0; + clearedLayers_ = 0; + gameOver_ = false; + paused_ = false; + spawn(); + updateTitle(); + } + + void spawn() { + std::uniform_int_distribution choose( + 0, static_cast(PIECES.size()) - 1); + pieceType_ = choose(random_); + piece_ = PIECES[static_cast(pieceType_)]; + x_ = WIDTH / 2 - 1; + y_ = DEPTH / 2 - 1; + int maxZ = 0; + for (const Cell& cell : piece_.cells) { + maxZ = std::max(maxZ, cell.z); + } + z_ = HEIGHT - 1 - maxZ; + if (!fits(x_, y_, z_, piece_)) { + gameOver_ = true; + } + updateTitle(); + } + + bool fits(int px, int py, int pz, const Piece& candidate) const { + for (const Cell& cell : candidate.cells) { + const int cx = px + cell.x; + const int cy = py + cell.y; + const int cz = pz + cell.z; + if (cx < 0 || cx >= WIDTH || cy < 0 || cy >= DEPTH || + cz < 0 || cz >= HEIGHT || board_[cz][cy][cx] != 0) { + return false; + } + } + return true; + } + + bool move(int dx, int dy, int dz) { + if (!fits(x_ + dx, y_ + dy, z_ + dz, piece_)) { + return false; + } + x_ += dx; + y_ += dy; + z_ += dz; + return true; + } + + void rotate() { + Piece rotated = piece_; + int maxY = 0; + for (const Cell& cell : piece_.cells) { + maxY = std::max(maxY, cell.y); + } + for (Cell& cell : rotated.cells) { + const int oldX = cell.x; + cell.x = maxY - cell.y; + cell.y = oldX; + } + if (fits(x_, y_, z_, rotated)) { + piece_ = rotated; + } + } + + void hardDrop() { + while (move(0, 0, -1)) { + } + lockPiece(); + } + + void lockPiece() { + for (const Cell& cell : piece_.cells) { + board_[z_ + cell.z][y_ + cell.y][x_ + cell.x] = pieceType_ + 1; + } + clearFullLayers(); + spawn(); + } + + void clearFullLayers() { + int cleared = 0; + for (int z = 0; z < HEIGHT;) { + bool full = true; + for (int y = 0; y < DEPTH && full; ++y) { + for (int x = 0; x < WIDTH; ++x) { + if (board_[z][y][x] == 0) { + full = false; + break; + } + } + } + if (full) { + for (int layer = z; layer < HEIGHT - 1; ++layer) { + board_[layer] = board_[layer + 1]; + } + board_[HEIGHT - 1] = Layer{}; + ++cleared; + } else { + ++z; + } + } + if (cleared > 0) { + clearedLayers_ += cleared; + score_ += cleared * cleared * 100; + } + } + + void handleEvent(const SDL_Event& event, bool& running) { + if (event.type == SDL_QUIT) { + running = false; + return; + } + if (event.type == SDL_MOUSEBUTTONDOWN && + event.button.button == SDL_BUTTON_LEFT) { + dragging_ = true; + return; + } + if (event.type == SDL_MOUSEBUTTONUP && + event.button.button == SDL_BUTTON_LEFT) { + dragging_ = false; + return; + } + if (event.type == SDL_MOUSEMOTION && dragging_) { + cameraYaw_ += event.motion.xrel * 0.5f; + cameraPitch_ = std::clamp( + cameraPitch_ - event.motion.yrel * 0.5f, 5.0f, 80.0f); + return; + } + if (event.type == SDL_MOUSEWHEEL) { + cameraDistance_ = std::clamp( + cameraDistance_ - event.wheel.y, 10.0f, 35.0f); + return; + } + if (event.type != SDL_KEYDOWN || event.key.repeat != 0) { + return; + } + + switch (event.key.keysym.sym) { + case SDLK_ESCAPE: + running = false; + break; + case SDLK_r: + start(); + break; + case SDLK_p: + if (!gameOver_) { + paused_ = !paused_; + updateTitle(); + } + break; + default: + if (gameOver_ || paused_) { + break; + } + handleGameKey(event.key.keysym.sym); + break; + } + } + + void handleGameKey(SDL_Keycode key) { + switch (key) { + case SDLK_a: + case SDLK_LEFT: + move(-1, 0, 0); + break; + case SDLK_d: + case SDLK_RIGHT: + move(1, 0, 0); + break; + case SDLK_w: + case SDLK_UP: + move(0, 1, 0); + break; + case SDLK_s: + case SDLK_DOWN: + if (key == SDLK_DOWN) { + if (!move(0, 0, -1)) { + lockPiece(); + } + } else { + move(0, -1, 0); + } + break; + case SDLK_q: + rotate(); + break; + case SDLK_e: + rotate(); + rotate(); + rotate(); + break; + case SDLK_SPACE: + hardDrop(); + break; + default: + break; + } + } + + void updateTitle() const { + std::string title = "3D Tetris v" GAME_VERSION " | Score: " + + std::to_string(score_) + " | Layers: " + + std::to_string(clearedLayers_); + if (gameOver_) { + title += " | GAME OVER - press R to restart"; + } else if (paused_) { + title += " | PAUSED"; + } else { + title += " | drag to rotate, wheel to zoom"; + } + SDL_SetWindowTitle(window_, title.c_str()); + } + + void drawFrame() const { + glColor3f(0.20f, 0.27f, 0.38f); + glBegin(GL_LINES); + for (int xSide = 0; xSide <= 1; ++xSide) { + for (int zSide = 0; zSide <= 1; ++zSide) { + const float x = xSide ? WIDTH : 0.0f; + const float z = zSide ? DEPTH : 0.0f; + glVertex3f(x, 0.0f, z); + glVertex3f(x, HEIGHT, z); + } + } + for (int ySide = 0; ySide <= 1; ++ySide) { + const float y = ySide ? HEIGHT : 0.0f; + glVertex3f(0.0f, y, 0.0f); + glVertex3f(WIDTH, y, 0.0f); + glVertex3f(0.0f, y, DEPTH); + glVertex3f(WIDTH, y, DEPTH); + glVertex3f(0.0f, y, 0.0f); + glVertex3f(0.0f, y, DEPTH); + glVertex3f(WIDTH, y, 0.0f); + glVertex3f(WIDTH, y, DEPTH); + } + glColor3f(0.12f, 0.17f, 0.25f); + for (int x = 0; x <= WIDTH; ++x) { + glVertex3f(static_cast(x), 0.01f, 0.0f); + glVertex3f(static_cast(x), 0.01f, DEPTH); + } + for (int y = 0; y <= DEPTH; ++y) { + glVertex3f(0.0f, 0.01f, static_cast(y)); + glVertex3f(WIDTH, 0.01f, static_cast(y)); + } + glEnd(); + } + + void drawBlock(int x, int y, int z, int type) const { + const auto& color = COLORS[static_cast(type)]; + const float x0 = static_cast(x) + 0.04f; + const float x1 = static_cast(x + 1) - 0.04f; + const float y0 = static_cast(z) + 0.04f; + const float y1 = static_cast(z + 1) - 0.04f; + const float z0 = static_cast(y) + 0.04f; + const float z1 = static_cast(y + 1) - 0.04f; + const std::array, 8> v = {{ + {{x0, y0, z0}}, {{x1, y0, z0}}, {{x1, y1, z0}}, {{x0, y1, z0}}, + {{x0, y0, z1}}, {{x1, y0, z1}}, {{x1, y1, z1}}, {{x0, y1, z1}}, + }}; + const std::array, 6> faces = {{ + {{0, 1, 2, 3}}, {{5, 4, 7, 6}}, {{4, 0, 3, 7}}, + {{1, 5, 6, 2}}, {{3, 2, 6, 7}}, {{4, 5, 1, 0}}, + }}; + const std::array shade = {{0.62f, 0.78f, 0.70f, + 0.82f, 1.0f, 0.52f}}; + glBegin(GL_QUADS); + for (std::size_t face = 0; face < faces.size(); ++face) { + glColor3f(color[0] * shade[face], + color[1] * shade[face], + color[2] * shade[face]); + for (int vertex : faces[face]) { + const auto& point = v[static_cast(vertex)]; + glVertex3f(point[0], point[1], point[2]); + } + } + glEnd(); + } + + void draw() { + int width = 0; + int height = 0; + SDL_GL_GetDrawableSize(window_, &width, &height); + if (height == 0) { + return; + } + + glViewport(0, 0, width, height); + glClearColor(0.035f, 0.05f, 0.085f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + const float aspect = static_cast(width) / height; + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + const double halfHeight = 0.1; + glFrustum(-halfHeight * aspect, halfHeight * aspect, + -halfHeight, halfHeight, 0.1, 100.0); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0.0f, 0.0f, -cameraDistance_); + glRotatef(cameraPitch_, 1.0f, 0.0f, 0.0f); + glRotatef(cameraYaw_, 0.0f, 1.0f, 0.0f); + glTranslatef(-WIDTH / 2.0f, -HEIGHT / 2.0f, -DEPTH / 2.0f); + + drawFrame(); + for (int z = 0; z < HEIGHT; ++z) { + for (int y = 0; y < DEPTH; ++y) { + for (int x = 0; x < WIDTH; ++x) { + const int type = board_[z][y][x]; + if (type != 0) { + drawBlock(x, y, z, type - 1); + } + } + } + } + if (!gameOver_) { + for (const Cell& cell : piece_.cells) { + drawBlock(x_ + cell.x, y_ + cell.y, z_ + cell.z, pieceType_); + } + } + + SDL_GL_SwapWindow(window_); + } +}; + +} // namespace + +int main(int argc, char* argv[]) { + if (argc > 1 && std::string(argv[1]) == "--version") { + std::cout << "3D Tetris " << GAME_VERSION << '\n'; + return 0; + } + if (argc > 1 && std::string(argv[1]) == "--help") { + std::cout << "3D Tetris " << GAME_VERSION + << "\nControls: arrows or WASD move, Q/E rotate, Space drop, " + "Down soft-drops, P pauses, R restarts. Drag to rotate " + "the camera and use the mouse wheel to zoom.\n"; + return 0; + } + + try { + Game game; + game.run(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +}