arrays - Stop Tic Tac Toe from overwriting moves in C -
sorry guys asked question couple of hours ago last thing need finish project. program allows overwrite of moves. if player 1 picks first square, allow player 2 pick square. else functions have been failing @ implementation of this.
any ideas? put 1 part of code since lot of code sadly copy , pasted. i'm new, haven't figured out optimization yet , out of time project appreciated.
so in code included printing of original board , first move of first player (if playing 2 humans). should enough if wants see rest of code please let me know have left out of it. thanks!!!
#include <stdio.h> #include <stdlib.h> /* known bugs: allows players place 1 or 2 on board if there 1 or 2 in spot. */ int main() { char board[3][3]; int i,j,k,l, player, move; for(i=0;i<=3;i++) // prints initial board of 0's { for(j=0;j<=3;j++) { board[i][j] = '0'; } } printf("hello! want play alone or computer? \n\n" "enter 1 alone or 2 play friend!\n"); scanf("%d", &player); if (player == 2) { for(k=0;k<9;k++) // 9 moves max. { printf("\n\n"); // print board again. printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]); printf("---+---+---\n"); printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]); printf("---+---+---\n"); printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]); { printf("player 1, move? enter 1-9\n"); scanf("%d", &move); if (move == 1) board[0][0] = '1'; if (move == 2) board[0][1] = '1'; if (move == 3) board[0][2] = '1'; if (move == 4) board[1][0] = '1'; if (move == 5) board[1][1] = '1'; if (move == 6) board[1][2] = '1'; if (move == 7) board[2][0] = '1'; if (move == 8) board[2][1] = '1'; if (move == 9) board[2][2] = '1'; }while(move>9 && move <1);
- i suggest using switch case in last while loop (see example)
- i think need check if field referencing taken!
** check()
**
void check (char *c, int *move){ if(*c == '0'){ *c = '1'; }else { printf("\nthis field taken! please choose one.\n"); /* since repeat long move bigger 9 or smaller 1, have user make choice. */ *move = 0; } }
** last while**
do { printf("player 1, move? enter 1-9\n"); scanf("%d", &move); switch (move){ case 1: check(&board[0][0], &move); break; case 2: check(&board[0][1], &move); break; case 3: check(&board[0][2], &move); break; case 4: check(&board[1][0], &move); break; case 5: check(&board[1][1], &move); break; case 6: check(&board[1][2], &move); break; case 7: check(&board[2][0], &move); break; case 8: check(&board[2][1], &move); break; case 9: check(&board[2][2], &move); break; default: printf("\nerror! choose field between 1 , 9\n"); } }while(move>9 || move <1);
note: others said, for-loops need iterate until i/j < 3, since array has size of 3 (indexes 0, 1, 2);
note 2: while statement must move > 9 or move < 1
since int can't bigger 9 , smaller 1 @ same time, cause infinite loop.
Comments
Post a Comment