AllenYuan

tile rotation

May 24th, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <time.h>
  3. using namespace sf;
  4.  
  5. const int M = 20;
  6. const int N = 10;
  7.  
  8. int field[M][N] = {0}; // tetris grid
  9.  
  10. struct Point
  11. { int x,y; } a[4], b[4]; // current/next tile = 4 points
  12.  
  13. int figures[7][4] = // encode blocks as 4 squares on a 2x4 rectangular grid indexed 0,...,7
  14. {
  15.   1,3,5,7, // I
  16.   2,4,5,7, // Z
  17.   3,5,4,6, // S
  18.   3,5,4,7, // T
  19.   2,3,5,7, // L
  20.   3,5,7,6, // J
  21.   2,3,4,5, // 0
  22. };
  23.  
  24. int main()
  25. {
  26.   RenderWindow window(VideoMode(320, 480), "The Game!"); // window config
  27.  
  28.   Texture t;
  29.   t.loadFromFile("/Users/alleyuan/code-snippets/16_games/01 Tetris/images/tiles.png"); // load sprite. replace my absolute path
  30.  
  31.   Sprite s(t);
  32.   s.setTextureRect(IntRect(0,0,18,18));
  33.  
  34.   int dx = 0; bool rotate = 0; int colorNum=1;
  35.  
  36.   while (window.isOpen()) // game loop
  37.   {
  38.     Event e;
  39.     while (window.pollEvent(e)) // close window
  40.     {
  41.       if (e.type == Event::Closed)
  42.         window.close();
  43.  
  44.       if (e.type == Event::KeyPressed) //rotate/move tile
  45.         if (e.key.code == Keyboard::Up) rotate = true;
  46.         else if (e.key.code == Keyboard::Left) dx=-1;
  47.         else if (e.key.code == Keyboard::Right) dx=1;
  48.     }
  49.  
  50.     for (int i =0; i < 4; i++) a[i].x += dx; //left/right movement
  51.  
  52.     if (rotate) // rotate clockwise
  53.     {
  54.       Point p = a[1]; // center of rotation
  55.       for (int i = 0; i < 4; i++) // shift each square
  56.       {
  57.         int x = a[i].y-p.y;
  58.         int y = a[i].x-p.x;
  59.         a[i].x = p.x - x;
  60.         a[i].y = p.y + y;
  61.       }
  62.     }
  63.  
  64.     int n = 3;
  65.     if (a[0].x==0)
  66.       for (int i = 0; i < 4; i++) // load T tile into a
  67.       {
  68.         a[i].x = figures[n][i] % 2;
  69.         a[i].y = figures[n][i] / 2;
  70.       }
  71.  
  72.     dx = 0; rotate = 0;
  73.  
  74.     window.clear(Color::White); // draw tiles
  75.     for (int i = 0; i < 4; i++)
  76.     {
  77.       s.setPosition(a[i].x*18,a[i].y*18);
  78.       window.draw(s);
  79.     }
  80.     window.display();
  81.   }
  82.  
  83.   return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment