I'm trying to write game snake
I'm having trouble making the snake move, help me move the snake
I want snake move slow , when i write it move very fast
thanks
#include <SFML/Graphics.hpp>
struct Pos2D
{
int x; int y;
int ox; int oy;
sf::Texture snakeTexture;
sf::Sprite snakeSprite;
};
int boardW; int boardH;
Pos2D snake[100];
int snakeLength;
Pos2D direction;
bool endGame;
float sox; float soy;
sf::RenderWindow window;
sf::Event event;
sf::Clock Clock;
sf::Time ElapsedTime = Clock.getElapsedTime();
void init()
{
boardW = 640;
boardH = 480;
//Thiết lập window
window.create(sf::VideoMode(boardW, boardH), "My Window");
// khởi tạo con rắn gồm có 5 ô
snake[0].x = 5; snake[0].y = 5;
snake[1].x = 4; snake[1].y = 5;
snake[2].x = 3; snake[2].y = 5;
snake[3].x = 2; snake[3].y = 5;
snake[4].x = 1; snake[4].y = 5;
//Load Texture 5 ô
snakeLength = 5;
for (int i = 0; i < snakeLength; i++)
snake[i].snakeTexture.loadFromFile("block.png");
for (int i = 0; i < snakeLength; i++)
snake[i].snakeSprite.setTexture(snake[i].snakeTexture);
// hướng di chuyển ban đầu là đi phải
direction.x = 1; direction.y = 0;
//Tọa độ đầu của rắn
sox = (snakeLength * 24) - 24;
soy = 0;
//Chiều dài con rắn
endGame = false;
}
void moveSnake(Pos2D dir)
{
if (dir.x = 1)
snake[0].snakeSprite.move(dir.x = 1.f, dir.y = 0.f);
/*else if (direction.x = -1)
_sox += 24;
else if (direction.y = 1)
_soy -= 24;
else if (direction.y = -1)
_soy += 24;*/
}
void drawSnake(int _sox,int _soy)
{
for (int i = 0; i < snakeLength; i++)
{
snake[i].snakeSprite.setPosition(sf::Vector2f(_sox, _soy));
window.draw(snake[i].snakeSprite);
if (direction.x = 1)
_sox -= 24;
else if (direction.x = -1)
_sox += 24;
else if (direction.y = 1)
_soy -= 24;
else if (direction.y = -1)
_soy += 24;
}
}
void CheckKey(sf::Keyboard::Key key)
{
if (key = sf::Keyboard::Up)
//Up
if (direction.y != 1)
{
direction.y = -1;
direction.x = 0;
}
else if (key = sf::Keyboard::Down)
//Down
if (direction.y != -1)
{
direction.y = 1;
direction.x = 0;
}
else if (key = sf::Keyboard::Left)
//Left
if (direction.x != 1)
{
direction.y = 0;
direction.x = -1;
}
else if (key = sf::Keyboard::Right)
//Right
if (direction.x != -1)
{
direction.y = 0;
direction.x = 1;
}
}
int main()
{
init();
while (window.isOpen())
{
Clock.restart();
// check all the window's events that were triggered since the last iteration of the loop
while (window.pollEvent(event))
{
switch (event.type)
{
case (sf::Event::Closed) :
window.close();
break;
case (sf::Event::KeyPressed) :
CheckKey(event.key.code);
break;
}
}
// clear the window with black color
window.clear(sf::Color::Black);
moveSnake(direction);
drawSnake(sox, soy);
// draw everything here...
// window.draw(...);
// end the current frame
window.display();
}
return 0;
}