给我一份基于qt的贪吃蛇代码
时间: 2023-11-04 08:02:34 浏览: 33
好的,以下是一份基于Qt的贪吃蛇代码:
```cpp
#include <QApplication>
#include <QMainWindow>
#include <QTimer>
#include <QKeyEvent>
#include <QPainter>
class Snake : public QMainWindow {
public:
Snake() {
setFixedSize(400, 400);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(move()));
m_timer->start(100);
m_snake.append(QPoint(width() / 2, height() / 2));
m_snake.append(QPoint(width() / 2, height() / 2 + 10));
m_snake.append(QPoint(width() / 2, height() / 2 + 20));
}
void paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
painter.setPen(Qt::white);
painter.setBrush(Qt::green);
for (int i = 0; i < m_snake.size(); i++) {
painter.drawRect(m_snake[i].x(), m_snake[i].y(), 10, 10);
}
painter.setBrush(Qt::red);
painter.drawRect(m_food.x(), m_food.y(), 10, 10);
}
void keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Left) {
m_direction = QPoint(-10, 0);
} else if (event->key() == Qt::Key_Right) {
m_direction = QPoint(10, 0);
} else if (event->key() == Qt::Key_Up) {
m_direction = QPoint(0, -10);
} else if (event->key() == Qt::Key_Down) {
m_direction = QPoint(0, 10);
}
}
public slots:
void move() {
QPoint head = m_snake.first();
head += m_direction;
m_snake.prepend(head);
if (head == m_food) {
m_food = QPoint(qrand() % (width() / 10) * 10, qrand() % (height() / 10) * 10);
} else {
m_snake.removeLast();
}
if (head.x() < 0 || head.x() >= width() || head.y() < 0 || head.y() >= height()) {
m_timer->stop();
QMessageBox::information(this, "Game Over", "You hit the wall!");
}
for (int i = 1; i < m_snake.size(); i++) {
if (head == m_snake[i]) {
m_timer->stop();
QMessageBox::information(this, "Game Over", "You hit yourself!");
}
}
update();
}
private:
QList<QPoint> m_snake;
QPoint m_direction = QPoint(0, -10);
QPoint m_food = QPoint(qrand() % (width() / 10) * 10, qrand() % (height() / 10) * 10);
QTimer *m_timer;
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Snake s;
s.show();
return a.exec();
}
```
希望这份代码对你有帮助!