switch (5 in a Row) – WIP

5 in a row

This week has been filled with new terms like Polymorphism, friend classes, virtual methods, forward declare, finite state machines… My brain feels melted. As a novice programmer these things may need some time to fully understand.

To help find my confidence again I decided to create a simple code for the game ”5 in a row”. Originally it’s a board game where two players by turns drop bricks on the top of the board where you can see the pieces fall down and stays in a lane. The more bricks you drop in same place the higher they stack up together. The goal is to make a row of five with your own bricks.

NOTE: The picture above is my rendered code from where I am now in the project, therefor theres only one color for one player at the moment.

I want to show one method that I am pretty happy with and how it worked so well with this type of game:

In a ‘board class’ a have a method ‘Set(int index, char brick)’. This method is used to set new bricks to the board.


bool Board::Set(int index, char brick)
{
switch (numberOfBricks[index]) {
case 6:    return false;    // "the column is already full with bricks"
break;
case 5: board[index][0] = brick;
break;
case 4: board[index][1] = brick;
break;
case 3: board[index][2] = brick;
break;
case 2: board[index][3] = brick;
break;
case 1: board[index][4] = brick;
break;
case 0: board[index][5] = brick;
break;
}
numberOfBricks[index]++;
return true;
}

In this method, as you can see, exists a ‘switch’ with an integer array ‘numberOfBricks[7]’ that represent how many bricks there currently are in the specific column. Each element of ‘numberOfBricks’ (7 elements total) is already initialized with the value 0 in the main constructed of the class. When the player, during the game, enter an integer from 0-6 (should be 1-7) the ‘Set’-method recives that value and check how many bricks of each column and then decide where to put brick, as if the brick falls down and lands on top of another brick. ‘numberOfBricks’ is then +1 to ”save” how many bricks there are in that specific column till next player does a move.

I’ve never described code in this way before but I hope this example was understandable. I’m not going into more details on this game but hopefully someone read and enjoyed this 😛

About Johannes Westberg

2014  Programming