你能写一个qt做的贪吃蛇游戏吗
时间: 2024-03-08 16:47:21 浏览: 48
当然可以,以下是一个简单的Qt贪吃蛇游戏示例:
```cpp
#include <QtWidgets>
class SnakeGame : public QWidget
{
public:
SnakeGame(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
private:
enum Direction {
Up, Down, Left, Right
};
struct SnakeSegment {
int x, y;
};
QVector<SnakeSegment> snake;
QPoint food;
Direction direction;
bool game_over;
QTimer timer;
void moveSnake();
bool checkCollision();
QPoint generateFood();
};
SnakeGame::SnakeGame(QWidget *parent)
: QWidget(parent)
{
setWindowTitle("Snake Game");
setFixedSize(300, 300);
snake.append({10, 10});
snake.append({10, 11});
snake.append({10, 12});
food = generateFood();
direction = Right;
game_over = false;
timer.setInterval(100);
connect(&timer, &QTimer::timeout, this, &SnakeGame::moveSnake);
timer.start();
}
void SnakeGame::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
// Draw the snake
painter.setBrush(Qt::green);
for (const auto &segment : snake) {
painter.drawRect(segment.x * 10, segment.y * 10, 10, 10);
}
// Draw the food
painter.setBrush(Qt::red);
painter.drawRect(food.x() * 10, food.y() * 10, 10, 10);
// Draw game over message if necessary
if (game_over) {
painter.setPen(Qt::red);
painter.drawText(rect(), Qt::AlignCenter, "Game Over");
}
}
void SnakeGame::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Up:
if (direction != Down) {
direction = Up;
}
break;
case Qt::Key_Down:
if (direction != Up) {
direction = Down;
}
break;
case Qt::Key_Left:
if (direction != Right) {
direction = Left;
}
break;
case Qt::Key_Right:
if (direction != Left) {
direction = Right;
}
break;
default:
QWidget::keyPressEvent(event);
}
}
void SnakeGame::moveSnake()
{
// Move the snake
SnakeSegment head = snake.first();
switch (direction) {
case Up:
head.y -= 1;
break;
case Down:
head.y += 1;
break;
case Left:
head.x -= 1;
break;
case Right:
head.x += 1;
break;
}
snake.prepend(head);
// Check for collision
if (checkCollision()) {
game_over = true;
timer.stop();
update();
return;
}
// Check for food
if (head.x == food.x() && head.y == food.y()) {
food = generateFood();
} else {
snake.removeLast();
}
update();
}
bool SnakeGame::checkCollision()
{
// Check for collision with walls
SnakeSegment head = snake.first();
if (head.x < 0 || head.x >= 30 || head.y < 0 || head.y >= 30) {
return true;
}
// Check for collision with body
for (int i = 1; i < snake.size(); ++i) {
if (head.x == snake.at(i).x && head.y == snake.at(i).y) {
return true;
}
}
return false;
}
QPoint SnakeGame::generateFood()
{
QPoint food;
do {
food.setX(qrand() % 30);
food.setY(qrand() % 30);
} while (snake.contains({food.x(), food.y()}));
return food;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
SnakeGame game;
game.show();
return app.exec();
}
```
这个示例创建了一个QWidget,绘制了一个简单的贪吃蛇游戏。当你运行这个程序时,你将看到一个绿色的贪吃蛇,一个红色的食物,以及一个游戏窗口。你可以使用方向键来控制贪吃蛇的移动方向,当贪吃蛇碰到墙壁或自己时,游戏结束。
阅读全文