3
« on: March 03, 2011, 12:38:37 am »
Hello ppl
Im making a snake game for my exam in programming. Its my first year programming so i still consider myself new in C++ and SFML. A classmate recommended me SFML. I read some of the tutorials and so far i coded this:
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
int WindowWidth = 800;
int WindowLength = 600;
int PixelDepth = 32;
char WindowTitle[] = "Snake";
int BlockSize = 20;
int SnakeLength=1;
float FPS;
int Direction = 'R';
sf::RenderWindow App(sf::VideoMode(WindowWidth, WindowLength, PixelDepth), WindowTitle);
sf::Clock WindowClock;
// Load a sprite to display
sf::Image TailImg;
TailImg.LoadFromFile("tail.png");
sf::Sprite TailSprite(TailImg);
TailSprite.SetPosition(WindowWidth/2,WindowLength/2);
sf::String DifficultyText;
DifficultyText.SetFont(sf::Font::GetDefaultFont());
DifficultyText.SetText("HEJ");
DifficultyText.SetSize(30);
DifficultyText.SetColor(sf::Color(128, 128, 0));
DifficultyText.SetPosition(WindowWidth/2-DifficultyText.GetSize(),WindowLength-DifficultyText.GetSize());
//App.SetFramerateLimit(30);
while (App.IsOpened())
{
sf::Event WindowEvent;
while (App.GetEvent(WindowEvent))
{
// Window closed
if (WindowEvent.Type == sf::Event::Closed)
App.Close();
// Escape key pressed
if ((WindowEvent.Type == sf::Event::KeyPressed) && (WindowEvent.Key.Code == sf::Key::Escape))
App.Close();
if ((WindowEvent.Type == sf::Event::KeyPressed) && (WindowEvent.Key.Code == sf::Key::Up))
{
Direction = 'U';
TailSprite.Move(0,-BlockSize);
}
else if ((WindowEvent.Type == sf::Event::KeyPressed) && (WindowEvent.Key.Code == sf::Key::Down))
{
Direction = 'D';
TailSprite.Move(0,BlockSize);
}
else if ((WindowEvent.Type == sf::Event::KeyPressed) && (WindowEvent.Key.Code == sf::Key::Right))
{
Direction = 'R';
TailSprite.Move(BlockSize,0);
}
else if ((WindowEvent.Type == sf::Event::KeyPressed) && (WindowEvent.Key.Code == sf::Key::Left))
{
Direction = 'L';
TailSprite.Move(-BlockSize,0);
}
}
FPS = 1.f / WindowClock.GetElapsedTime();
WindowClock.Reset();
std::cout << FPS << std::endl;
App.Clear(sf::Color(110, 235, 140));
App.Draw(TailSprite);
App.Draw(DifficultyText);
App.Display();
}
return EXIT_SUCCESS;
}
Now Im at the point where I have to get TailSprite moving in a desired direction until another direction is chosen. How can i achieve that? I guess i need to use sf::Clock and some kind of function?