AllenYuan

falling

May 24th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 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.   float timer = 0, delay = 0.3; // tickrate
  36.  
  37.   Clock clock;
  38.  
  39.   while (window.isOpen()) // game loop
  40.   {
  41.     float time = clock.getElapsedTime().asSeconds();
  42.     clock.restart();
  43.     timer += time;
  44.  
  45.     Event e;
  46.     while (window.pollEvent(e)) // close window
  47.     {
  48.       if (e.type == Event::Closed)
  49.         window.close();
  50.  
  51.       if (e.type == Event::KeyPressed) //rotate/move tile
  52.         if (e.key.code == Keyboard::Up) rotate = true;
  53.         else if (e.key.code == Keyboard::Left) dx=-1;
  54.         else if (e.key.code == Keyboard::Right) dx=1;
  55.     }
  56.  
  57.     for (int i =0; i < 4; i++) a[i].x += dx; //left/right movement
  58.  
  59.     if (rotate) // rotate clockwise
  60.     {
  61.       Point p = a[1]; // center of rotation
  62.       for (int i = 0; i < 4; i++) // shift each square
  63.       {
  64.         int x = a[i].y-p.y;
  65.         int y = a[i].x-p.x;
  66.         a[i].x = p.x - x;
  67.         a[i].y = p.y + y;
  68.       }
  69.     }
  70.  
  71.     if (timer > delay) // drop the block
  72.     {
  73.       for (int i = 0; i < 4; i++) a[i].y += 1;
  74.       timer = 0;
  75.     }
  76.  
  77.     int n = 3;
  78.     if (a[0].x==0)
  79.       for (int i = 0; i < 4; i++) // load T tile into a
  80.       {
  81.         a[i].x = figures[n][i] % 2;
  82.         a[i].y = figures[n][i] / 2;
  83.       }
  84.  
  85.     dx = 0; rotate = 0;
  86.  
  87.     window.clear(Color::White); // draw tiles
  88.     for (int i = 0; i < 4; i++)
  89.     {
  90.       s.setPosition(a[i].x*18,a[i].y*18);
  91.       window.draw(s);
  92.     }
  93.     window.display();
  94.   }
  95.  
  96.   return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment