2016-10-11 6 views
2

Im пытается попросить пользователя ввести y или n, и игра либо выйдет, либо продолжит. Я также хочу показать общий выигрыш и проиграть, и пользователь уйдет. Может быть, я не получаю настоящую ручку логического и возвращающегося в функции?Игра в Craps

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

int rollDice(void); 
bool playGame(void); 

int main(void) 
{ 
    srand((unsigned)(time(NULL))); 
    char userInput; 
    while (true) 
    { 
     playGame(); 
     printf("Would you like to play again?"); 
     scanf("%c", &userInput); 
     if (userInput == 'n' || userInput == 'N') 
     { 
      return false; 
     } 
     else 
     { 
      return true; 
     } 
    } 
    return 0; 
} 
int rollDice(void) 
{ 

    int dice1 = rand()%6+1; 
    int dice2 = rand()%6+1; 
    int totaldice = dice1 + dice2; 

    return totaldice; 
} 
bool playGame(void) 
{ 
    int point, total; 
    int winCounter, looseCounter; 
    printf("The game is starting!\n"); 
    total = rollDice(); 
    printf("You rolled: %d\n", total); 
    if (total == 7 || total == 11) 
    { 

     printf("Wow it's your lucky day! You Win!\n"); 
     winCounter++; 

    } 
    else if (total == 2 || total == 3 || total == 12) 
    { 
     printf("Unlucky! You Loose!\n"); 
     looseCounter++; 
    } 
    else { 
     point = total; 
     printf("Your Point is: %d\n", point); 
     while (true) 
     { 
      total = rollDice(); 
      printf("You rolled: %d\n", total); 
      if (total == point) 
      { 
       printf("You made your point! You Win!\n"); 
       winCounter++; 
       break; 
      } 
      else if (total == 7) 
      { 
       printf("Thats a %d. You Loose!\n", total); 
       looseCounter++; 
       break; 
      } 
     } 

    }return true; 
} 
+3

'зсапЕ (» % c ", & userInput);' -> 'scanf ("% c ", & userInput);' – LPs

+0

'int winCounter, looseCounter;' -> 'int winCounter = 0, looseCounter = 0;' – LPs

+0

'return true; '->' // return true; ' – LPs

ответ

0

Ваша главная проблема заключается в том, что в случае ввода пользователя что-то другое, то 'n' или 'N' вы прекратить основной с return instruction.Remove ней и цикл может продолжаться.

Лучше, если вы используете логическую переменную для выхода из цикла то время как:

int main(void) 
{ 
    srand((unsigned)(time(NULL))); 
    char userInput; 

    bool paygame = true; 

    while (paygame) 
    { 
     playGame(); 
     printf("Would you like to play again?"); 
     scanf(" %c", &userInput); 

     printf ("Test: %c\n", userInput); 
     if (userInput == 'n' || userInput == 'N') 
     { 
      paygame = false; 
     } 
    } 
    return 0; 
} 

Вторая большая проблема счетчики функции пустяки: они должны быть inited 0.

int winCounter = 0, looseCounter = 0; 

В противном случае начало отсчета от случайного числа.

Если вы хотите, чтобы посчитать все победы и россыпью всех сыгранных игр вы можете просто использовать статические ВАР:

bool playGame(void) 
{ 
    int point, total; 
    static int winCounter = 0, looseCounter = 0; 
    printf("The game is starting!\n"); 
    total = rollDice(); 
    printf("You rolled: %d\n", total); 
    if (total == 7 || total == 11) 
    { 

     printf("Wow it's your lucky day! You Win!\n"); 
     winCounter++; 

    } 
    else if (total == 2 || total == 3 || total == 12) 
    { 
     printf("Unlucky! You Loose!\n"); 
     looseCounter++; 
    } 
    else { 
     point = total; 
     printf("Your Point is: %d\n", point); 
     while (true) 
     { 
      total = rollDice(); 
      printf("You rolled: %d\n", total); 
      if (total == point) 
      { 
       printf("You made your point! You Win!\n"); 
       winCounter++; 
       break; 
      } 
      else if (total == 7) 
      { 
       printf("Thats a %d. You Loose!\n", total); 
       looseCounter++; 
       break; 
      } 
     } 

    } 

    printf ("Won: %d - Lose: %d\n", winCounter, looseCounter); 

    return true; 
} 

Последняя вещь изменить формат scanf спецификатор для " %c", чтобы scanf к «смывать» перевод строки '\n' символ слева до stdin после каждого ввода пользователем.

0

Не используйте возврат во время цикла. вместо этого используйте переменную и используйте ее для условия. Также нет необходимости, чтобы сделать это верно, так как все время, условие истинно, пока не нажата п или N

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

int rollDice(void); 
bool playGame(void); 

int main(void) 
{ 
    srand((unsigned)(time(NULL))); 
    char userInput; 
    bool again = true; 
    while (again==true) 
    { 
     printf("Would you like to play again?"); 
     scanf("%c", &userInput); 
     if (userInput == 'n' || userInput == 'N') 
     { 
      again = false; 
     } 
    } 
    return 0; 
} 
0

Если вы хотите отобразить итоговые данные после того, как пользователь завершает работу вам нужно хранить их за пределами функции playGame.

Возвращаемое значение playGame не имеет смысла в данный момент, так что давайте использовать его, чтобы указать, выиграл ли игрок:

bool playGame(void) 
{ 
    int point, total; 
    printf("The game is starting!\n"); 
    total = rollDice(); 
    printf("You rolled: %d\n", total); 
    if (total == 7 || total == 11) 
    { 
     printf("Wow it's your lucky day! You Win!\n"); 
     return true; 
    } 
    else if (total == 2 || total == 3 || total == 12) 
    { 
     printf("Unlucky! You Lose!\n"); 
     return false; 
    } 
    else 
    { 
     point = total; 
     printf("Your Point is: %d\n", point); 
     while (true) 
     { 
      total = rollDice(); 
      printf("You rolled: %d\n", total); 
      if (total == point) 
      { 
       printf("You made your point! You Win!\n"); 
       return true; 
      } 
      else if (total == 7) 
      { 
       printf("Thats a %d. You Lose!\n", total); 
       return false; 
      } 
     } 

    } 
    return false; 
} 

И небольшое переписывают main:

int main(void) 
{ 
    srand((unsigned)(time(NULL))); 
    int total = 0; 
    int wins = 0; 
    char userInput; 
    while (true) 
    { 
     total += 1; 
     if (playGame()) 
     { 
      wins += 1; 
     } 
     printf("Would you like to play again?"); 
     scanf("%c", &userInput); 
     if (userInput == 'n' || userInput == 'N') 
     { 
      break; 
     } 
    } 
    printf("Of %d games, you won %d.", total, wins); 
    return 0; 
} 
+0

Привет @molbdnilo Просто быстрый вопрос. В моем учебнике нам нужно использовать bool (void). Когда мы возвращаем false в конце функции - что мы на самом деле делаем? я не вижу разницы в возврате false или true в конце функции .... – xxFlashxx