Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Help me troubleshoot my 1st C projekt :)

Go to solution Solved by Mojo-Jojo,

 

@ Thanks to you and a short Lynda lesson about pointers, the program now works! All that is left is to add the rest of the game (pairs, 2 pairs, yatzy etc...)!

 

Feel free to come with criticism on the code and suggest changes that would make it "nicer" code.

-code snip-

 

Great to hear :)

 

Now that you've applied these changes, your code looks a lot better and is much easier to read. Looking good  :D

Hi!

 

I have just started to learn programming in C. I'm using Code Blocks and gcc compiler (std C99).

Just for exercise I have started to make a Yatzy game running in Windows cmd and I have hit a problem that i cant seam to fix. Can you please help me? :)

 

I have narrowed it down a bit and it seams that the problem lies in the function printfield(). It doesn't save the score of the players correct.

 

If, say for example player one gets 3 ones. Then he should get 3x1 point in the appropriate location of course, but instead I get something like this:

 

Players:        P1
Ones            2686584
Twos            2686692
Threes          2686696
Fours           2686700
Fives            0
Sixes            0
------------------
Sum:            10746672
 
pic:
o40An2Z.jpg
 
 
This is how it should look:
 

Players:        P1
Ones            3
Twos            0
Threes         0
Fours           0
Fives            0
Sixes            0
------------------
Sum:            3
 
Here is the code:
 

#include <stdio.h>#include <stdlib.h>#include <time.h>int players;char *numbers[6] = {"Ones","Twos","Threes","Fours","Fives","Sixes"};void printfield(int field[6][players]);int main(){    int run = 1;    int dize[5];    int keep[5];    int temp;    srand(time(0));/*Program starts and the number of players are selected*/    printf("Hi and welcome to Yatzy a la Glaa:D. How many players want to play?\n");    scanf("%d", &players);    while(run == 1)    {       if (players<5 && players>0)       {        run = 0;       }       else       {        system("cls");        printf("The number of players needs to be between 1 and 4. So I'll ask again, how many?\n");        scanf("%d", &players);       }    }//Asks the player what dize he wants to save/* Creates the play field*/    int field[6][players];    for (int i=0;i<6;i++)//Fills the play field with zeros    {        for (int j=0;j<players;j++)        {            field[i][j] = 0;        }    }    printfield(field);    run = 1;/*Game starts*/    while (run == 1)    {        for (int i=0;i<6;i++)//Runs 6 times for the 6 different dize        {            if (i>0) Sleep(2000);            for (int j=0;j<players;j++)//Runs as many times as there are players            {                printfield(field);                printf("This round you want to collect as many %s as possible\n", numbers[i]);                Sleep(1000);                printf("Player %d, it is your turn.\n", j+1);                Sleep(1000);                for (int asd=0;asd<5;asd++)//Puts the dize to reroll                {                    keep[asd] = 0;                }                for (int k=0;k<3;k++)//Runs three times, ones per time you roll the dize                {                    printf("Your dice: ");                    for (int l=0;l<5;l++)//Runs 5 times, one per dize                    {                        if (keep[l]==0)//Rolls the dize if it is not to be saved                        {                            dize[l] = rand()%6+1;                        }                        printf("%d ", dize[l]);//Prints the dize                    }                    printf("\n");                    Sleep(1000);                    if (k<2)//Asks the player what dize he wants to save                    {                        printf("What dizes do you want to keep? Type 1 for save and 0 for reroll (Type:'1 0 0 1 0' if you want to save dize 1 and 4 for example)\n");                        scanf("%d %d %d %d %d", &keep[0], &keep[1], &keep[2], &keep[3], &keep[4]);                    }                }                temp = 0;                for (int a=0;a<5;a++)//Checks how many of the desired dize there is                {                 if (dize[a]==(i+1))                 {                     //field[i][j] = field[i][j] + dize[a];//calculates the players point                     temp = temp + (i + 1);                 }                 //printf("Points: %d", temp);                }                //printf("Points: %d", temp);                field[i][j] = temp;                //printf("Points: %d", field[i][j]);                //Sleep(5000);                printf("%d",field[i][j]);            }        }    }    return 0;}void printfield(int field[6][players]){    system("cls"); //clears the cmd window of any text    printf("Players:\t");    for (int i=1;i<=players;i++) //The players are printed    {        printf("P%d\t",i);    }    printf("\n");    for (int i=0;i<6;i++) //The dize and the players points/dize are printed    {        printf("%s\t\t",numbers[i]);        for (int j=0;j<players;j++)        {            printf("%2d\t",field[i][j]);        }        printf("\n");    }    int sum[players];    for (int i=0;i<players;i++)    {        sum[i] = 0;//sets the sum to zero    }    for (int i=0;i<players;i++)//Calculates the sum of all the players    {        for (int j=0;j<6;j++)        {            sum[i] = sum[i]+field[j][i];        }    }    if (players==1){//Prints a line based on the number of players        printf("------------------\n");    }else if(players==2){        printf("--------------------------\n");    }else if(players==3){        printf("----------------------------------\n");    }else if(players==4){        printf("------------------------------------------\n");    }    printf("Sum:\t\t");//Prints the players sums    for (int i=0;i<players;i++)    {        printf("%2d\t", sum[i]);    }    printf("\n");}

