C++写一个俄罗斯方块
时间: 2023-04-03 22:02:36 浏览: 80
很高兴回答你的问题。以下是一个简单的俄罗斯方块的 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] = {};
int shapes[7][4][2] = {
{{, }, {, 1}, {1, }, {1, 1}}, // O
{{, }, {, 1}, {, 2}, {, 3}}, // I
{{, }, {, 1}, {, 2}, {1, 2}}, // L
{{, }, {, 1}, {, 2}, {-1, 2}}, // J
{{, }, {, 1}, {1, 1}, {1, 2}}, // S
{{, }, {, 1}, {-1, 1}, {-1, 2}}, // Z
{{, }, {, 1}, {, 2}, {1, 1}} // T
};
int current_shape = ;
int current_rotation = ;
int current_x = ;
int current_y = ;
void draw_board() {
system("cls");
for (int i = ; i < HEIGHT; i++) {
for (int j = ; j < WIDTH; j++) {
if (board[i][j] == ) {
printf(".");
} else {
printf("#");
}
}
printf("\n");
}
}
void draw_shape() {
for (int i = ; i < 4; i++) {
int x = current_x + shapes[current_shape][i][];
int y = current_y + shapes[current_shape][i][1];
board[y][x] = 1;
}
}
void erase_shape() {
for (int i = ; i < 4; i++) {
int x = current_x + shapes[current_shape][i][];
int y = current_y + shapes[current_shape][i][1];
board[y][x] = ;
}
}
int check_collision() {
for (int i = ; i < 4; i++) {
int x = current_x + shapes[current_shape][i][];
int y = current_y + shapes[current_shape][i][1];
if (x < || x >= WIDTH || y >= HEIGHT) {
return 1;
}
if (y >= && board[y][x] == 1) {
return 1;
}
}
return ;
}
void new_shape() {
current_shape = rand() % 7;
current_rotation = ;
current_x = WIDTH / 2 - 1;
current_y = ;
if (check_collision()) {
printf("Game over!\n");
exit();
}
}
void rotate_shape() {
erase_shape();
current_rotation = (current_rotation + 1) % 4;
if (check_collision()) {
current_rotation = (current_rotation - 1 + 4) % 4;
}
draw_shape();
}
void move_left() {
erase_shape();
current_x--;
if (check_collision()) {
current_x++;
}
draw_shape();
}
void move_right() {
erase_shape();
current_x++;
if (check_collision()) {
current_x--;
}
draw_shape();
}
void move_down() {
erase_shape();
current_y++;
if (check_collision()) {
current_y--;
draw_shape();
new_shape();
} else {
draw_shape();
}
}
int main() {
srand(time(NULL));
new_shape();
while (1) {
draw_board();
if (_kbhit()) {
char c = _getch();
if (c == 'a') {
move_left();
} else if (c == 'd') {
move_right();
} else if (c == 's') {
move_down();
} else if (c == 'w') {
rotate_shape();
}
}
Sleep(100);
move_down();
}
return ;
}
阅读全文