俄罗斯方块代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h> //此处使用了Windows系统下的控制台函数
#define ROW 20
#define COLUMN 10
//定义游戏区域和方块类型
int map[ROW][COLUMN] = {0};
int block[7][4] = {
{1, 3, 5, 7},
{2, 4, 5, 7},
{3, 5, 4, 6},
{3, 5, 4, 7},
{2, 3, 5, 7},
{3, 5, 7, 6},
{2, 3, 4, 5}
};
//清屏函数
void clearScreen() {
system("cls"); //在Windows下执行清屏命令
}
//绘制游戏区域
void drawMap() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COLUMN; j++) {
if (map[i][j] == 0) {
printf(" ");
} else {
printf("*");
}
}
printf("\n");
}
}
//检查当前方块是否可以移动到指定的位置
int checkBlock(int x, int y, int type, int direction) {
int i, newX, newY;
for (i = 0; i < 4; i++) {
newX = x + (block[type][i] / 3) * direction;
newY = y + (block[type][i] % 3);
if (newX < 0 || newX >= COLUMN || newY < 0 || newY >= ROW || map[newY][newX] != 0) {
return 0;
}
}
return 1;
}
//将当前的方块放到游戏区域中
void setBlock(int x, int y, int type) {
int i, newX, newY;
for (i = 0; i < 4; i++) {
newX = x + (block[type][i] / 3);
newY = y + (block[type][i] % 3);
map[newY][newX] = type + 1;
}
}
//移除当前的方块
void removeBlock(int x, int y, int type) {
int i, newX, newY;
for (i = 0; i < 4; i++) {
newX = x + (block[type][i] / 3);
newY = y + (block[type][i] % 3);
map[newY][newX] = 0;
}
}
//消除满行
void clearFullRows() {
int i, j, count, flag;
for (i = ROW - 1; i >= 0; i--) {
count = 0;
flag = 1;
for (j = 0; j < COLUMN; j++) {
if (map[i][j] != 0) {
count++;
} else {
flag = 0;
}
}
if (count == COLUMN) {
int k, m;
for (k = i - 1; k >= 0; k--) {
for (m = 0; m < COLUMN; m++) {
map[k + 1][m] = map[k][m];
}
}
for (m = 0; m < COLUMN; m++) {
map[0][m] = 0;
}
i++;
} else if (flag) {
break;
}
}
}
//游戏主循环
void gameLoop() {
int x = COLUMN / 2, y = 0, type = rand() % 7, direction = 0, speed = 10;
while (1) {
clearScreen();
drawMap();
//等待用户输入
if (_kbhit()) {
char ch = _getch(); //获取用户输入的字符
switch (ch) {
case 'a': //向左移动
if (checkBlock(x, y, type, -1)) {
removeBlock(x, y, type);