用c++编写俄罗斯方块代码
时间: 2023-03-31 18:01:35 浏览: 101
好的,我可以回答这个问题。以下是一个简单的俄罗斯方块代码示例:
#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}}, // Z
{{, }, {, 1}, {-1, 1}, {-1, 2}}, // S
{{, }, {, 1}, {, 2}, {1, 1}} // T
};
int cur_shape[4][2];
int cur_x, cur_y, cur_type;
int score = ;
void init_game()
{
srand(time(NULL));
cur_type = rand() % 7;
for (int i = ; i < 4; i++) {
cur_shape[i][] = shapes[cur_type][i][];
cur_shape[i][1] = shapes[cur_type][i][1];
}
cur_x = WIDTH / 2 - 1;
cur_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");
}
printf("Score: %d\n", score);
}
int check_collision(int x, int y, int type)
{
for (int i = ; i < 4; i++) {
int nx = x + cur_shape[i][];
int ny = y + cur_shape[i][1];
if (nx < || nx >= WIDTH || ny < || ny >= HEIGHT) {
return 1;
}
if (board[ny][nx] != ) {
return 1;
}
}
return ;
}
void place_shape()
{
for (int i = ; i < 4; i++) {
int nx = cur_x + cur_shape[i][];
int ny = cur_y + cur_shape[i][1];
board[ny][nx] = cur_type + 1;
}
}
void remove_lines()
{
int lines = ;
for (int i = HEIGHT - 1; i >= ; i--) {
int full = 1;
for (int j = ; j < WIDTH; j++) {
if (board[i][j] == ) {
full = ;
break;
}
}
if (full) {
lines++;
for (int k = i; k > ; k--) {
for (int j = ; j < WIDTH; j++) {
board[k][j] = board[k - 1][j];
}
}
for (int j = ; j < WIDTH; j++) {
board[][j] = ;
}
i++;
}
}
score += lines * lines * 100;
}
void game_loop()
{
while (1) {
draw_board();
if (check_collision(cur_x, cur_y + 1, cur_type)) {
place_shape();
remove_lines();
init_game();
if (check_collision(cur_x, cur_y, cur_type)) {
break;
}
} else {
cur_y++;
}
if (_kbhit()) {
int c = _getch();
if (c == 'a' && !check_collision(cur_x - 1, cur_y, cur_type)) {
cur_x--;
} else if (c == 'd' && !check_collision(cur_x + 1, cur_y, cur_type)) {
cur_x++;
} else if (c == 's' && !check_collision(cur_x, cur_y + 1, cur_type)) {
cur_y++;
} else if (c == 'w') {
int new_type = (cur_type + 1) % 7;
int new_shape[4][2];
for (int i = ; i < 4; i++) {
new_shape[i][] = shapes[new_type][i][];
new_shape[i][1] = shapes[new_type][i][1];
}
if (!check_collision(cur_x, cur_y, new_type)) {
cur_type = new_type;
for (int i = ; i < 4; i++) {
cur_shape[i][] = new_shape[i][];
cur_shape[i][1] = new_shape[i][1];
}
}
} else if (c == 'q') {
break;
}
}
Sleep(100);
}
}
int main()
{
init_game();
game_loop();
printf("Game over!\n");
return ;
}
阅读全文