Thanks in advance!

 

// gurraglaa

Chassi: FD R4 window CPU: 3570k @4.5GHz GPU: ASUS 970 Strix @ 1450/7000 MHz PSU: FD Integra 500w

Mobo: Asus Sabertooth Z77 RAM: 2x4 Corsair Vengence 1600MHz SSDs: 2x Kingston 120GB RAID 0 (OS), Samsung 840 120GB (Steam) CPU fan: Noctua U12P Case fans: 3x140mm FD R2

Link to post
Share on other sites

I tried to debug it but I cannot find any problems, but I did need to rewrite parts to not use variable length arrays, so your problem may be there. Can you try running this version of the code.\

#include <stdio.h>#include <stdlib.h>#include <time.h>int players;char *numbers[6] = { "Ones", "Twos", "Threes", "Fours", "Fives", "Sixes" };void printfield(int *field[6]);int main() {	int run = 1;	int dize[5];	int keep[5];	int temp;	srand(time(0));	/*Program starts and the number of players are selected*/	printf("Hi and welcome to Yatzy a la Glaa:D. How many players want to play?\n");	scanf("%d", &players);	while (run == 1) {		if (players<5 && players>0) {			run = 0;		} else {			system("cls");			printf("The number of players needs to be between 1 and 4. So I'll ask again, how many?\n");			scanf("%d", &players);		}	}//Asks the player what dize he wants to save	/* Creates the play field*/	int *field[6];	for (int i = 0; i<6; i++)//Fills the play field with zeros	{		field[i] = malloc(sizeof(int) * players);		for (int j = 0; j<players; j++) {			field[i][j] = 0;		}	}	printfield(field);	run = 1;	/*Game starts*/	while (run == 1) {		for (int i = 0; i<6; i++)//Runs 6 times for the 6 different dize		{			if (i>0) Sleep(2000);			for (int j = 0; j<players; j++)//Runs as many times as there are players			{				printfield(field);				printf("This round you want to collect as many %s as possible\n", numbers[i]);				Sleep(1000);				printf("Player %d, it is your turn.\n", j + 1);				Sleep(1000);				for (int asd = 0; asd<5; asd++)//Puts the dize to reroll				{					keep[asd] = 0;				}				for (int k = 0; k<3; k++)//Runs three times, ones per time you roll the dize				{					printf("Your dice: ");					for (int l = 0; l<5; l++)//Runs 5 times, one per dize					{						if (keep[l] == 0)//Rolls the dize if it is not to be saved						{							dize[l] = rand() % 6 + 1;						}						printf("%d ", dize[l]);//Prints the dize					}					printf("\n");					Sleep(1000);					if (k<2)//Asks the player what dize he wants to save					{						printf("What dizes do you want to keep? Type 1 for save and 0 for reroll (Type:'1 0 0 1 0' if you want to save dize 1 and 4 for example)\n");						scanf("%d %d %d %d %d", &keep[0], &keep[1], &keep[2], &keep[3], &keep[4]);					}				}				temp = 0;				for (int a = 0; a<5; a++)//Checks how many of the desired dize there is				{					if (dize[a] == (i + 1)) {						//field[i][j] = field[i][j] + dize[a];//calculates the players point						temp = temp + (i + 1);					}					//printf("Points: %d", temp);				}				//printf("Points: %d", temp);				field[i][j] = temp;				//printf("Points: %d", field[i][j]);				//Sleep(5000);				printf("%d", field[i][j]);			}		}	}	return 0;}void printfield(int *field[6]) {	system("cls"); //clears the cmd window of any text	printf("Players:\t");	for (int i = 1; i <= players; i++) //The players are printed	{		printf("P%d\t", i);	}	printf("\n");	for (int i = 0; i<6; i++) //The dize and the players points/dize are printed	{		printf("%s\t\t", numbers[i]);		for (int j = 0; j<players; j++) {			printf("%2d\t", field[i][j]);		}		printf("\n");	}	int *sum = malloc(sizeof(int) * players);	for (int i = 0; i<players; i++) {		sum[i] = 0;//sets the sum to zero	}	for (int i = 0; i<players; i++)//Calculates the sum of all the players	{		for (int j = 0; j<6; j++) {			sum[i] = sum[i] + field[j][i];		}	}	if (players == 1) {//Prints a line based on the number of players		printf("------------------\n");	} else if (players == 2) {		printf("--------------------------\n");	} else if (players == 3) {		printf("----------------------------------\n");	} else if (players == 4) {		printf("------------------------------------------\n");	}	printf("Sum:\t\t");//Prints the players sums	for (int i = 0; i<players; i++) {		printf("%2d\t", sum[i]);	}	printf("\n");}
Link to post
Share on other sites

 

