因为我的上一个主题充满了经过编辑的版本,而且根本不是很清楚,而且因为我改变了很多东西并且我现在明白了我是如何做到的,所以我问了一个关于我的蛇的新问题:为什么我的蛇消失,因为当我调用AdvanceStep()时,是的它弹出一个元素,但在它push_back另一个元素之后?感谢您的帮助,我会有更好的态度。(通过@Jason C,要求某人放弃,或者对他说我偷了某人的代码,或者这是一个家庭作业,也应该得到更好的态度)。提前致谢。
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <deque>
void advanceStep();
sf::Event event;
/*sf::Clock clockSnake;
sf::Time elapse;*/
sf::Vector2i direction(0, 0);
class SnakeBlock
{
public:
sf::Texture texture;
sf::Sprite snakeblock;
int dir;
int lastX, lastY;
};
std::deque<SnakeBlock> Snake;
int main()
{
//elapse = clockSnake.getElapsedTime();
sf::Music epicMusic;
epicMusic.openFromFile("epicmusic.wav");
epicMusic.play();
SnakeBlock snakeHead;
snakeHead.texture.loadFromFile("spritesheetsnake.png", sf::IntRect(0,0,20,22));
snakeHead.snakeblock.setTexture(snakeHead.texture);
SnakeBlock snakeBody1;
snakeBody1.snakeblock.setTexture(*(snakeHead.snakeblock.getTexture()));
SnakeBlock snakeBody2;
snakeBody2.snakeblock.setTexture(*(snakeHead.snakeblock.getTexture()));
Snake.push_back(snakeHead);
Snake.push_back(snakeBody1);
Snake.push_back(snakeBody2);
Snake[2].snakeblock.setPosition(500,350);
Snake[1].snakeblock.setPosition(475, 338);
Snake[0].snakeblock.setPosition(450, 316);
sf::RenderWindow window(sf::VideoMode(1028,768), "SFML Snake");
window.setFramerateLimit(20);
while(window.isOpen())
{
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
epicMusic.stop();
window.close();
break;
default:
break;
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
direction.x = -1;
advanceStep();
for(int i = 1; i < Snake.size(); i++)
{
Snake[i].snakeblock.setPosition(Snake[i+1].snakeblock.getPosition().x-20, Snake[i+1].snakeblock.getPosition().y);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
direction.x = 1;
advanceStep();
for(int j = 1; j < Snake.size(); j++)
{
Snake[j].snakeblock.setPosition(Snake[j+1].snakeblock.getPosition().x+20, Snake[j+1].snakeblock.getPosition().y);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
direction.y = -1;
advanceStep();
for(int l = 1; l < Snake.size(); l++)
{
Snake[l].snakeblock.setPosition(Snake[l+1].snakeblock.getPosition().x, Snake[l+1].snakeblock.getPosition().y-22);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
direction.y = 1;
advanceStep();
for(int o = 1; o < Snake.size(); o++)
{
Snake[o].snakeblock.setPosition(Snake[o+1].snakeblock.getPosition().x, Snake[o+1].snakeblock.getPosition().y+22);
}
}
window.clear(sf::Color::Red);
for(unsigned int m = 0; m < Snake.size(); m++)
{
window.draw(Snake[m].snakeblock);
}
window.display();
}
return 0;
}
void advanceStep()
{
sf::Vector2f headpos;
headpos.x = Snake[0].snakeblock.getPosition().x;
headpos.y = Snake[0].snakeblock.getPosition().y;
headpos.x += 22 * direction.x;
headpos.y += 22 * direction.y;
SnakeBlock element;
element.snakeblock.setPosition(headpos);
Snake.push_front(element);
Snake.pop_back();
}