A Console based turn based dice rolling game. The player with highest number on dice wins. If both have same dice then the game draws.
CODE:
#include<stdio.h> #include<time.h> #include<stdbool.h> #define TOTAL_PLAYERS 2 int rollDices(int sides); int tossCoin(); void exitMessage(); void invalidOp(); void playerDiceOptions(int tc, int sides); struct player { char name[100]; bool played; int dice; } p[TOTAL_PLAYERS]; int main() { int sides = 6; char tcAgree = '\0'; for(int i=0; i<TOTAL_PLAYERS; i++) { printf("Enter Player %d name:\n", i+1); scanf("%s", &p[i].name); } int tc = tossCoin(); printf("Toss COIN: (Y/N)?\n"); getchar(); tcAgree = getchar(); printf("\n"); if(tcAgree - 'y'==0|| tcAgree - 'Y'==0) { printf("Player %d \"%s\" will play first\n", tc+1, p[tc].name); p[tc].played = true; } else if(tcAgree - 'n'==0 || tcAgree - 'N'==0) { exitMessage(); return 0; } else { invalidOp(); return 0; } playerDiceOptions(tc, sides); //invert the player if(tc==0) tc=1; else tc=0; printf("\n"); for(int i=0; i<TOTAL_PLAYERS; i++) { if(!p[i].played) { printf("Player %d \"%s\" will play\n", i+1, p[i].name); playerDiceOptions(tc, sides); } } printf("\n"); Sleep(2000); int k=0; if(p[k].dice>p[k+1].dice) printf("Player %d \"%s\" wins\n", k+1, p[k].name); else if(p[k].dice<p[k+1].dice) printf("Player %d \"%s\" wins\n", (k+1)+1, p[k+1].name); else printf("the game is a draw\n"); return 0; } int rollDices(int sides) { int dice1 = rand() % sides + 1; return dice1; } int tossCoin() { srand(time(NULL)); return rand() % 2; } void exitMessage() { printf("Exiting....."); Sleep(2000); } void invalidOp() { printf("Invalid Operation\n"); } void playerDiceOptions(int tc, int sides) { char rollAgree = '\0'; printf("Roll dice: (Y/N)\n"); getchar(); rollAgree = getchar(); if(rollAgree - 'y'==0|| rollAgree - 'Y'==0) { p[tc].dice = rollDices(sides); printf("Player %d \"%s\" got on dice: %d\n", tc+1, p[tc].name, p[tc].dice); } else if(rollAgree - 'n'==0 || rollAgree - 'N'==0) { printf("I get it you don't want to play\n"); exitMessage(); return 0; } else { printf("Invalid operation\n"); return 0; } }