public void champ (Grid g) { int [][] b = {{2,2,2}, {2,2,2}, {2,2,2}}; int turn = 1, i, j, // turn is the turn about to be played, from 1 to 9 make2 = 0, posWinEX = -1, posWinOH = -1; // these are linear indexes {0, 1, ..., 8} for (i=0; i<3; i++) for (j=0; j<3; j++) { if (g.equals(i, j, g.EX)) {b[i][j] = 3; turn++;} else if (g.equals(i, j, g.OH)) {b[i][j] = 5; turn++;} } // compute posWinEX = the position of a win by EX (-1 if none) for (i=0; i<3; i++) { if (b[i][0]*b[i][1]*b[i][2]==18) { posWinEX = 3*i; if (b[i][1]==2) posWinEX=posWinEX+1; else if (b[i][2]==2) posWinEX=posWinEX+2; } if (b[0][i]*b[1][i]*b[2][i]==18) { posWinEX = i; if (b[1][i]==2) posWinEX=posWinEX + 3; else if (b[2][i]==2) posWinEX=posWinEX + 6; } } if (b[0][0]*b[1][1]*b[2][2]==18) {posWinEX = 0; if (b[1][1]==2) posWinEX=4; else if (b[2][2]==2) posWinEX=8;} if (b[0][2]*b[1][1]*b[2][0]==18) {posWinEX = 2; if (b[1][1]==2) posWinEX=4; else if (b[2][0]==2) posWinEX=6;} // compute posWinOH = the position of a win by OH (-1 if none) for (i=0; i<3; i++) { if (b[i][0]*b[i][1]*b[i][2]==50) { posWinOH = 3*i; if (b[i][1]==2) posWinOH=posWinOH+1; else if (b[i][2]==2) posWinOH=posWinOH+2; } if (b[0][i]*b[1][i]*b[2][i]==50) { posWinOH = i; if (b[1][i]==2) posWinOH=posWinOH + 3; else if (b[2][i]==2) posWinOH=posWinOH + 6; } } if (b[0][0]*b[1][1]*b[2][2]==50) {posWinOH = 0; if (b[1][1]==2) posWinOH=4; else if (b[2][2]==2) posWinOH=8;} if (b[0][2]*b[1][1]*b[2][0]==50) {posWinOH = 2; if (b[1][1]==2) posWinOH=4; else if (b[2][0]==2) posWinOH=6;} // try to make 2 in a row, or find a blank square if (b[1][1]==2) make2=4; else if (b[0][1]==2) make2=1; else if (b[1][0]==2) make2=3; else if (b[1][2]==2) make2=5; else if (b[2][1]==2) make2=7; else if (b[0][2]==2) make2=2; else if (b[2][0]==2) make2=6; else if (b[2][2]==2) make2=8; switch (turn) { case 1: g.set(0,0,g.EX); return; case 2: if (b[1][1]==2) g.set(1,1,g.OH); else g.set(0,0,g.OH); return; case 3: if (b[2][2]==2) g.set(2,2,g.EX); else g.set(1,0,g.EX); return; case 4: if (posWinEX!=-1) g.set(posWinEX/3, posWinEX%3, g.OH); // block else g.set(make2/3, make2%3, g.OH); return; case 5: if (posWinEX!=-1) g.set(posWinEX/3, posWinEX%3, g.EX); // win else if (posWinOH!=-1) g.set(posWinOH/3, posWinOH%3, g.EX); // block // try for a fork else if (b[2][0]==2) g.set(2, 0, g.EX); else g.set(0, 2, g.EX); return; case 6: case 8: if (posWinOH!=-1) g.set(posWinOH/3, posWinOH%3, g.OH); // win else if (posWinEX!=-1) g.set(posWinEX/3, posWinEX%3, g.OH); // block else g.set(make2/3, make2%3, g.OH); return; case 7: case 9: if (posWinEX!=-1) g.set(posWinEX/3, posWinEX%3, g.EX); // win else if (posWinOH!=-1) g.set(posWinOH/3, posWinOH%3, g.EX); // block else g.set(make2/3, make2%3, g.EX); return; } }