写一段俄罗斯方块的C语言代码
时间: 2023-11-29 14:04:53 浏览: 89
以下是一个简单的俄罗斯方块游戏的C语言代码,包括基本的游戏逻辑和绘制方块的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define ROWS 20
#define COLS 10
int board[ROWS][COLS] = {0};
int cur_tetromino[4][4];
int cur_row, cur_col;
int score = 0;
void generate_tetromino() {
int tetrominos[7][4][4] = {
{{1, 1, 0, 0},
{1, 1, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0, 1, 0, 0},
{1, 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}},
{{1, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0, 0, 1, 0},
{1, 1, 1, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{1, 0, 0, 0},
{1, 1, 1, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{1, 1, 1, 1},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}}
};
int rand_tetromino = rand() % 7;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cur_tetromino[i][j] = tetrominos[rand_tetromino][i][j];
}
}
cur_row = 0;
cur_col = COLS / 2 - 2;
}
void draw_board() {
system("cls");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] == 0) {
printf(" ");
} else {
printf("#");
}
}
printf("\n");
}
}
void draw_tetromino() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (cur_tetromino[i][j] == 1) {
board[cur_row + i][cur_col + j] = 1;
}
}
}
}
void erase_tetromino() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (cur_tetromino[i][j] == 1) {
board[cur_row + i][cur_col + j] = 0;
}
}
}
}
int check_collision() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (cur_tetromino[i][j] == 1 && board[cur_row + i][cur_col + j] == 1) {
return 1;
}
}
}
return 0;
}
void clear_lines() {
int lines_cleared = 0;
for (int i = ROWS - 1; i >= 0; i--) {
int line_full = 1;
for (int j = 0; j < COLS; j++) {
if (board[i][j] == 0) {
line_full = 0;
break;
}
}
if (line_full) {
lines_cleared++;
for (int j = i; j > 0; j--) {
for (int k = 0; k < COLS; k++) {
board[j][k] = board[j - 1][k];
}
}
for (int j = 0; j < COLS; j++) {
board[0][j] = 0;
}
i++;
}
}
score += lines_cleared * lines_cleared * 100;
}
int main() {
srand(time(NULL));
generate_tetromino();
while (1) {
draw_board();
draw_tetromino();
if (check_collision()) {
erase_tetromino();
clear_lines();
generate_tetromino();
} else {
cur_row++;
}
if (cur_row + 4 > ROWS) {
printf("Game over!\n");
printf("Final score: %d\n", score);
break;
}
if (_kbhit()) {
int key = _getch();
if (key == 'a' && cur_col > 0) {
erase_tetromino();
cur_col--;
} else if (key == 'd' && cur_col + 4 < COLS) {
erase_tetromino();
cur_col++;
} else if (key == 's') {
while (!check_collision()) {
cur_row++;
}
cur_row--;
} else if (key == 'q') {
exit(0);
}
}
Sleep(100);
}
return 0;
}
```
注意:这段代码使用了Windows特有的 `_kbhit()` 和 `_getch()` 函数来获取按键输入,如果在其他操作系统上运行可能会有问题。
阅读全文
相关推荐














