1

Hello everyone I'm trying to make a Tetris game with C++. I'm looking that tutorial

#include <iostream>
#include <string>
using namespace std;

int nFieldWidth = 12;
int nFieldHeight = 18;
unsigned char *pField = nullptr;   //dynamic memory allocation for store game area elements

int main(){
...

pField = new unsigned char[nFieldHeight * nFieldWidth]; 
for(int x = 0; x < nFieldWidth; x++)
    for(int y = 0; y < nFieldHeight; y++)
        pField[y*nFieldWidth+x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;
...
system("pause");
return 0;
}

What are we doing in this conditional branching? I know that

if(x == 0 || x == nFieldWidth -1 || y == nFieldHeight -1)
   pField[y*nFieldWidth+x] = 9;
else
   pField[y*nFieldWidth+x] = 0;

Are we allocating memory? If we are why we set to 9 , in the global we choose 12 and 18 as a border length??

unamattina
  • 13
  • 3
  • 12 and 18 are the dimensions of the board. 0 and 9 indicate whether a cell is a boundary cell or not. – cigien Sep 12 '20 at 21:24
  • There's no memory allocation done at that point, no. – πάντα ῥεῖ Sep 12 '20 at 21:29
  • Sometimes it's helpful to do something crazy like change `? 9 : 0` to `? 0: 9` and see what happens. (Not in production code of course; this is for your own experimentation.) – JaMiT Sep 12 '20 at 21:41
  • why 0 and 9 for the boundary cell? @cigien – unamattina Sep 12 '20 at 21:43
  • What makes you think memory is being allocated there? Memory was allocated on the line `pField = new unsigned char[nFieldHeight * nFieldWidth];`. This is just filling in the array elements. – Barmar Sep 12 '20 at 22:00

1 Answers1

0

He explains it from 8:20 onward in the youtube video: pField is set to 0 if the slot is empty, otherwise 1 to 8 if it is occupied by one of the tetromini shapes. 9 is reserved for the board walls. So with that ternary condition he is initialising the board, setting it to empty (0) almost everywhere, unless the loop hits the edges (0 is the left edge, nFieldWidth - 1 is the right edge, nFieldHeight - 1 is the bottom edge), where he will place a wall slot (9) instead.

Giogre
  • 1,444
  • 7
  • 19
  • actually 7 tetromino shapes we have? – unamattina Sep 12 '20 at 21:47
  • @unamattina: I see, probably number 9 represents the walls because it is opposite (most distant) from 0 which is empty space. It is conceptually easier to remember that empty and wall are 0-9, then actual pieces can be any number inbetween. – Giogre Sep 12 '20 at 21:54