用C++写一个钟摆小游戏
时间: 2023-12-07 22:00:33 浏览: 27
好的,以下是一个简单的钟摆小游戏的 C++ 实现:
```c++
#include <iostream>
#include <cmath>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 80; // 窗口宽度
const int HEIGHT = 25; // 窗口高度
const double PI = 3.1415926;
// 画布类
class Canvas {
public:
Canvas() {
// 将光标隐藏
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
// 将窗口大小设置为指定大小
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
_COORD size = { WIDTH, HEIGHT };
SetConsoleScreenBufferSize(handle, size);
SMALL_RECT rc = { 0, 0, WIDTH - 1, HEIGHT - 1 };
SetConsoleWindowInfo(handle, TRUE, &rc);
}
void set(int x, int y, char c) {
m_buf[x][y] = c;
}
void draw() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
cout << m_buf[x][y];
}
cout << endl;
}
}
void clear() {
memset(m_buf, ' ', sizeof(m_buf));
}
private:
char m_buf[WIDTH][HEIGHT];
};
// 钟摆类
class Pendulum {
public:
Pendulum(int x, int y, double length, double angle)
: m_x(x), m_y(y), m_length(length), m_angle(angle) {}
void update(double time) {
double a = -9.8 / m_length * sin(m_angle);
m_angle += m_velocity * time;
m_velocity += a * time;
}
void draw(Canvas& canvas) {
int px = m_x + m_length * sin(m_angle);
int py = m_y + m_length * cos(m_angle);
canvas.set(px, py, 'O');
canvas.set(m_x, m_y, '+');
}
private:
int m_x, m_y; // 钟摆原点坐标
double m_length; // 钟摆长度
double m_angle; // 钟摆角度
double m_velocity = 0; // 钟摆角速度
};
// 游戏类
class Game {
public:
Game() : m_canvas() {}
void run() {
Pendulum pendulum(WIDTH / 2, HEIGHT / 2, 10, PI / 3);
m_canvas.clear();
while (true) {
m_canvas.clear();
pendulum.update(0.05);
pendulum.draw(m_canvas);
m_canvas.draw();
Sleep(50);
if (_kbhit()) {
break;
}
}
}
private:
Canvas m_canvas;
};
int main() {
Game game;
game.run();
return 0;
}
```
这个小游戏使用了 Windows 平台下的控制台 API,可以在 Windows 下编译并运行。它通过模拟物理学中的钟摆运动来实现,玩家无需操作,只需要观察钟摆的动态即可。