c - Number Guessing Game with two players -
can please me figure out wrong program prety complex me. number guessing game 2 player can play. starts saying player goes first , player has input number either 1 or 2 , enter guess or either pass (players can't pass more 3 times or twice in row). working except everytime player 1 starts asks him guess twice in row bu works fine, , when player 2 starts alternates should this:
and code quite 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 = 1; int playerturn = 0; int turn = 0; srand(time(null)); playernumber = 1 + rand() % 2; /* random number generated */ srand(time(null)); number = 0 + rand() % 100; /* random number 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 wait turn.\nplayer number?\n"); } if (playera != playernumber) playerb = playernumber; if (i%2 == 1) { playernumber = playera; } else { playernumber = playerb; } = i+1; printf("enter 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 guess lower, output: guess low */ printf("your guess low.\n "); else if(guess > number) /* if guess higher, output: guess high */ printf("your guess high.\n "); else /* guess equial random number: success!! */ printf("yes!! got it!\n"); } } return 0; }
first of all, should use consistent indentation. make easier read code.
second, should use newlines , whitespace group like-lines together. think of writing code writing prose, , newlines ways separate paragraphs. don't double-space anything, because wastes space , harder read (people aren't used it) don't double-space code.
third, use of playera , playerb variables ok concept, there better ways it. typical convention in c/c++ use #define magic numbers, caps - #define player_a 1
. following convention make code more readable. also, since players "1" , "2" more readable use #define player1 1
or player_1.
you use variable "i" convention using variables named i, j, k, m, or n loop counters incremented either @ top of loop or @ bottom of loop. incrementing loop counter in middle of loop makes easier counter lost. move increment top or bottom.
do work hand see variables program executes. teacher has done in class. write down each variable , write value next it, change variables change while program executes. technique fix other difficult bugs in future, rather me giving answer.
Comments
Post a Comment