2013-04-09 42 views
1

有人可以幫助我找出我的計劃有什麼問題,這對我來說很複雜。這是一個猜謎遊戲,兩個玩家可以玩。它首先說出哪個玩家先走,然後玩家必須輸入1或2的數字,然後輸入一個猜測或任意一個遊戲(玩家連續不得超過3次或兩次)。這是工作,只是每次玩家1點開始就要求他猜測連續兩次BU然後正常工作非常好,而當玩家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; 

} 

回答

1

首先,你應該使用一致的縮進。這會讓你更容易閱讀你的代碼。

其次,您應該使用換行符和空白將類似行組合在一起。可以考慮編寫像散文一樣的代碼,用換行符來分隔段落。幾乎所有東西都不會雙倍空間,因爲它浪費空間並且很難閱讀(人們不習慣它),因此不要使代碼雙重空間。

第三,您使用playerA和playerB變量是一個好概念,但有更好的方法可以做到這一點。 C/C++中的典型慣例是使用#define作爲幻數,並且全部大寫 - #define PLAYER_A 1。遵循這個約定將使你的代碼更具可讀性。另外,由於您的玩家是「1」和「2」,因此使用#define PLAYER1 1或PLAYER_1更具可讀性。

您使用變量「i」,但使用名稱爲i,j,k,m或n的變量的慣例是作爲在循環頂部或循環底部遞增的循環計數器。在循環中間增加循環計數器使得計數器更容易丟失。將增量移至頂部或底部。

在程序執行時手工完成工作,看看變量是什麼。你的老師在課上做了這個。只需寫下每個變量並在其旁邊寫下它的值,然後更改這些變量,因爲它們在程序執行時會發生變化。這項技術將幫助您解決未來的其他難題,而不是我給你的答案。

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"); 

    } 
+0

如果我不這樣做,它會不會循環,並再次問我我的電話號碼。 – user2133160 2013-04-09 02:45:37

+0

我正確的解決了這個問題 – user2133160 2013-04-09 04:01:32