对于AI助手来说,无法实际编写代码。但是以下是一个简单的贪吃蛇项目的代码示例:
#include <QtWidgets>
class Snake : public QWidget {
public:
Snake(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *) override;
void keyPressEvent(QKeyEvent *) override;
private:
enum Direction { Up, Down, Left, Right };
QVector<QPoint> snake;
QPoint food;
int score = 0;
Direction dir = Right;
void initializeGame();
void createFood();
void moveSnake();
bool isGameOver() const;
};
Snake::Snake(QWidget *parent)
: QWidget(parent)
{
setFixedSize(400, 400);
setWindowTitle("Snake Game");
initializeGame();
}
void Snake::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// draw the snake
painter.setBrush(Qt::darkGreen);
for (const auto &segment : snake) {
painter.drawRect(segment.x(), segment.y(), 10, 10);
}
// draw the food
painter.setBrush(Qt::red);
painter.drawRect(food.x(), food.y(), 10, 10);
// draw the score
painter.setPen(Qt::black);
painter.setFont(QFont("Arial", 14));
painter.drawText(rect(), Qt::AlignTop | Qt::AlignRight,
QString("Score: %1").arg(score));
}
void Snake::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Up:
if (dir != Down) dir = Up;
break;
case Qt::Key_Down:
if (dir != Up) dir = Down;
break;
case Qt::Key_Left:
if (dir != Right) dir = Left;
break;
case Qt::Key_Right:
if (dir != Left) dir = Right;
break;
}
}
void Snake::initializeGame()
{
snake.clear();
snake << QPoint(20, 20) << QPoint(10, 20) << QPoint(0, 20);
createFood();
score = 0;
dir = Right;
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &Snake::moveSnake);
timer->start(100);
}
void Snake::createFood()
{
int x = qrand() % (width() / 10) * 10;
int y = qrand() % (height() / 10) * 10;
food = QPoint(x, y);
}
void Snake::moveSnake()
{
QPoint head = snake.first();
switch (dir) {
case Up: head.setY(head.y() - 10); break;
case Down: head.setY(head.y() + 10); break;
case Left: head.setX(head.x() - 10); break;
case Right: head.setX(head.x() + 10); break;
}
snake.prepend(head);
if (head == food) {
createFood();
score += 10;
} else {
snake.removeLast();
}
update();
if (isGameOver()) {
QMessageBox::information(this, "Game Over", "You lost!");
initializeGame();
}
}
bool Snake::isGameOver() const
{
// check if the snake has hit a wall
if (snake.first().x() < 0 || snake.first().x() >= width()
|| snake.first().y() < 0 || snake.first().y() >= height()) {
return true;
}
// check if the snake has hit itself
for (int i = 1; i < snake.size(); ++i) {
if (snake.at(i) == snake.first()) return true;
}
return false;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Snake game;
game.show();
return app.exec();
}