Search code examples
c++arrayspointersdynamic-memory-allocationtetris

Can we assign a value to pointer unsigned char array?


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??


Solution

  • 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.