用c++写俄罗斯方块 代码
时间: 2023-05-15 20:07:30 浏览: 131
C++编写俄罗斯方块
4星 · 用户满意度95%
非常感谢您的提问!以下是用 C 语言编写俄罗斯方块的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 10
#define HEIGHT 20
int board[HEIGHT][WIDTH] = {0};
int shapes[7][4][2] = {
{{0, 0}, {0, 1}, {1, 0}, {1, 1}}, // O
{{0, 0}, {0, 1}, {0, 2}, {0, 3}}, // I
{{0, 0}, {0, 1}, {0, 2}, {1, 2}}, // L
{{0, 0}, {0, 1}, {0, 2}, {-1, 2}}, // J
{{0, 0}, {0, 1}, {1, 1}, {1, 2}}, // S
{{0, 0}, {0, 1}, {-1, 1}, {1, 0}}, // Z
{{0, 0}, {0, 1}, {0, 2}, {1, 1}} // T
};
int current_shape[4][2];
int current_x = WIDTH / 2 - 1;
int current_y = 0;
int current_type = -1;
int score = 0;
void draw_board() {
system("cls");
printf("Score: %d\n", score);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] == 0) {
printf(".");
} else {
printf("*");
}
}
printf("\n");
}
}
void generate_shape() {
if (current_type == -1) {
current_type = rand() % 7;
}
for (int i = 0; i < 4; i++) {
current_shape[i][0] = shapes[current_type][i][0];
current_shape[i][1] = shapes[current_type][i][1];
}
}
int check_collision(int x, int y) {
for (int i = 0; i < 4; i++) {
int new_x = x + current_shape[i][0];
int new_y = y + current_shape[i][1];
if (new_x < 0 || new_x >= WIDTH || new_y < 0 || new_y >= HEIGHT) {
return 1;
}
if (board[new_y][new_x] != 0) {
return 1;
}
}
return 0;
}
void place_shape() {
for (int i = 0; i < 4; i++) {
int x = current_x + current_shape[i][0];
int y = current_y + current_shape[i][1];
board[y][x] = 1;
}
current_type = -1;
score += 10;
}
void remove_full_lines() {
int full_lines = 0;
for (int i = HEIGHT - 1; i >= 0; i--) {
int is_full = 1;
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] == 0) {
is_full = 0;
break;
}
}
if (is_full) {
full_lines++;
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;
}
i++;
}
}
score += full_lines * 100;
}
void game_over() {
printf("Game Over!\n");
printf("Your score: %d\n", score);
exit(0);
}
void game_loop() {
while (1) {
if (current_type == -1) {
generate_shape();
current_x = WIDTH / 2 - 1;
current_y = 0;
if (check_collision(current_x, current_y)) {
game_over();
}
}
draw_board();
if (_kbhit()) {
char c = _getch();
if (c == 'a') {
if (!check_collision(current_x - 1, current_y)) {
current_x--;
}
} else if (c == 'd') {
if (!check_collision(current_x + 1, current_y)) {
current_x++;
}
} else if (c == 's') {
if (!check_collision(current_x, current_y + 1)) {
current_y++;
}
} else if (c == ' ') {
while (!check_collision(current_x, current_y + 1)) {
current_y++;
}
} else if (c == 'q') {
exit(0);
}
}
if (check_collision(current_x, current_y + 1)) {
place_shape();
remove_full_lines();
} else {
current_y++;
}
Sleep(100);
}
}
int main() {
srand(time(NULL));
game_loop();
return 0;
}
```
希望这个代码示例能够帮助您!如果您有任何问题或需要进一步的帮助,请随时联系我。
阅读全文