用 c语言写个俄罗斯方块程序
时间: 2023-10-05 22:05:30 浏览: 63
C语言写的俄罗斯方块程序
好的,下面是一个基于C语言的简单俄罗斯方块程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define WIDTH 10
#define HEIGHT 20
int board[HEIGHT][WIDTH] = {0}; //初始化游戏面板
int block[4][4] = {0}; //初始化方块
//生成随机方块
void generate_block() {
int idx = rand() % 7;
int blocks[7][4][4] = {
{{0,0,0,0},
{1,1,1,1},
{0,0,0,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},
{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},
{0,1,0,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},
{0,0,1,0},
{1,1,1,0},
{0,0,0,0}}
};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
block[i][j] = blocks[idx][i][j];
}
}
}
//判断方块是否可以放置
int can_put_block(int x, int y) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (block[i][j] == 1) {
int px = x + j;
int py = y + i;
if (px < 0 || px >= WIDTH || py < 0 || py >= HEIGHT || board[py][px] != 0) {
return 0;
}
}
}
}
return 1;
}
//将方块放置到游戏面板上
void put_block(int x, int y) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (block[i][j] == 1) {
board[y+i][x+j] = 1;
}
}
}
}
//消除满行
void clear_full_rows() {
for (int i = 0; i < HEIGHT; i++) {
int is_full = 1;
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] == 0) {
is_full = 0;
break;
}
}
if (is_full) {
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 draw_board() {
system("cls"); //清屏
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
printf("%c", board[i][j] == 0 ? ' ' : '*');
}
printf("\n");
}
}
int main() {
srand(time(NULL)); //初始化随机数生成器
while (1) {
generate_block(); //生成随机方块
int x = 3;
int y = 0;
while (can_put_block(x, y)) { //如果方块可以放置
draw_board(); //绘制游戏面板
Sleep(100); //暂停100毫秒
y++; //方块下落
}
y--; //方块无法再下落时回退一格
put_block(x, y); //将方块放置到游戏面板上
clear_full_rows(); //消除满行
}
return 0;
}
```
这个程序使用了Windows API中的Sleep函数来实现暂停,如果在其他平台上运行,需要使用相应的函数来实现暂停。
阅读全文