Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //don't miss the next post to get the Processing code
- #define PLAYER_MOVE 1
- #define COMPUTER_MOVE 2
- void setup()
- {
- Serial.begin(9600);
- Serial.print("Write you chooses using the format ");
- Serial.println("'line column' (in numbers) without \" ' \" ");
- }
- void loop()
- {
- while(Serial.available() >= 1)
- {
- int value;
- value = Serial.read();
- playPlayer(value);
- }
- }
- void playPlayer(int pos)
- {
- static int board[9] = {
- 0, 0, 0,
- 0, 0, 0,
- 0, 0, 0
- };
- board[pos] = PLAYER_MOVE;
- if(findWinner(board))
- {
- //Serial.println("Player is the winner!");
- }
- playComputer(board);
- }
- void playComputer(int board[9])
- {
- if(!chooseNextMove(board))
- {
- computerStrategicMove(board);
- }
- if(findWinner(board))
- {
- //Serial.println("Computer is the winner!");
- }
- }
- bool chooseNextMove(int board[9])
- {
- int p;
- for(p = 0; p < 9; p++)
- {
- if(!board[p])
- {
- board[p] = COMPUTER_MOVE;
- if(findWinner(board))
- {
- Serial.write(p);
- return true;
- }
- board[p] = PLAYER_MOVE;
- if(findWinner(board))
- {
- Serial.write(p);
- board[p] = COMPUTER_MOVE;
- return true;
- }
- board[p] = 0;
- }
- }
- return false;
- }
- void computerStrategicMove(int board[9])
- {
- bool ahead = false;
- int p = 4;
- //center
- if(!board[p])
- {
- board[p] = COMPUTER_MOVE;
- Serial.write(p);
- return;
- }
- //diagonal
- for( p = 0; p < 9; p += ((!ahead) ? (2) : (4)) )
- {
- if(!board[p])
- {
- board[p] = COMPUTER_MOVE;
- Serial.write(p);
- return;
- }
- ahead ^= true;
- }
- //mid lines
- for(p = 1; p < 9; p+=2)
- {
- if(!board[p])
- {
- board[p] = COMPUTER_MOVE;
- Serial.write(p);
- return;
- }
- }
- }
- bool findWinner(const int board[9])
- {
- int a;
- for(a = 0; a < 9; a+=3)
- {
- if(!board[a])
- {
- continue;
- }
- if( board[a] == board[a + 1] &&
- board[a] == board[a + 2])
- {
- return true;
- }
- }
- //
- for(a = 0; a < 3; a++)
- {
- if(!board[a])
- {
- continue;
- }
- if( board[a] == board[a + 3] &&
- board[a] == board[a + 6])
- {
- return true;
- }
- }
- //
- if( board[0] == board[4] &&
- board[0] == board[8] && board[0] != 0)
- {
- return true;
- }
- if( board[2] == board[4] &&
- board[2] == board[6] && board[2] != 0)
- {
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement