1

The game is going from left to right starting with >> and moving down the rows until the end >>. Here's a picture of the board printed for reference:

Printed Snakes and Ladders board

I want to be able to update and print a player's position immediately after they have cast the dice.

I can't understand how I'm meant to 'limit' the position variable so that it automatically transfers to the next row when it hits the end column of one. Another thing I'm struggling with is editing the printed board because I've made it into a function so //table[pos1][0]=219 is coded out because it doesn't make sense and it does nothing as such an array doesn't exist in main.

So far I've managed to create a pseudo random dice roll along with printing the starting position board and keeping track of each roll. Just to note, 219 and 176 are characters I've used for Player1 and Player2.

I've seen solutions of this with switch() statement but I'm not too sure about it and that doesn't solve my problem with updating the board and printing new position.

#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

void printBoard();

int main(){
    //Counters
    //int i,k,p;
    //Keeps track of position
    int pos1=0;
    int pos2=0;
    //Keeps track of turns
    int rollA=0;
    int rollB=0;

    int playerTurn;
    int rRoll;
    bool gameOn;
    gameOn=true;
    srand(time(0));

    printf("Starting Position:\n");
    printBoard();

    while(gameOn==true){
        printf("Enter player number to roll dice\n");
        scanf("%d",&playerTurn);
        rRoll=(rand() % 6) + 1;

        if(playerTurn==1){
            pos1=pos1+rRoll;
            //table[pos1][0]=219;
            rollA++;
            printf("You rolled a %d \nPlayed 1: %d times   Player 2: %d times\n",rRoll, rollA, rollB);
            printBoard();

        } else if(playerTurn==2){
            pos2=pos2+rRoll;
            rollB++;
            printf("You rolled a %d \nPlayed 1: %d times   Player 2: %d times\n",rRoll, rollA, rollB);
            printBoard();

            } else {
            printf("Please choose a valid Player\n");
            }

        /*gameOn=false;
        if(gameOn==false){
            printf("Congratulations Player %d wins! The game will now terminate. \n",playerWin);

            }*/
    }
    return 0;
}

void printBoard(){
    int i,k,p;
    char table[10][10];
    for(i=0; i<10; i++){
        for(k=0; k<10; k++){
            table[i][k]=46;
                for(p=2;p<8;p++){
                    table[p][3]=186;
                }
            table[4][9]=245;
            table[5][8]=245;
            table[6][7]=245;
            table[7][6]=245;
            table[8][5]=245;

            table[2][1]=219;
            table[1][2]=176;

            printf("%c",table[i][k]);
        }
        printf("\n");
    }
}
5
  • 3
    I'd probably store position as a single number from 0-99 or 1-100 and then compute how that maps onto the board position when you want to display it / check for snakes and ladders. That seems easier to me than having to worry about changing direction on odd / even rows etc. However even that's not too difficult; if pos1 becomes out of range then increment pos2 and then adjust pos1 for the position on the new row.
    – Rup
    Feb 10, 2020 at 11:25
  • @Rup does that mean that I would have to have two switch statements both with 0-99 cases for pos1 and pos2
    – Yasuo Main
    Feb 10, 2020 at 11:34
  • @Yasuo Main, Quite the opposite, that would allow you to use simple array lookups instead of complex switch or if statements. I fully endorse Rup's suggestion. /// The only complex part would be in the display routine, but it wouldn't be that complex. All you need is a formula would be used to convert the row and col into the array index, and that's not that complicated.
    – ikegami
    Feb 10, 2020 at 11:46
  • @ikegami how can I edit the function printBoard(); to not print the array immediately and instead output it to main where I can overwrite one of the dots with the new player positions; I've seen that if I create a position 0-99 when I choose any number say 35 this would map to table[3][5] so that's quite easy as you said
    – Yasuo Main
    Feb 10, 2020 at 12:53
  • 2
    Backwards. Pass the board and state (player positions) to printBoard (or use global variables so it already has access them) and let it print there board including player positions
    – ikegami
    Feb 10, 2020 at 12:55

1 Answer 1

0

This is my 'completed' version of the solution provided by @rykker. I have successfully managed to get both players going in the right direction (left-to-right instead of top-to-bottom), set up the in-game barriers, and create an end game condition that stops the game, which admittedly was not that challenging. I'm planning on updating this answer come Thursday.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <time.h>

//Improves code readability
#define POSITIONS (100 - 1) //assign 99 positions from 0-99
#define PLYR_ICON_1 219
#define PLYR_ICON_2 176
#define SNAKE 245
#define SNAKE_BEGIN 49
#define LADDER 186
#define LADDER_END 73
#define DOT 46
#define ROWS 10
#define COLS 10
#define START_END 175
#define ZERO 48
#define ONE 49
#define TWO 50

//Creates a global enumeration PLAYER - Improves code readability
enum {
    PLAYER1,    //Enumerator; state=0
    PLAYER2,    //Enumerator; state=1
    MAX_PLAYERS //Enumerator; state=2
}PLAYER;        //enum variable

//Creates a global struct POS containing an integer member position
typedef struct {
    int position;
}POS;

//Initializes function container that can pass position values for all players
void printBoard(POS *ptr);

int main(void){

    //local position initialized at 0
    int pos1=0;//local player1 position
    int pos2=0;//local player2 position

    //bounds check variable initialized at 0
    int check_position = 0;

    //turn counter initialized at 0
    int rollA=0;
    int rollB=0;

    POS *pos_global = calloc(MAX_PLAYERS, sizeof(*pos_global)); //creates a new pointer instance of the struct with enough space for MAX_PLAYERS(or 2) elements, 4bytes (the size of a pointer) each
    //used to pass information via function argument
    //free(pos_global) when done

    char input[10]={0}; //initializing array for user input for player turn
    int rRoll;          //random roll
    bool gameOn=true;   //bool utilized in while loop
    srand(time(0));     //pseudo-random seed generator for rand() depending on time(0);


    printf("Starting Position:\n");
    //Sets both positions to 0
    pos_global[PLAYER1].position = 0;   //equivalent to pos_global[0].position = 0
    pos_global[PLAYER2].position = 0;   //equivalent to pos_global[1].position = 0
    printBoard(pos_global);             //calls printBoard function passing pos_global for both players as 0, enabling the function to set both player tags in the starting position


    while(gameOn==true) //main game loop
    {
        printf("Enter player number to roll dice\n");
        fgets(input, sizeof(input), stdin); //stores user input as characters in the array input[]
        if((isdigit(input[0]))==0){         //checks if digit is entered; isdigit returns 0 if the 1st element of the array storing the user input isn't a digit, providing some input boundaries
            printf("Incorrect input please enter digits 0, 1 or 2 \n");
        }
        else{//code to be executed if a digit is entered for the first character

        rRoll=(rand() % 6) + 1; //random dice roll: any numbers remainder when divided by 6 will be between 0-5, adding one give 1-6 random dice roll

        if(input[0]==ONE){      //code to be executed if 1 is entered: PLAYER1's TURN
            pos1=pos1+rRoll;    //new position=old position+dice roll
            rollA++;            //adds one to the turn counter
            printf("You rolled a %d \n",rRoll);

            if (pos1>POSITIONS) //winning end-game condition (if new position is bigger than 99 (last position/end of board), end the game)
            {
                printf(" *** Game over. Player 1 wins! *** \n");
                free(pos_global); //deallocates the earlier allocated memory by calloc();
            }

            check_position = POSITIONS - pos1;
            if(check_position < 0) pos1 = pos1 - POSITIONS; //if pos>99, subtract the difference to pos, providing some bounds

            //Switch used to make ladder/snake functional
            switch (pos1)
                {
                case 23:
                case 33:
                case 43:
                case 53:
                case 63:
                    pos1=LADDER_END; //whenever PLAYER1 lands on any of the ladder positions, set his position at the LADDER_END (73th position)
                    break;

                case 85:
                case 76:
                case 67:
                case 58:
                case 69:
                    pos1=SNAKE_BEGIN; //whenever PLAYER1 lands on any of the snake positions, set his position at the SNAKE_BEGIN (49th position)
                    break;
                }

                pos_global[PLAYER1].position = pos1;    //updates the pointer instance with the new position for PLAYER1
                printBoard(pos_global);                 //prints the board with newly updated pointer
                printf("Player 1: %d times   Player 2: %d times\n",rollA, rollB);
        }
        else if(input[0]==TWO)  //code to be executed if 1 is entered: PLAYER1's TURN
        {
            pos2=pos2+rRoll;    //new position=old position+dice roll
            rollB++;            //adds one to the turn counter
            printf("You rolled a %d \n",rRoll);

            if (pos2>POSITIONS)
            {
                printf(" *** Game over. Player 2 wins! *** \n");
                free(pos_global); //deallocates the earlier allocated memory by calloc();
            }

            check_position = POSITIONS - pos2;
            if(check_position < 0) pos2 = pos2 - POSITIONS; //if pos>99, subtract the difference to pos, providing some bounds

            //Switch used to make ladder/snake functional
            switch (pos2){
                case 23:
                case 33:
                case 43:
                case 53:
                case 63:
                    pos2=LADDER_END;   //whenever PLAYER2 lands on any of the ladder positions, set his position at the LADDER_END (73th position)
                    break;

                case 85:
                case 76:
                case 67:
                case 58:
                case 69:
                    pos2=SNAKE_BEGIN;  //whenever PLAYER2 lands on any of the ladder positions, set his position at the LADDER_END (49th position)
                    break;
                }

            pos_global[PLAYER2].position = pos2;    //updates the pointer instance with the new position for PLAYER2
            printBoard(pos_global);                 //prints the board with newly updated pointer
            printf("Player 1: %d times   Player 2: %d times\n",rollA, rollB);

        }
            else if(input[0]==ZERO)//exit program if 0 is entered
            {
                free(pos_global); //deallocates the earlier allocated memory by calloc();
                break;
            }
            else{
                printf("Please choose a valid Player\n");
            }

        }
    }
    free(pos_global); //deallocates the earlier allocated memory by calloc() effectively terminating the program;
    return 0;
}