I tried to debug it but I cannot find any problems, but I did need to rewrite parts to not use variable length arrays, so your problem may be there. Can you try running this version of the code.\

/* Creates the play field*/  int *field[6];    for (int i = 0; i<6; i++)//Fills the play field with zeros    {        field[i] = malloc(sizeof(int) * players);        for (int j = 0; j<players; j++) {            field[i][j] = 0;        }    }    printfield(field);
 
  

 

I can't seam to get your code to work at all. It gets stuck at the first dize roll. i will take a closer look tomorrow and see if i can fix it. In the meantime, could you please explain how the code above works? I am not that familiar with pointers. In my mind, that code creates a 1 dim array.

Chassi: FD R4 window CPU: 3570k @4.5GHz GPU: ASUS 970 Strix @ 1450/7000 MHz PSU: FD Integra 500w

Mobo: Asus Sabertooth Z77 RAM: 2x4 Corsair Vengence 1600MHz SSDs: 2x Kingston 120GB RAID 0 (OS), Samsung 840 120GB (Steam) CPU fan: Noctua U12P Case fans: 3x140mm FD R2

Link to post
Share on other sites

@gurraglaa There are multiple problems with your code. I'll be listing them here.

This is to give you some pointers in the right direction. I may seem harsh, but that doesn't mean I think you're doing a bad job - I simply want to help  :)

 

  • You haven't #include'd the header for Sleep(). You're implicitly linking the "sleep" functionality. Solve by adding this bit of code at the top:
    • #ifdef _WIN32    #include <Windows.h>#else    #include <unistd.h>#endif
  • There is no input validation for your Inputs
  • Creating an array with a dimension size determined by an integer on runtime is not endorsed practice. Especially without proper input validation.
  • Some of your variables have improper names. I see "asd" and "field" for example. It's good practice to always show what type your variable is. For example
    • char cChoice;int iResult;char * acUsername;int aiIndexes[10];

Those are just some starting points.

 

By the way, really, see my first point about Sleep(). I think you'll find your issues resolved.  ;) 

