C语言 粘在纸上-剪刀-石头游戏

7y4bm7vi  于 2023-02-15  发布在  其他
关注(0)|答案(3)|浏览(146)

While循环每次迭代两次,CPU只在选择“S”作为剪刀时得分。另一个问题是,我如何使它更好,我在哪里添加该函数?我必须使用字符“r”,“s”和“p”,而不是1,2,3来接受用户输入。不知道如何继续修复这个问题

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

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R': 
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```
mv1qrgav

mv1qrgav1#

我建议你把它变得简单一些。石头剪刀布的赢家可以用算术来决定。
比较同类比较更简单,使用整数值可以实现更简单的算术解决方案,而且从算术上讲,使用0,1,2比使用1,2,3更简单,因此,首先将用户输入转换为0,1,2:

#define INVALID_SELECTION sizeof(rps)
static const char rps[] = {'r', 'p', 's'} ;
int human = INVALID_SELECTION ;

while( human == INVALID_SELECTION )
{
    printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");

    char ch = 0 ;
    scanf("%c", &ch ) ;
    while( ch != '\n' && getchar() != '\n' ) ;

    for( human = 0; 
         human < INVALID_SELECTION && tolower(ch) != rps[human] ; 
         human++ )
    {
        // do nothing
    }
}

然后,计算机游戏应确定如下:

srand( (int)time(NULL) ) ;
int computer = rand() % 3 ;

不过请注意,您只需要调用srand()一次,因此如果您将游戏放入循环中以重复播放,srand()调用应该出现在repeat循环 * 之前 *。
然后,您可以按以下方式报告该播放:

static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
printf( "Human played %s\n", play_lookup[human] ) ;
printf( "Computer played %s\n", play_lookup[computer] ) ;

humancomputer是直接的和算术上可比较的,使得:

int battle = human - computer ;
if( battle < 0 ) battle += 3 ;
switch( battle )
{
    case 0 : printf( "Draw!\n" ) ; break ;
    case 1 : printf( "Human wins!\n" ) ; break ;
    case 2 : printf( "Computer wins!\n" ) ; break ;
}

或(记入@HAL9000):

int battle = ((human - computer) + 3) % 3 ;
switch( battle )
...

把所有这些放在一起:

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

int main()
{
    // Randomize
    srand( (int)time(NULL) ) ;
    
    // Repeat play indefinitely
    for(;;)
    {
        #define INVALID_SELECTION sizeof(rps)
        static const char rps[] = {'r', 'p', 's'} ;
        int human = INVALID_SELECTION ;
        
        // While human input is not one of R,P,S,r,p or s...
        while( human == INVALID_SELECTION )
        {
            printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");
        
            char ch = 0 ;
            scanf("%c", &ch ) ;
            while( ch != '\n' && getchar() != '\n' ) ;
        
            // Transform input to one of 0,1,2 (for R,P,S respectively)
            for( human = 0; 
                 human < INVALID_SELECTION && tolower(ch) != rps[human] ; 
                 human++ )
            {
                // do nothing
            }
        }

        // Get computer's play    
        int computer = rand() % 3 ;
    
        // Report human and computer plays in full text
        static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
        printf( "Human played %s\n", play_lookup[human] ) ;
        printf( "Computer played %s\n", play_lookup[computer] ) ;
    
        // Calculate and report result
        int battle = ((human - computer) + 3) % 3 ;
        switch( battle )
        {
            case 0 : printf( "Draw!\n" ) ; break ;
            case 1 : printf( "Human wins!\n" ) ; break ;
            case 2 : printf( "Computer wins!\n" ) ; break ;
        }
    }
    
    return 0;
}

输出示例:

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Paper
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Scissors
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Rock
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Rock
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: R
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: P
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: S
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: xx

Enter R for Rock, P for Paper, or S for Scissors: yy

Enter R for Rock, P for Paper, or S for Scissors: zz

Enter R for Rock, P for Paper, or S for Scissors:
pgpifvop

pgpifvop2#

试试这个:

#include <stdio.h>
#include <stdlib.h> 
int main () {
   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   srand ((int) time (NULL));
   int count = 0;
   while(count != 10) {
       printf("Enter p for Paper, r for rock, or S for scissor:\n");
       fgets(&player1, 80, stdin);
       player2 = rand ( ) % 4;
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!\n");
       }if(player1 == 'P' && player2 == 2) {
        userScore++;
        printf("User won this one!\n");
       }if(player1 == 'P' && player2 == 3){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'R' && player2 == 2) {
         printf("Draw!\n");
       }if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'R' && player2 == 1){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'S' && player2 == 3) {
         printf("Draw!\n");
       }if(player1 == 'S' && player2 == 1) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'S' && player2 == 2){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1!='S' || player1!='R' || player1!='P'){
         printf("Invalid Input\n");
       }
    printf("User Score: %d\n", userScore);
    printf("CPU Score: %d\n", cpuScore);
    count++;
}
   if(userScore == cpuScore) {
     printf("Draw game!\n");
   } else if(userScore > cpuScore) {
     printf("You win!\n");
   } else {
     printf("CPU wins!\n");
   }
   return 0;
}

我还应该补充一点,这个程序是敏感的。例如,输入"r"将不起作用,但"r"将起作用。请酌情更改此设置。

wydwbb8l

wydwbb8l3#

问题是您在循环外设置了player2,而没有更新它;它总是相同的。这可能是一个典型的情况,不需要通过toupper将其转换为中间值,直接将其转换为enum将是合适的。不需要用if转换switch,这将问题空间缩小到3个值,这很容易适合查找表。

#include <stdlib.h>
#include <stdio.h> /* `printf` requires this. */
#include <time.h>

/* https://en.wikipedia.org/wiki/X_Macro just because I don't want to type. */
#define CHOICE(X)  X(ROCK), X(PAPER), X(SCISSORS)
#define OUTCOME(X) X(LOSS), X(TIE), X(WIN)
#define NAME(A) A
#define STR(A) #A
enum Choice { CHOICE(NAME) };
static const char *const choice_names[] = { CHOICE(STR) };
enum Outcome { OUTCOME(NAME) };
static const char *const outcome_names[] = { OUTCOME(STR) };
static enum Outcome choice_outcomes[][3] = {
    { TIE, LOSS,  WIN },
    { WIN,  TIE, LOSS },
    { LOSS, WIN,  TIE }
};

int main(void) { /* <- `void` should be used to prototype. */
    char input;
    enum Choice player1, player2;
    int score[] = { 0, 0, 0 }; /* <- Replace `cpuScore` and `userScore`. */
    int count = 0;

    srand ((int) time (NULL)); /* <- `srand` should precede `rand`. */

    while(count <= 10) {
        printf("\nEnter p for Paper, r for rock, or S for scissor: ");
        /* Ignores whitespace, (_viz_ enter); breaks on error, (_eg_ EOF.) */
        if(scanf(" %c", &input) != 1) break;
        /* Convert it to `player1` immediately. */
        switch(input) {
        case 'r': case 'R':
            player1 = ROCK; break;
        case 'p': case 'P':
            player1 = PAPER; break;
        case 's': case 'S':
            player1 = SCISSORS; break;
        default:
            printf("Unexpected input, '%c'.\n", input); continue;
        }
        player2 = rand() % 3;
        printf("User choses %s _vs_ Cpu choses %s: %s.\n",
            choice_names[player1], choice_names[player2],
            outcome_names[choice_outcomes[player1][player2]]);
        score[choice_outcomes[player1][player2]]++;
        printf("User Score: %d\n", score[WIN]);
        printf("CPU Score: %d\n", score[LOSS]);
        printf("Ties: %d\n", score[TIE]);
        count++;
    }
    /* One of the places was the `scanf` break, so check, (unlikely.) */
    if(ferror(stdin)) { perror("stdin"); return 1; }

    /* Print the winner. */
    if(score[WIN] == score[LOSS]) {
        printf("Draw game!\n");
    } else if(score[WIN] > score[LOSS]) {
        printf("You win!\n");
    } else {
        printf("CPU wins!\n");
    }
    return 0;
}

我还将userScorecpuScore放入以enum Outcome为索引的数组中。

相关问题