用继承多态写俄罗斯方块c++
时间: 2023-06-26 19:06:02 浏览: 228
好的,下面是一个简单的使用继承和多态的 C++ 代码实现俄罗斯方块游戏。
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 方块类
class Block {
protected:
int x, y; // 方块位置
public:
Block(int x = 0, int y = 0) : x(x), y(y) {}
virtual void draw() {} // 绘制方块
virtual void moveDown() { y++; } // 方块下落
virtual void moveLeft() { x--; } // 方块左移
virtual void moveRight() { x++; } // 方块右移
};
// I形方块类
class BlockI : public Block {
public:
BlockI(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "I"; }
};
// J形方块类
class BlockJ : public Block {
public:
BlockJ(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "J"; }
};
// L形方块类
class BlockL : public Block {
public:
BlockL(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "L"; }
};
// O形方块类
class BlockO : public Block {
public:
BlockO(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "O"; }
};
// S形方块类
class BlockS : public Block {
public:
BlockS(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "S"; }
};
// T形方块类
class BlockT : public Block {
public:
BlockT(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "T"; }
};
// Z形方块类
class BlockZ : public Block {
public:
BlockZ(int x = 0, int y = 0) : Block(x, y) {}
virtual void draw() { cout << "Z"; }
};
// 随机生成方块
Block *randomBlock() {
int type = rand() % 7;
switch (type) {
case 0: return new BlockI();
case 1: return new BlockJ();
case 2: return new BlockL();
case 3: return new BlockO();
case 4: return new BlockS();
case 5: return new BlockT();
case 6: return new BlockZ();
}
return NULL;
}
// 游戏主循环
int main() {
srand(time(NULL));
Block *block = randomBlock(); // 随机生成方块
while (true) {
// 绘制游戏区域
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
if (i == block->x && j == block->y) {
block->draw();
}
else {
cout << ".";
}
}
cout << endl;
}
cout << endl;
// 方块下落
block->moveDown();
// 暂停一段时间
for (int i = 0; i < 100000000; i++) {}
// 清除上一次的绘制
system("cls");
}
return 0;
}
```
这个代码实现了七种不同形状的方块,并且使用了继承和多态来实现方块的绘制和移动。在主循环中,首先随机生成一个方块,并且不断重复绘制游戏区域、方块下落、暂停一段时间和清除上一次的绘制的过程,从而模拟整个俄罗斯方块游戏的过程。
阅读全文
相关推荐















