自己制作俄罗斯方块C语言源代码
时间: 2023-08-02 19:11:33 浏览: 203
C语言实现俄罗斯方块源代码
5星 · 资源好评率100%
好的,下面是一个简单的俄罗斯方块C语言源代码,供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 10
#define HEIGHT 20
#define SIZE 4
int shapes[7][4][4] = {
{ {0,0,0,0}, {1,1,1,1}, {0,0,0,0}, {0,0,0,0} },
{ {0,0,1,0}, {0,0,1,0}, {0,0,1,0}, {0,0,1,0} },
{ {0,1,1,0}, {0,1,0,0}, {0,1,0,0}, {0,0,0,0} },
{ {0,1,0,0}, {0,1,1,0}, {0,0,1,0}, {0,0,0,0} },
{ {0,0,1,0}, {0,1,1,0}, {0,1,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}, {0,1,1,0}, {1,1,0,0}, {0,0,0,0} }
};
int board[HEIGHT][WIDTH];
void init_board() {
int i, j;
for(i = 0; i < HEIGHT; i++) {
for(j = 0; j < WIDTH; j++) {
board[i][j] = 0;
}
}
}
void print_board() {
int i, j;
for(i = 0; i < HEIGHT; i++) {
for(j = 0; j < WIDTH; j++) {
printf("%c", board[i][j] == 0 ? ' ' : '*');
}
printf("\n");
}
}
int can_move(int shape[][SIZE], int x, int y) {
int i, j;
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
if(shape[i][j] != 0) {
int x1 = x + i;
int y1 = y + j;
if(x1 < 0 || x1 >= HEIGHT || y1 < 0 || y1 >= WIDTH || board[x1][y1] != 0) {
return 0;
}
}
}
}
return 1;
}
void update_board(int shape[][SIZE], int x, int y) {
int i, j;
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
if(shape[i][j] != 0) {
board[x + i][y + j] = 1;
}
}
}
}
void remove_line() {
int i, j;
for(i = HEIGHT - 1; i >= 0; i--) {
int flag = 1;
for(j = 0; j < WIDTH; j++) {
if(board[i][j] == 0) {
flag = 0;
break;
}
}
if(flag) {
int k;
for(k = i - 1; k >= 0; k--) {
for(j = 0; j < WIDTH; j++) {
board[k + 1][j] = board[k][j];
}
}
i++;
}
}
}
void play() {
init_board();
int score = 0;
while(1) {
int shape_index = rand() % 7;
int shape[SIZE][SIZE];
int i, j;
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
shape[i][j] = shapes[shape_index][i][j];
}
}
int x = 0;
int y = WIDTH / 2 - 2;
if(!can_move(shape, x, y)) {
printf("Game Over!\n");
break;
}
while(1) {
system("cls");
update_board(shape, x, y);
print_board();
int ch = getch();
switch(ch) {
case 'a':
if(can_move(shape, x, y - 1)) {
y--;
}
break;
case 'd':
if(can_move(shape, x, y + 1)) {
y++;
}
break;
case 's':
if(can_move(shape, x + 1, y)) {
x++;
}
break;
case 'w':
int shape2[SIZE][SIZE];
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
shape2[i][j] = shape[j][SIZE - 1 - i];
}
}
if(can_move(shape2, x, y)) {
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
shape[i][j] = shape2[i][j];
}
}
}
break;
case ' ':
while(can_move(shape, x + 1, y)) {
x++;
}
break;
case 'q':
return;
}
update_board(shape, x, y);
if(!can_move(shape, x + 1, y)) {
break;
}
Sleep(100);
}
remove_line();
score += 10;
printf("Score: %d\n", score);
}
}
int main() {
srand((unsigned int)time(NULL));
play();
return 0;
}
```
这个代码包含了一个简单的俄罗斯方块游戏,可以在控制台中运行。具体实现可以参考代码中的注释。
阅读全文