Code:#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { char board[10]="....X...."; int match[10]; int testMoveNumber(); /* generates random number between 1 and 9 */ /* the section below numbers the match array keys to match the board arrays dots- the other moves will stay at zero so the computer can't select them */ if (board[0]='.') match[1]=1; else if (board[1]='.') match[2]=2; else if (board[2]='.') match[3]=3; else if (board[3]='.') match[4]=4; else if (board[4]='.') match[5]=5; else if (board[5]='.') match[6]=6; else if (board[6]='.') match[7]=7; else if (board[7]='.') match[8]=8; else if (board[8]='.') match[9]=9; /* section below matches the random number with an empty board spot and hopefully loops through with another number until it can write to the board again and break the loop */ int r=0; while(r!=1) { int a=testMoveNumber(); if (match[1]==a) {board[0]='0'; r++;} else if (match[2]==a) {board[1]='0'; r++;} else if (match[3]==a) {board[2]='0'; r++;} else if (match[4]==a) {board[3]='0'; r++;} else if (match[5]==a) {board[4]='0'; r++;} else if (match[6]==a) {board[5]='0'; r++;} else if (match[7]==a) {board[6]='0'; r++;} else if (match[8]==a) {board[7]='0'; r++;} else if (match[9]==a) {board[8]='0'; r++;} else testMoveNumber(); } /* just printing to test the resultant random move by the computer */ printf("%c%c%c%c%c%c%c%c%c", board[0], board[1], board[2], board[3], board[4], board[5], board[6], board[7], board[8]); return 0; } int testMoveNumber() { const int lowestRandom = 1; const int highestRandom = 9; int randomNumber=-1; time_t seconds; time(&seconds); srand((unsigned int) seconds); randomNumber = rand() % (highestRandom - lowestRandom + 1) + lowestRandom; return randomNumber; }
Hi everyone- I'm new to programming and am writing my first program. I am using what I have learnt so far to create a noughts and crosses game but I've got a bit stuck. I am having trouble writing the computers random move to the board array. Basically I'm trying to create a random number between 1 and 9- loop through the unselected board spaces that are numbered in the 'match' array, then writing the matching move back to the board array. I think it is because I am not understanding the regeneration of the random number to select an available space. I still don't know how to use pointers yet and it would be awesome at some point to have the program encapsulated in a few simple functions passing the array back and forth- but for now I'm building it this way I hope my description wasn't too confusing! many thanks, Joe