用c++做一个俄罗斯方块游戏
时间: 2023-12-25 12:09:35 浏览: 41
好的,下面是一个简单的基于控制台的俄罗斯方块游戏示例代码,帮助你入门:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 10;
const int HEIGHT = 20;
int board[HEIGHT][WIDTH] = {0}; // 游戏棋盘
int score = 0; // 得分
// 方块类型和形状
int shapes[7][4] = {
{1,1,1,1}, // I
{1,1,0,0,1,1,}, // O
{1,1,0,0,0,1,1}, // Z
{0,1,1,0,1,1,0}, // S
{1,0,0,1,1,1,0}, // J
{0,0,1,1,1,1,}, // L
{0,1,0,0,1,1,1}, // T
};
// 方块类
class Shape {
public:
int type; // 方块类型
int x, y; // 方块位置
int rotation; // 方块旋转角度
Shape() {
type = rand() % 7;
x = WIDTH / 2 - 2;
y = 0;
rotation = 0;
}
// 绘制方块
void draw() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (shapes[type][rotation * 4 + i * 4 + j] == 1) {
if (x + j >= 0 && x + j < WIDTH && y + i >= 0 && y + i < HEIGHT) {
board[y + i][x + j] = 1;
}
}
}
}
}
// 擦除方块
void erase() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (shapes[type][rotation * 4 + i * 4 + j] == 1) {
if (x + j >= 0 && x + j < WIDTH && y + i >= 0 && y + i < HEIGHT) {
board[y + i][x + j] = 0;
}
}
}
}
}
// 检测方块是否可以移动
bool canMove(int dx, int dy, int r) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (shapes[type][r * 4 + i * 4 + j] == 1) {
int nx = x + j + dx;
int ny = y + i + dy;
if (nx < 0 || nx >= WIDTH || ny < 0 || ny >= HEIGHT || board[ny][nx] == 1) {
return false;
}
}
}
}
return true;
}
// 移动方块
void move(int dx, int dy, int r) {
erase();
if (canMove(dx, dy, r)) {
x += dx;
y += dy;
rotation = r;
}
draw();
}
// 检测是否可以下落
bool canFall() {
return canMove(0, 1, rotation);
}
// 下落
void fall() {
erase();
if (canFall()) {
++y;
} else {
draw();
clearLines();
newShape();
}
draw();
}
// 清除行
void clearLines() {
for (int i = HEIGHT - 1; i >= 0; --i) {
bool full = true;
for (int j = 0; j < WIDTH; ++j) {
if (board[i][j] == 0) {
full = false;
break;
}
}
if (full) {
for (int k = i; k > 0; --k) {
for (int j = 0; j < WIDTH; ++j) {
board[k][j] = board[k-1][j];
}
}
++i;
score += 10;
}
}
}
// 新增方块
void newShape() {
x = WIDTH / 2 - 2;
y = 0;
rotation = 0;
type = rand() % 7;
if (!canMove(0, 0, rotation)) {
gameOver();
}
}
// 游戏结束
void gameOver() {
cout << "Game Over!" << endl;
exit(1);
}
};
// 显示游戏界面
void display() {
system("cls");
cout << "Score: " << score << endl;
for (int i = 0; i < HEIGHT; ++i) {
for (int j = 0; j < WIDTH; ++j) {
if (board[i][j] == 0) {
cout << " ";
} else {
cout << "*";
}
}
cout << endl;
}
}
int main() {
Shape shape;
display();
while (true) {
if (_kbhit()) {
char c = _getch();
if (c == 'a') {
shape.move(-1, 0, shape.rotation);
} else if (c == 'd') {
shape.move(1, 0, shape.rotation);
} else if (c == 's') {
shape.fall();
} else if (c == 'q') {
shape.move(0, 0, (shape.rotation + 3) % 4);
} else if (c == 'e') {
shape.move(0, 0, (shape.rotation + 1) % 4);
}
} else {
shape.fall();
}
display();
Sleep(100);
}
return 0;
}
```
这个示例代码只是一个简单的实现,你可以根据需求进行修改和扩展。