用c语言写一个俄罗斯方块游戏
时间: 2023-12-19 18:05:08 浏览: 89
好的,下面是一个简单的俄罗斯方块游戏的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#define WIDTH 10
#define HEIGHT 20
int board[HEIGHT][WIDTH];
int shape[7][4][4] = {
{{0,0,0,0},
{1,1,1,1},
{0,0,0,0},
{0,0,0,0}},
{{0,0,0,0},
{0,2,2,0},
{0,2,2,0},
{0,0,0,0}},
{{0,0,0,0},
{0,0,3,3},
{0,3,3,0},
{0,0,0,0}},
{{0,0,0,0},
{0,4,4,0},
{4,4,0,0},
{0,0,0,0}},
{{0,0,0,0},
{5,5,0,0},
{0,5,5,0},
{0,0,0,0}},
{{0,0,0,0},
{0,6,0,0},
{6,6,6,0},
{0,0,0,0}},
{{0,0,0,0},
{0,7,0,0},
{0,7,7,0},
{0,0,7,0}}
};
int pos_x, pos_y;
int cur_shape, cur_angle;
int check_block(int x, int y)
{
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT || board[y][x])
return 0;
return 1;
}
void rotate_shape(int angle)
{
int tmp[4][4];
int i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
tmp[i][j] = shape[cur_shape][i][j];
while (angle--) {
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
shape[cur_shape][i][j] = tmp[3-j][i];
}
}
void new_block()
{
cur_shape = rand() % 7;
cur_angle = rand() % 4;
pos_x = WIDTH / 2 - 2;
pos_y = 0;
if (!check_block(pos_x, pos_y)) {
printf("Game Over!\n");
exit(0);
}
}
void draw_board()
{
int i, j;
system("cls");
printf("Score: 0\n");
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
if (board[i][j])
printf("#");
else if (check_block(j, i+1))
printf(".");
else
printf(" ");
}
printf("\n");
}
}
void merge_block()
{
int i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
if (shape[cur_shape][i][j])
board[pos_y+i][pos_x+j] = shape[cur_shape][i][j];
}
void check_line()
{
int i, j, k;
for (i = HEIGHT-1; i >= 0; i--) {
for (j = 0; j < WIDTH; j++) {
if (!board[i][j])
break;
}
if (j == WIDTH) {
for (k = i; k > 0; k--)
for (j = 0; j < WIDTH; j++)
board[k][j] = board[k-1][j];
for (j = 0; j < WIDTH; j++)
board[0][j] = 0;
i++;
}
}
}
int main()
{
int i, j, ch;
srand((unsigned)time(NULL));
new_block();
while (1) {
draw_board();
if (_kbhit()) {
ch = _getch();
switch (ch) {
case 'a':
if (check_block(pos_x-1, pos_y))
pos_x--;
break;
case 'd':
if (check_block(pos_x+1, pos_y))
pos_x++;
break;
case 's':
if (check_block(pos_x, pos_y+1))
pos_y++;
break;
case 'w':
rotate_shape(1);
if (!check_block(pos_x, pos_y))
rotate_shape(3);
break;
case 'q':
rotate_shape(3);
if (!check_block(pos_x, pos_y))
rotate_shape(1);
break;
case ' ':
while (check_block(pos_x, pos_y+1))
pos_y++;
merge_block();
new_block();
check_line();
break;
case 'r':
for (i = 0; i < HEIGHT; i++)
for (j = 0; j < WIDTH; j++)
board[i][j] = 0;
new_block();
break;
case 'x':
exit(0);
}
}
if (!check_block(pos_x, pos_y+1)) {
merge_block();
new_block();
check_line();
} else {
pos_y++;
}
}
return 0;
}
```
这个代码使用了Windows下的conio库,可以通过Visual Studio等IDE来编译运行。游戏操作:a/d键左右移动,s键加速下落,w键顺时针旋转,q键逆时针旋转,空格键直接落下,r键重新开始,x键退出游戏。
阅读全文