Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- String board[] = {"","","","","","","","",""};
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- }
- void loop() {
- // put your main code here, to run repeatedly:
- if(checkIfOver()) {
- resetBoard();
- }
- else {
- playerPlaceX();
- }
- if(checkIfOver()) {
- resetBoard();
- }
- else {
- HEROPlaceO();
- }
- }
- boolean isAvailable(int square) {
- if(board[square]==""){
- return true;
- }
- else {
- return false;
- }
- }
- void resetBoard() {
- Serial.println("Resetting board...");
- delay(5000);
- for(int i = 0; i < 8; i++){
- board[i] = "";
- }
- }
- void playerPlaceX() {
- Serial.println("Where would you like to place an X? Enter 0-8");
- while (Serial.available() == 0) { // stops program from continuing until Serial.available is 0, or the user inputs something.
- //wait for user to input data
- }
- int playerChoice = Serial.readString().toInt();
- if (isAvailable(playerChoice)) {
- board[playerChoice] = 'X';
- }
- else {
- Serial.println("Spot already contains: " + board[playerChoice]);
- delay(2000);
- playerPlaceX();
- }
- }
- void HEROPlaceO() {
- randomSeed(analogRead(0));
- int AIChoice = random(9);
- if(isAvailable(AIChoice)){
- board[AIChoice] = 'O';
- Serial.println("HERO Placed 0 in board spot " + String(AIChoice));
- }
- else {
- HEROPlaceO();
- }
- }
- boolean crossCheck(String a, String b, String c){
- if(a.equals(b) && b.equals(c)){
- if(c.equals("")){
- return false;
- }
- return true;
- }
- else {
- return false;
- }
- }
- boolean boardFull() {
- for(int i = 0; i < 8; i++){
- if(board[i].equals("")) {
- return false;
- }
- }
- return true;
- }
- boolean checkIfOver() {
- if(crossCheck(board[0], board[3], board[6])
- || crossCheck(board[0], board[1], board[2])
- || crossCheck(board[0], board[4], board[8])) { //case 1-3
- Serial.println(board[0] + " wins!");
- return true;
- }
- else if(crossCheck(board[4], board[3], board[5])
- || crossCheck(board[4], board[1], board[7])
- || crossCheck(board[4], board[2], board[6])) { //case 4-6
- Serial.println(board[4] + " wins!");
- return true;
- }
- else if(crossCheck(board[8], board[6], board[7])
- || crossCheck(board[8], board[2], board[5])) { //case 7-8
- Serial.println(board[8] + " wins!");
- return true;
- }
- else if(boardFull()) {
- Serial.println("A draw has occured.");
- return true;
- }
- else {
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement