Text Based Game(C++): 2048


Link to github: https://github.com/coffee-enthusiast/2048TextBased

A grid 4 x 4 of cells/boxes that either have a number or not.

class Cell
{
private:
	int m_value;
public:
	int getValue();
	void setValue(int value);
	Cell();
	~Cell();
};

The game loop is simple:

  • Spawn a new cell with value 2 or 4
  • Player chooses a direction to move all the cells(Up,Down,Right,Left)
  • All the cells are moved towards the selected direction

This is the code that gets executed when player chooses Up as a direction:

void MoveUp(int y, int x)
{
	if (table[y][x].getValue() != 0)
	{
		// If upper cell is empty
		int upperValue = table[y - 1][x].getValue();
		if (upperValue == 0)
		{
			table[y - 1][x].setValue(table[y][x].getValue());
			table[y][x].setValue(0);
			somethingMoved = true;
			if (y - 2 >= 0)
				MoveUp(y - 1, x);
		}
		else
		{
			if (upperValue == table[y][x].getValue() && !mixHappened)
			{
				table[y - 1][x].setValue(table[y][x].getValue() * 2);
				table[y][x].setValue(0);
				if (table[y][x].getValue() * 2 > maxScore)
					maxScore = table[y][x].getValue() * 2;
				cellsFilled--;
				mixHappened = true;
				somethingMoved = true;
			}
		}
	}
}

table[][] is 4 by 4 array of cells that hold the number of each cell.

somethingMoved is a global bool that gets true if a cell moved, when its true at the end of the game loop a new random cell will be spawned.

mixHappened is a bool that gets true when 2 cells with the same value touch and they mix together to a new cell with double their value. It is used to prevent from consecutive cell mixes.

The method is called for each cell from the main() method:

playerInput = getchar();
		switch (playerInput)
		{
		case 'w':
			for (int x = 0; x < 4; x++)
			{
				mixHappened = false;
				for (int y = 1; y < 4; y++)
				{
					MoveUp(y,x);
				}
			}
			break;