数字猜测游戏与两名球员

时间:2013-04-09 02:24:52

标签: c

有人可以帮我弄清楚我的程序出了什么问题,这对我来说很复杂。这是一个数字猜谜游戏,两个玩家可以玩。首先说明哪个玩家先行,然后玩家必须输入他或者1或2的数字,然后输入猜测或者通过(玩家连续不能超过3次或两次)。它工作得非常好,除非每次玩家1开始它要求他连续两次猜测然后工作正常,当玩家2开始时它会像它应该这样交替:

Here is when player 2 goes first it works fine

Here it is when player 1 goes first and it reapeats only once

And this is my code It quite a lot of code:

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

int main(void) { 

int playerNumber = 0;
int number = 0;
int playerInput = 0;    
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;

 srand(time(NULL));
 playerNumber = 1 + rand() % 2; /* Random number is generated */

 srand(time(NULL));
 number = 0 + rand() % 100; /* Random number is generated */


  while(number != guess) {

   printf("\nIt's player's %d turn\n", playerNumber);

  printf("Player Number?\n");

  scanf("%d", &playerInput);

  while (playerNumber != playerInput)
   {

printf("You Have to wait your turn.\nPlayer number?\n");

  }

  if (playerA != playerNumber)
playerB = playerNumber;

if (i%2 == 1) {
    playerNumber = playerA;
    }
else {
    playerNumber = playerB;
    }

i = i+1;

    printf("Enter Your Guess, 0 - 100 or Pass: ");

scanf("%s", str);


if (strcmp(str, "pass") == 0){
    if (playerNumber == playerA){
        passB = passB -1;
        printf("Player 2 has %d more 'Pass' left!\n", passB);
        }   
    else{
        passA = passA -1;
        printf("Player 1 has %d more 'Pass' left!\n", passA);
        }
    }   
else {
    guess = atoi(str);
        if(guess < number) /* if the guess is lower, output: the guess is to low */
            printf("Your guess was to low.\n ");

        else if(guess > number) /* if the guess is higher, output: the guess is to high */
            printf("Your guess was to high.\n ");

        else /* is the guess is equial to the random number: Success!! */
            printf("Yes!! you got it!\n");

         }

 }
  return 0;

}

2 个答案:

答案 0 :(得分:1)

首先,您应该使用一致的缩进。这样可以更轻松地阅读您的代码。

其次,你应该使用换行符和空格来将相似的行组合在一起。考虑编写像写散文的代码,以及新行作为分隔段落的方法。几乎没有任何东西的双重空间,因为它浪费空间并且更难阅读(人们不习惯它)所以不要对代码进行双重空间化。

第三,你使用playerA和playerB变量是一个好的概念,但有更好的方法来做到这一点。 C / C ++中的典型惯例是将#define用于幻数,并使用全部大写 - #define PLAYER_A 1。遵循此约定将使您的代码更具可读性。此外,由于您的播放器为“1”和“2”,因此使用 #define PLAYER1 1或PLAYER_1更具可读性。

使用变量“i”,但使用名为i,j,k,m或n的变量的约定是循环计数器,它在循环的顶部或循环的底部递增。在循环中间增加循环计数器使计数器更容易丢失。将增量移动到顶部或底部。

手工完成工作,看看程序执行时的变量。你的老师在课堂上做了这个。只需记下每个变量并在其旁边写下它的值,然后在程序执行时更改变量。这项技术将帮助你解决未来的其他困难,而不是我给你答案。

答案 1 :(得分:0)

你的代码中有一个无限循环,

下面给出的代码是错误的,

   while(playerNumber != playerInput)
   {

       printf("You Have to wait your turn.\nPlayer number?\n");

   }

应该是,

   if(playerNumber != playerInput)
   {

       printf("You Have to wait your turn.\nPlayer number?\n");

   }