C语言俄罗斯方块代码
时间: 2024-04-21 07:19:28 浏览: 144
C语言俄罗斯方块代码是一种使用C语言编写的经典游戏代码,它实现了俄罗斯方块游戏的基本功能。以下是一个简单的C语言俄罗斯方块代码的示例:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 10
#define HEIGHT 20
int board[HEIGHT][WIDTH] = {0};
int currentPiece[4][4] = {0};
int currentX = 0;
int currentY = 0;
void generatePiece() {
// 生成随机方块
int pieces[7][4][4] = {
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0 0, 0, 0}},
{{1, 1, 1, 0}, {1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
{{1, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
{{1, 1, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
{{1, 1, 0, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
{{1, 1, 0, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
{{0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
};
int randomIndex = rand() % 7;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
currentPiece[i][j] = pieces[randomIndex][i][j];
}
}
currentX = WIDTH / 2 - 2;
currentY = 0;
}
int checkCollision(int x, int y) {
// 检查方块是否与边界或已有方块碰撞
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (currentPiece[i][j] != 0 && (x + j < 0 || x + j >= WIDTH || y + i >= HEIGHT || board[y + i][x + j] != 0)) {
return 1;
}
}
}
return 0;
}
void mergePiece() {
// 将当前方块合并到已有方块中
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (currentPiece[i][j] != 0) {
board[currentY + i][currentX + j] = currentPiece[i][j];
}
}
}
}
void clearLines() {
// 消除满行
for (int i = HEIGHT - 1; i >= 0; i--) {
int isFull = 1;
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] == 0) {
isFull = 0;
break;
}
}
if (isFull) {
for (int k = i; k > 0; k--) {
for (int j = 0; j < WIDTH; j++) {
board[k][j] = board[k - 1][j];
}
}
for (int j = 0; j < WIDTH; j++) {
board[0][j] = 0;
}
}
}
}
void drawBoard() {
// 绘制游戏界面
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] != 0) {
printf("■ ");
} else {
printf(" ");
}
}
printf("\n");
}
}
int main() {
srand(time(NULL));
generatePiece();
while (1) {
drawBoard();
if (checkCollision(currentX, currentY + 1)) {
mergePiece();
clearLines();
generatePiece();
if (checkCollision(currentX, currentY)) {
break;
}
} else {
currentY++;
}
if (_kbhit()) {
char key = _getch();
switch (key) {
case 'a':
if (!checkCollision(currentX - 1, currentY)) {
currentX--;
}
break;
case 'd':
if (!checkCollision(currentX + 1, currentY)) {
currentX++;
}
break;
case 's':
while (!checkCollision(currentX, currentY + 1)) {
currentY++;
}
break;
case 'q':
exit(0);
}
}
}
printf("Game Over!\n");
return 0;
}
```
这段代码实现了一个简单的俄罗斯方块游戏,包括生成随机方块、检测碰撞、合并方块、消除满行等功能。你可以在此基础上进行修改和扩展,实现更多的游戏功能。
阅读全文