使用C语言编一下俄罗斯方块的代码
时间: 2023-12-28 20:05:05 浏览: 31
好的,下面是一个简单的俄罗斯方块游戏的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define ROW 20
#define COL 10
int board[ROW][COL] = {0};
int shapes[7][4][2] = {
{{0, 0}, {0, 1}, {1, 0}, {1, 1}},
{{0, 0}, {0, 1}, {0, 2}, {0, 3}},
{{0, 0}, {1, 0}, {2, 0}, {3, 0}},
{{0, 0}, {0, 1}, {0, 2}, {1, 2}},
{{0, 0}, {0, 1}, {0, 2}, {1, 0}},
{{0, 0}, {0, 1}, {0, 2}, {1, 1}},
{{0, 0}, {1, 0}, {1, 1}, {2, 1}},
};
int cur_shape = 0;
int cur_x = 0;
int cur_y = 0;
void init() {
srand((unsigned int)time(NULL));
cur_shape = rand() % 7;
cur_x = 0;
cur_y = COL / 2 - 2;
}
void draw() {
system("cls");
printf("Press W/A/S/D to move, Q to quit.\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (board[i][j] == 0) {
printf(".");
} else {
printf("*");
}
}
printf("\n");
}
}
void move(char op) {
switch (op) {
case 'a':
cur_y--;
break;
case 'd':
cur_y++;
break;
case 's':
cur_x++;
break;
case 'w':
cur_x--;
break;
}
}
void merge() {
for (int i = 0; i < 4; i++) {
int x = cur_x + shapes[cur_shape][i][0];
int y = cur_y + shapes[cur_shape][i][1];
board[x][y] = 1;
}
}
int check() {
for (int i = 0; i < 4; i++) {
int x = cur_x + shapes[cur_shape][i][0];
int y = cur_y + shapes[cur_shape][i][1];
if (x < 0 || x >= ROW || y < 0 || y >= COL) {
return 0;
}
if (board[x][y] == 1) {
return 0;
}
}
return 1;
}
void update() {
if (check()) {
merge();
init();
}
}
int main() {
init();
while (1) {
draw();
if (_kbhit()) {
char op = _getch();
if (op == 'q') {
break;
}
move(op);
}
update();
Sleep(100);
}
return 0;
}
```
这是一个简单的命令行俄罗斯方块游戏,使用了 Windows.h 库中的 Sleep 函数来控制帧率。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)