Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save sgtvcamera/bb439e38613366ee915c49e4303e7909 to your computer and use it in GitHub Desktop.

Select an option

Save sgtvcamera/bb439e38613366ee915c49e4303e7909 to your computer and use it in GitHub Desktop.
Версия тетриса. Для примера.
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <ctime>
using namespace std;
// Размеры игрового поля
const int WIDTH = 12;
const int HEIGHT = 20;
int field[HEIGHT][WIDTH] = {0};
// Фигуры (Тетромино): 7 штук, каждая имеет 4 блока с координатами (x, y)
int figures[7][4][2] = {
{{0,1}, {1,1}, {2,1}, {3,1}}, // I
{{1,0}, {1,1}, {1,2}, {2,2}}, // L
{{1,2}, {2,0}, {2,1}, {2,2}}, // J
{{1,1}, {1,2}, {2,1}, {2,2}}, // O
{{1,2}, {2,1}, {2,2}, {3,1}}, // S
{{1,1}, {2,1}, {2,2}, {3,2}}, // Z
{{1,2}, {2,1}, {2,2}, {3,2}} // T (упрощенная)
};
// Текущая падающая фигура
struct Piece {
int x, y;
int type;
int blocks[4][2];
} currentPiece;
// Функция для установки курсора в начало (убирает мерцание экрана)
void setCursorPosition(int x, int y) {
COORD coord = { (short)x, (short)y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// Проверка на столкновения со стенами или другими блоками
bool checkCollision(Piece p) {
for (int i = 0; i < 4; i++) {
int fx = p.x + p.blocks[i][0];
int fy = p.y + p.blocks[i][1];
if (fx < 0 || fx >= WIDTH || fy >= HEIGHT || (fy >= 0 && field[fy][fx] != 0)) {
return true;
}
}
return false;
}
// Создание новой фигуры
void spawnPiece() {
currentPiece.type = rand() % 7;
currentPiece.x = WIDTH / 2 - 2;
currentPiece.y = 0;
for (int i = 0; i < 4; i++) {
currentPiece.blocks[i][0] = figures[currentPiece.type][i][0];
currentPiece.blocks[i][1] = figures[currentPiece.type][i][1];
}
}
// Вращение фигуры
void rotatePiece() {
Piece temp = currentPiece;
for (int i = 0; i < 4; i++) {
int x = temp.blocks[i][1];
int y = -temp.blocks[i][0];
temp.blocks[i][0] = x;
temp.blocks[i][1] = y;
}
if (!checkCollision(temp)) {
currentPiece = temp;
}
}
// Отрисовка игрового поля
void drawField(int score) {
setCursorPosition(0, 0);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0 || j == WIDTH - 1 || i == HEIGHT - 1) cout << "#"; // Стены
else {
bool isPiece = false;
for (int k = 0; k < 4; k++) {
if (currentPiece.x + currentPiece.blocks[k][0] == j &&
currentPiece.y + currentPiece.blocks[k][1] == i) {
isPiece = true;
break;
}
}
if (isPiece) cout << "O"; // Падающая фигура
else if (field[i][j] != 0) cout << "X"; // Упавшие блоки
else cout << " "; // Пустое пространство
}
}
cout << endl;
}
cout << "Score: " << score << endl;
cout << "Controls: A/D - Move | W - Rotate | S - Drop" << endl;
}
int main() {
srand(time(0));
spawnPiece();
bool gameOver = false;
int score = 0;
DWORD lastTick = GetTickCount();
int dropSpeed = 500; // Скорость падения (мс)
while (!gameOver) {
// --- 1. Обработка ввода (Управление) ---
if (_kbhit()) {
char key = _getch();
Piece temp = currentPiece;
if (key == 'a' || key == 'A') temp.x -= 1;
else if (key == 'd' || key == 'D') temp.x += 1;
else if (key == 's' || key == 'S') temp.y += 1;
else if (key == 'w' || key == 'W') rotatePiece();
if (!checkCollision(temp) && (key != 'w' && key != 'W')) {
currentPiece = temp;
}
}
// --- 2. Логика падения фигур ---
if (GetTickCount() - lastTick > dropSpeed) {
Piece temp = currentPiece;
temp.y += 1;
if (checkCollision(temp)) {
// Закрепляем фигуру на поле
for (int i = 0; i < 4; i++) {
int fx = currentPiece.x + currentPiece.blocks[i][0];
int fy = currentPiece.y + currentPiece.blocks[i][1];
if (fy >= 0) field[fy][fx] = 1;
}
spawnPiece();
// Если новая фигура сразу сталкивается - конец игры
if (checkCollision(currentPiece)) gameOver = true;
} else {
currentPiece = temp;
}
lastTick = GetTickCount();
}
// --- 3. Уничтожение заполненных линий ---
for (int i = HEIGHT - 2; i > 0; i--) {
bool fullLine = true;
for (int j = 1; j < WIDTH - 1; j++) {
if (field[i][j] == 0) {
fullLine = false;
break;
}
}
if (fullLine) {
score += 100;
// Сдвигаем всё вниз
for (int k = i; k > 0; k--) {
for (int j = 1; j < WIDTH - 1; j++) {
field[k][j] = field[k - 1][j];
}
}
i++; // Проверяем эту же линию еще раз, так как блоки сместились
}
}
// --- 4. Отрисовка ---
drawField(score);
Sleep(50); // Небольшая задержка, чтобы не перегружать процессор
}
system("cls");
cout << "Game Over! Final Score: " << score << endl;
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment