/* A little tick-tack-toe game. Makes some use of para statement. */ include 'dimTwoD' array of array of string board = dimTwoD(3,3); to printRow(array of string a) /* Print out X and O's with | between them */ { prin(a[0]); prin("|"); prin(a[1]); prin("|"); prin(a[2]); print(""); } to printBoard() /* Print out tick-tack-toe board with X's and O's */ { printRow(board[0]); print("-----"); printRow(board[1]); print("-----"); printRow(board[2]); } to won(array of array of string b, string mark) into bit won /* Return true if the given mark has won. */ { static array of int ix3 = (0,1,2); bit wonByRow = para (row in b) || para (square in row) && square == mark; bit wonByCol = para (j in ix3) || para (i in ix3) && b[i][j] == mark; bit wonDiag = para (i in ix3) && b[i][i] == mark; bit wonSlash = para (i in ix3) && b[2-i][i] == mark; won = wonByRow || wonByCol || wonDiag || wonSlash; } to full() into bit full /* Return true if the board is full. */ { full = para (row in board) && para (square in row) && square != " "; } to parseInput(string s) into (bit ok, int x, int y) /* Parse two integers between 1 and 3 out of line. * Return whether parsed ok, and numbers x and y * converted to 0-2 coordinates. */ { int pos; string xAscii,yAscii; (xAscii, pos) = s.nextWord(pos); (yAscii, pos) = s.nextWord(pos); if (xAscii && yAscii) { x = atoi(xAscii) - 1; y = atoi(yAscii) - 1; if (x >= 0 && x <= 2 && y >= 0 && y <= 2) ok = 1; } } to computerMove() /* Have the computer put an O someplace semi-intelligent. */ { /* First try to win. */ for (int i=0; i<3; i += 1) for (int j=0; j<3; j += 1) if (board[j][i] == " ") { board[j][i] = "O"; if (won(board, "O")) return; else board[j][i] = " "; } /* Next try to block. */ for (int i=0; i<3; i += 1) for (int j=0; j<3; j += 1) if (board[j][i] == " ") { board[j][i] = "X"; if (won(board, "X")) { board[j][i] = "O"; return; } else board[j][i] = " "; } /* Next take middle square if available. */ if (board[1][1] == " ") { board[1][1] = "O"; return; } /* Next just fill in anything. */ for (int i=0; i<3; i += 1) for (int j=0; j<3; j += 1) if (board[j][i] == " ") { board[j][i] = "O"; return; } } print( " You are X and I am O. You go first. Type in coordinates and return to make a move. For instance to get upper right corner type 1 3. "); printBoard(); print(""); for (;;) /* This is the main game loop. */ { int x,y; bit ok; while (!ok) { string input = lineIn(); (ok,x,y) = parseInput(input); if (ok) { if (board[x][y] != " ") { print("That space is already taken."); ok = 0; } } else print("Please put in two numbers, both between 1 and 3."); } board[x][y] = "X"; printBoard(); print(""); if (won(board, "X")) { print("Argh, you won"); break; } else if (full()) { print("Cat's paw. A typical tie."); break; } computerMove(); printBoard(); if (won(board, "O")) { print("I won, yippee!"); break; } }