用c++写能穿墙,能加速的贪吃蛇代码
时间: 2023-10-14 16:26:36 浏览: 140
用c++写的贪吃蛇
以下是一个简单的能穿墙、能加速的贪吃蛇代码,使用了C++语言和SFML库实现:
```c++
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
int main()
{
// 创建窗口
sf::RenderWindow window(sf::VideoMode(800, 600), "Snake Game");
// 设置帧率
window.setFramerateLimit(60);
// 创建蛇头
sf::RectangleShape head(sf::Vector2f(20, 20));
head.setFillColor(sf::Color::Green);
head.setPosition(400, 300);
// 创建蛇身
std::vector<sf::RectangleShape> body;
for(int i = 0; i < 3; i++) {
body.emplace_back(sf::Vector2f(20, 20));
body.back().setFillColor(sf::Color::Green);
body.back().setPosition(380-i*20, 300);
}
// 初始化移动方向
int direction = 0; // 0: 向右, 1: 向下, 2: 向左, 3: 向上
// 初始化加速
bool speedUp = false;
// 游戏循环
while (window.isOpen()) {
// 处理事件
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Right && direction != 2) {
direction = 0;
}
if (event.key.code == sf::Keyboard::Down && direction != 3) {
direction = 1;
}
if (event.key.code == sf::Keyboard::Left && direction != 0) {
direction = 2;
}
if (event.key.code == sf::Keyboard::Up && direction != 1) {
direction = 3;
}
if (event.key.code == sf::Keyboard::Space) {
speedUp = true;
}
}
if (event.type == sf::Event::KeyReleased) {
if (event.key.code == sf::Keyboard::Space) {
speedUp = false;
}
}
}
// 移动蛇头
if (direction == 0) {
head.move(2*(speedUp?2:1), 0);
} else if (direction == 1) {
head.move(0, 2*(speedUp?2:1));
} else if (direction == 2) {
head.move(-2*(speedUp?2:1), 0);
} else if (direction == 3) {
head.move(0, -2*(speedUp?2:1));
}
// 穿墙
if (head.getPosition().x > 800) {
head.setPosition(0, head.getPosition().y);
}
if (head.getPosition().x < 0) {
head.setPosition(800, head.getPosition().y);
}
if (head.getPosition().y > 600) {
head.setPosition(head.getPosition().x, 0);
}
if (head.getPosition().y < 0) {
head.setPosition(head.getPosition().x, 600);
}
// 移动蛇身
for (int i = body.size()-1; i > 0; i--) {
body[i].setPosition(body[i-1].getPosition());
}
body[0].setPosition(head.getPosition());
// 检测蛇头和蛇身是否碰撞
for (auto& part : body) {
if (head.getGlobalBounds().intersects(part.getGlobalBounds())) {
std::cout << "Game Over!" << std::endl;
window.close();
}
}
// 渲染
window.clear();
window.draw(head);
for (auto& part : body) {
window.draw(part);
}
window.display();
}
return 0;
}
```
这段代码使用了SFML库来实现窗口、图形等的操作。游戏循环中处理了事件、移动蛇头和蛇身、碰撞检测等逻辑,并在循环中渲染了游戏画面。其中,穿墙逻辑通过判断蛇头是否超出窗口边界来实现,加速逻辑通过按下空格键来切换加速状态来实现。
阅读全文