Использование функций одна за другой или оба в int main () - PullRequest
0 голосов
/ 16 марта 2020

Итак, я получил 2 функции, и обе они в основном играют в игру с именем "Свинья игра" , а код ниже - int main () в моем коде, и он просто печатает главное и после этого запускаются функции одна за другой. Кроме того, есть еще одна функция с именем roll_a_dice () , которую вы можете игнорировать, она в основном бросает кости.

Например, в первом случае l oop play_computer начинается первым и play_user вторым. L oop повторяется 6 раз. И что мне нужно, это после каждого раунда, мне нужно получить результат (или вывести, или вернуть) функций и поместить его в другую функцию с именем scoresheets () . И я понятия не имею, как это сделать. Помогите мне, пожалуйста.

int main(void){
int roll, comp, me, round=1;
srand(time(NULL));
printf("Welcome to Big Pig game.");
printf("\nLets get started!");
comp = roll_a_dice();
printf("\nI have rolled the dice and got %d!",comp);
printf("\nShall i roll the dice for you (Y/N)? ");
scanf("%c",&roll);
if (roll=='Y'){
    me=roll_a_dice();
    printf("I have rolled the dice for you and you got %d!",me);
    if (comp>me){
        while (round<=6){
        printf("\nRound %d--My Turn: ",round);
        printf("\n===================================================================================");
        printf("%d",play_computer());
        printf("\nRound %d--Your Turn: ",round);
        printf("\n===================================================================================");
        printf("%d",play_user());
        round++;    
        }
        }
    else{
        while (round<=6){
        printf("\nRound %d--Your Turn: ",round);
        printf("\n===================================================================================");
        printf("%d",play_user());
        printf("\nRound %d--My Turn: ",round);
        printf("\n===================================================================================");
        printf("%d",play_computer());
        round++;    
        }
        }
    }
printf("%d",scoresheet());
return 0;

} ​​

1 Ответ

0 голосов
/ 18 марта 2020

Также я немного изменил твой код

//Included the header files which I assume you included in your program so that it compiles

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h> 
#include <time.h>
#include <stdlib.h>



//Declaring the functions



int scoresheet(int getOrPut,int score, int player) 
{
    //0 is put and 1 is get
    static int playerScore=0;
    static int computerScore=0;
    if(player==0 && getOrPut==0)
    {
        playerScore+=score;
        return 0;
    }
    if(player==1 && getOrPut==0)
    {
        computerScore+=score;
        return 0;
    }
    if(player==0 && getOrPut==1)
        return playerScore;
    if(player==1 && getOrPut==1)
        return computerScore;
    return -1;
}


int roll_a_dice()
{
    return (rand()%6) +1; //I assume the code looks something like this
}


int play_user(int round) //Using parameters
{

    int totalScoreOfUser=(rand()%36) + 1; //Enter code to calculate actual score here 
    scoresheet(0,totalScoreOfUser,0);//Add score to scoresheet
    return totalScoreOfUser;
}


int play_computer() //Without passing parameters
{
    static int round=0; //Declares a variable static to the function
    round++;//Increases value of variable each time function is called
    int totalScoreOfComputer=(rand()%36) + 1; 
    scoresheet(0,totalScoreOfComputer,1);//Add score to scoresheet
    return totalScoreOfComputer; 
}




int main(void)
{
    int comp, me, round=1;
    char roll; //changed type of roll from int to char as you were scanning input as %c
    srand(time(NULL));
    printf("Welcome to Big Pig game.");
    printf("\nLets get started!");
    comp = roll_a_dice();
    printf("\nI have rolled the dice and got %d!",comp);
    printf("\nShall I roll the dice for you (Y/N)? "); //Fixed grammar changing i to I in string
    scanf(" %c",&roll); //Added a blank space before %c to remove whitespace errors during run time

    while(roll!='Y' && roll!='y' && roll!='N' && roll!='n') //Added some extra code so that user will always input either y or n
    {
        printf("\nInvalid Input. Please enter either (Y/N)\n");
        scanf(" %c",&roll);
    }

    if (roll=='Y' || roll=='y'){ //Most people don't usually press shift while typing so included the lower case y in your code
            me=roll_a_dice();
            printf("I have rolled the dice for you and you got %d!",me);
            if (comp>me){ //When computer has rolled a higher number, it goes first
                while (round<=6){
                //I reordered and combined a few print statements so the code looks shorter
                    printf("\nRound %d--My Turn: ",round);
                    printf("%d",play_computer());
                    printf("\n===================================================================================");
                    printf("\nRound %d--Your Turn: ",round);

                    printf("%d",play_user(round));
                printf("\n===================================================================================");        
                round++;    
                }
            }
        else{ //When user has rolled higher or both rolled equal, user goes first
                while (round<=6){
                //I reordered and combined a few print statements so the code looks shorter
                printf("\nRound %d--Your Turn: %d",round,play_user(round));
                printf("\n===================================================================================");        

                printf("\nRound %d--My Turn: %d",round,play_computer());        
                printf("\n===================================================================================");   
                    round++;    
                }
            }
        printf("\nTotal Scores are Computer: %d and User: %d\n",scoresheet(1,0,1),scoresheet(1,0,0));

        }

    else
    {
        printf("You chose not to roll the die and hence the game did not begin\n");
    }

    return 0;
}
...