void printBoard(POS *ptr)
{
    //Counters
    int i,k,p;
    //position stored by digit 64; x=6 y=4;
    int x=0,y=0;
    char table[ROWS][COLS] = {0};   //initialize array table[10][10] before use
    for(i=0; i<ROWS; i++){          //for loop #1 executing 10 times from i=0 to i=9
        for(k=0; k<COLS; k++){      //for loop #2 executing 10 times from j=0 to j=9, nested within #1 to allow the whole 2d array to be
            table[i][k]=DOT;        //filled with dots (ascii 46)
                for(p=2;p<8;p++){   //fills table[][] with LADDERs
                    table[p][3]=LADDER;
                }
            table[4][9]=SNAKE;      //fills the SNAKE on the board
            table[5][8]=SNAKE;
            table[6][7]=SNAKE;
            table[7][6]=SNAKE;
            table[8][5]=SNAKE;
            table[0][0]=START_END;  //characters used in the beginning and ending of game
            table[9][9]=START_END;
           //position digit breakdown PLAYER1
           y = ptr[PLAYER1].position%COLS; //stores the 2nd digit of the position computed by applying a modulo argument to ptr[0].position (64%10=4)
           x = ptr[PLAYER1].position/COLS; //stores the 1st digit of position computed by dividing ptr[0].position by 10
           table[x][y]=PLYR_ICON_1;        //assigns PLAYER1 icon to it's new position
           //position digit breakdown PLAYER2
           y = ptr[PLAYER2].position%COLS; //equivalent to y = ptr[1].position%10
           x = ptr[PLAYER2].position/COLS; //equivalent to x = ptr[1].position/10
           table[x][y]=PLYR_ICON_2;

            printf("%c",table[i][k]);      //prints every character stored in all the array space
        }
        printf("\n");                      //inserts a new line after every row of 10 spaces
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.