Always sort out any compiler warnings you get ASAP! They cause undefined and strange behaviour.

Link to post
Share on other sites

@gurraglaa Hey there! Just checking up, did you manage to get the project working with the help above? I'd be happy to help if not.

Link to post
Share on other sites

@gurraglaa Hey there! Just checking up, did you manage to get the project working with the help above? I'd be happy to help if not.

Hi! I Have not had the time to sit down and code yet. Have too much to do in school. But I think I will take a look tonight.

Anyway, thanks a lot for the help. Will make a post when I'm done/when I get stuck again.

Chassi: FD R4 window CPU: 3570k @4.5GHz GPU: ASUS 970 Strix @ 1450/7000 MHz PSU: FD Integra 500w

Mobo: Asus Sabertooth Z77 RAM: 2x4 Corsair Vengence 1600MHz SSDs: 2x Kingston 120GB RAID 0 (OS), Samsung 840 120GB (Steam) CPU fan: Noctua U12P Case fans: 3x140mm FD R2

Link to post
Share on other sites

@ Thanks to you and a short Lynda lesson about pointers, the program now works! All that is left is to add the rest of the game (pairs, 2 pairs, yatzy etc...)!

 

Feel free to come with criticism on the code and suggest changes that would make it "nicer" code.

#include <stdio.h>#include <stdlib.h>#include <time.h>#ifdef _WIN32    #include <Windows.h>#else    #include <unistd.h>#endifint iPlayers;char *asNumbers[6] = {"Ones","Twos","Threes","Fours","Fives","Sixes"};void printfield(int *aiField[6], int *aiSum);int main(){    int iRun = 1;    int aiDice[5];    int aiKeep[5];    int iTemp;    srand(time(0));/*Program starts and the number of players are selected*/    printf("Hi and welcome to Yatzy a la Glaa:D. How many players want to play?\n");    scanf("%d", &iPlayers);    while(iRun == 1)    {       if (iPlayers<5 && iPlayers>0)       {        iRun = 0;       }       else       {        system("cls");        printf("The number of players needs to be between 1 and 4. So I'll ask again, how many?\n");        scanf("%d", &iPlayers);       }    }/*Declares some necessary arrays*/    int *aiField[6];	int *aiSum = malloc(sizeof(int) * iPlayers);    iRun = 1;/*Game starts*/    while (iRun == 1)    {        /* Creates the play field*/        int *aiField[6];        for (int i = 0; i<6; i++)//Fills the play field with zeros        {            aiField[i] = malloc(sizeof(int) * iPlayers);            for (int j = 0; j<iPlayers; j++) {                aiField[i][j] = 0;            }        }        for (int i=0;i<6;i++)//Runs 6 times for the 6 different Dice        {            if (i>0) Sleep(2000);            for (int j=0;j<iPlayers;j++)//Runs as many times as there are players            {                printfield(aiField, aiSum);                printf("This round you want to collect as many %s as possible\n", asNumbers[i]);                Sleep(1000);                printf("Player %d, it is your turn.\n", j+1);                Sleep(1000);                for (int asd=0;asd<5;asd++)//Puts the Dice to reroll                {                    aiKeep[asd] = 0;                }                for (int k=0;k<3;k++)//Runs three times, ones per time you roll the Dice                {                    printf("Your dice: ");                    for (int l=0;l<5;l++)//Runs 5 times, one per Dice                    {                        if (aiKeep[l]==0)//Rolls the Dice if it is not to be saved                        {                            aiDice[l] = rand()%6+1;                        }                        printf("%d ", aiDice[l]);//Prints the Dice                    }                    printf("\n");                    Sleep(1000);                    if (k<2)//Asks the player what Dice he wants to save                    {                        printf("What Dice do you want to keep?");                        if (i = 0)                        {                            printf("Type 1 to save and 0 to reroll (Ex: '1 0 0 1 0' saves Dice 1 and 4)\n");                        } else                        {                            printf("\n");                        }                        scanf("%d %d %d %d %d", &aiKeep[0], &aiKeep[1], &aiKeep[2], &aiKeep[3], &aiKeep[4]);                    }                }                iTemp = 0;                for (int a=0;a<5;a++)//Checks how many of the desired Dice there is                {                 if (aiDice[a]==(i+1))                 {                     iTemp = iTemp + (i + 1);                 }                }                aiField[i][j] = iTemp;                //printf("%d",aiField[i][j]);            }        }/*Checks who is the winner*/        system("cls");        printfield(aiField, aiSum); //prints the final play field        int *aiResults[2];        for (int i=0;i<2;i++)//Creates an array to store the results in and calculate who the winner is        {            aiResults[i] = malloc(sizeof(iPlayers) / sizeof(int));        }        for (int i=0;i<iPlayers;i++)//Fills the array with the results        {                aiResults[0][i] = (i+1);                aiResults[1][i] = aiSum[i];        }        int c, d, t;        for (c = 0 ; c < ( iPlayers - 1 ); c++)//Sorting the results        {            for (d = 0 ; d < iPlayers - c - 1; d++)            {                if (aiResults[1][d] < aiResults[1][d+1])                {                /* Swapping */                    t = aiResults[1][d];                    aiResults[1][d]   = aiResults[1][d+1];                    aiResults[1][d+1] = t;                    t = aiResults[0][d];                    aiResults[0][d]   = aiResults[0][d+1];                    aiResults[0][d+1] = t;                }            }        }/*Displaying the results and asks if the player(s) want to play again*/        printf("The results:\n");        for (int i=0;i<iPlayers;i++)        {            printf("%d place: Player %d with %d points\n", (i+1), aiResults[0][i], aiResults[1][i]);        }        printf("\n");        printf("Would you like to play again? 1=YES, 0=NO\n");        scanf("%d", &iRun);    }    return 0;}void printfield(int *aiField[6], int *aiSum){    system("cls"); //clears the cmd window of any text    printf("Players:\t");    for (int i=1;i<=iPlayers;i++) //The players are printed    {        printf("P%d\t",i);    }    printf("\n");    for (int i=0;i<6;i++) //The Dice and the players points/Dice are printed    {        printf("%s\t\t",asNumbers[i]);        for (int j=0;j<iPlayers;j++)        {            printf("%2d\t",aiField[i][j]);        }        printf("\n");    }    for (int i=0;i<iPlayers;i++)    {        aiSum[i] = 0;//sets the Sum to zero    }    for (int i=0;i<iPlayers;i++)//Calculates the sum of all the players    {        for (int j=0;j<6;j++)        {            aiSum[i] = aiSum[i]+aiField[j][i];        }    }    if (iPlayers==1){//Prints a line based on the number of players        printf("------------------\n");    }else if(iPlayers==2){        printf("--------------------------\n");    }else if(iPlayers==3){        printf("----------------------------------\n");    }else if(iPlayers==4){        printf("------------------------------------------\n");    }    printf("aiSum:\t\t");//Prints the players sums    for (int i=0;i<iPlayers;i++)    {        printf("%2d\t", aiSum[i]);    }    printf("\n");} 

Chassi: FD R4 window CPU: 3570k @4.5GHz GPU: ASUS 970 Strix @ 1450/7000 MHz PSU: FD Integra 500w

Mobo: Asus Sabertooth Z77 RAM: 2x4 Corsair Vengence 1600MHz SSDs: 2x Kingston 120GB RAID 0 (OS), Samsung 840 120GB (Steam) CPU fan: Noctua U12P Case fans: 3x140mm FD R2

Link to post
Share on other sites

 

@ Thanks to you and a short Lynda lesson about pointers, the program now works! All that is left is to add the rest of the game (pairs, 2 pairs, yatzy etc...)!

 

Feel free to come with criticism on the code and suggest changes that would make it "nicer" code.

-code snip-

 

Great to hear :)

 

Now that you've applied these changes, your code looks a lot better and is much easier to read. Looking good  :D

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×