用c++做一个俄罗斯方块游戏代码
时间: 2023-11-05 08:03:03 浏览: 42
以下是一个简单的俄罗斯方块游戏的C++代码示例:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
const int width = 10;
const int height = 20;
int board[height][width] = {0};
int shapes[7][4][2] =
{
{{0,1},{1,1},{2,1},{3,1}}, // I shape
{{0,1},{1,1},{2,1},{2,0}}, // L shape
{{0,1},{1,1},{2,1},{2,2}}, // J shape
{{1,0},{2,0},{1,1},{2,1}}, // O shape
{{0,1},{1,1},{1,0},{2,0}}, // Z shape
{{0,0},{1,0},{1,1},{2,1}}, // S shape
{{0,1},{1,1},{1,0},{2,1}} // T shape
};
void print_board()
{
system("cls");
cout << "========================" << endl;
for(int i=0; i<height; i++)
{
cout << "|";
for(int j=0; j<width; j++)
{
if(board[i][j] == 0)
cout << " ";
else
cout << "*";
}
cout << "|" << endl;
}
cout << "========================" << endl;
}
int check_collision(int x, int y, int shape)
{
for(int i=0; i<4; i++)
{
int next_x = x + shapes[shape][i][0];
int next_y = y + shapes[shape][i][1];
if(next_x < 0 || next_x >= width || next_y >= height || board[next_y][next_x] != 0)
return 1;
}
return 0;
}
void place_shape(int x, int y, int shape)
{
for(int i=0; i<4; i++)
{
int next_x = x + shapes[shape][i][0];
int next_y = y + shapes[shape][i][1];
board[next_y][next_x] = 1;
}
}
void remove_shape(int x, int y, int shape)
{
for(int i=0; i<4; i++)
{
int next_x = x + shapes[shape][i][0];
int next_y = y + shapes[shape][i][1];
board[next_y][next_x] = 0;
}
}
int main()
{
srand(time(NULL));
int x = width / 2;
int y = 0;
int shape = rand() % 7;
while(true)
{
if(check_collision(x, y+1, shape))
{
place_shape(x, y, shape);
shape = rand() % 7;
x = width / 2;
y = 0;
}
else
{
remove_shape(x, y, shape);
y++;
place_shape(x, y, shape);
}
print_board();
Sleep(100);
}
return 0;
}
```
这个代码可以在终端中运行,使用WASD键控制方块移动,Q键旋转方块。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)