Advertisement
krot

SFML

Nov 2nd, 2019
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <time.h>
  3. using namespace sf;
  4.  
  5. int N=30,M=20;
  6. int size=16;
  7. int w = size*N;
  8. int h = size*M;
  9.  
  10. int dir,num=4;
  11.  
  12. struct Snake
  13. { int x,y;}  s[100];
  14.  
  15. struct Fruit
  16. { int x,y;} f;
  17.  
  18. void Tick()
  19.  {
  20.     for (int i=num;i>0;--i)
  21.      {s[i].x=s[i-1].x; s[i].y=s[i-1].y;}
  22.  
  23.     if (dir==0) s[0].y+=1;      
  24.     if (dir==1) s[0].x-=1;        
  25.     if (dir==2) s[0].x+=1;        
  26.     if (dir==3) s[0].y-=1;  
  27.  
  28.     if ((s[0].x==f.x) && (s[0].y==f.y))
  29.      {num++; f.x=rand()%N; f.y=rand()%M;}
  30.  
  31.     if (s[0].x>N) s[0].x=0;  if (s[0].x<0) s[0].x=N;
  32.     if (s[0].y>M) s[0].y=0;  if (s[0].y<0) s[0].y=M;
  33.  
  34.     for (int i=1;i<num;i++)
  35.      if (s[0].x==s[i].x && s[0].y==s[i].y)  num=i;
  36.  }
  37.  
  38. int main()
  39. {  
  40.     srand(time(0));
  41.  
  42.     RenderWindow window(VideoMode(w, h), "Snake Game!");
  43.  
  44.     Texture t1,t2;
  45.     t1.loadFromFile("images/white.png");
  46.     t2.loadFromFile("images/red.png");
  47.  
  48.     Sprite sprite1(t1);
  49.     Sprite sprite2(t2);
  50.  
  51.     Clock clock;
  52.     float timer=0, delay=0.1;
  53.  
  54.     f.x=10;
  55.     f.y=10;
  56.    
  57.     while (window.isOpen())
  58.     {
  59.         float time = clock.getElapsedTime().asSeconds();
  60.         clock.restart();
  61.         timer+=time;
  62.  
  63.         Event e;
  64.         while (window.pollEvent(e))
  65.         {
  66.             if (e.type == Event::Closed)      
  67.                 window.close();
  68.         }
  69.  
  70.         if (Keyboard::isKeyPressed(Keyboard::Left)) dir=1;  
  71.         if (Keyboard::isKeyPressed(Keyboard::Right)) dir=2;    
  72.         if (Keyboard::isKeyPressed(Keyboard::Up)) dir=3;
  73.         if (Keyboard::isKeyPressed(Keyboard::Down)) dir=0;
  74.  
  75.         if (timer>delay) {timer=0; Tick();}
  76.  
  77.    ////// draw  ///////
  78.     window.clear();
  79.  
  80.     for (int i=0; i<N; i++)
  81.       for (int j=0; j<M; j++)
  82.         { sprite1.setPosition(i*size, j*size);  window.draw(sprite1); }
  83.  
  84.     for (int i=0;i<num;i++)
  85.         { sprite2.setPosition(s[i].x*size, s[i].y*size);  window.draw(sprite2); }
  86.    
  87.     sprite2.setPosition(f.x*size, f.y*size);  window.draw(sprite2);    
  88.  
  89.     window.display();
  90.     }
  91.  
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement