|
@@ -0,0 +1,96 @@
|
|
|
+import java.util.Random;
|
|
|
+
|
|
|
+public class PlayField {
|
|
|
+ int[] field = new int[9];
|
|
|
+
|
|
|
+ //updates the field after a players move
|
|
|
+ //returns true if won
|
|
|
+ public boolean updatePos(int pos, int player) {
|
|
|
+ field[pos - 1] = player;
|
|
|
+ printField();
|
|
|
+ return hasWon(player);
|
|
|
+ }
|
|
|
+
|
|
|
+ public boolean isDraw() {
|
|
|
+ for(int i = 0; i < 9; i++) {
|
|
|
+ if(field[i] == 0) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ public boolean hasWon(int player) {
|
|
|
+ //Waagrecht
|
|
|
+ if(field[0] == player && field[1] == player && field[2] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if(field[3] == player && field[4] == player && field[5] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if(field[6] == player && field[7] == player && field[8] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ //Senkrecht
|
|
|
+ if(field[0] == player && field[3] == player && field[6] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if(field[1] == player && field[4] == player && field[7] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if(field[2] == player && field[5] == player && field[8] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ //Diagonal
|
|
|
+ if(field[4] == player) {
|
|
|
+ if(field[0] == player && field[8] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if(field[2] == player && field[6] == player) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void resetField() {
|
|
|
+ for(int i = 0; i < 9; i++) {
|
|
|
+ field[i] = 0;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ //the opponent player moves
|
|
|
+ //updates the field
|
|
|
+ //returns true if won
|
|
|
+ public boolean oppMove() {
|
|
|
+ Random move = new Random();
|
|
|
+ int pos = 1 + move.nextInt(9);
|
|
|
+ while(getPos(pos) != 0 ) {
|
|
|
+ pos = 1 + move.nextInt(9);
|
|
|
+ }
|
|
|
+ return updatePos(pos, 2);
|
|
|
+ }
|
|
|
+
|
|
|
+ public int getPos(int pos) {
|
|
|
+ return field[pos - 1];
|
|
|
+ }
|
|
|
+
|
|
|
+ public void printField() {
|
|
|
+ String sign;
|
|
|
+ for(int h = 0; h < 3; h++) {
|
|
|
+ for(int i = 0; i < 3; i++) {
|
|
|
+ int a = field[i + 3 * h];
|
|
|
+ if(a == 0) {
|
|
|
+ sign = " ";
|
|
|
+ } else if(a == 1) {
|
|
|
+ sign = "x";
|
|
|
+ } else {
|
|
|
+ sign = "o";
|
|
|
+ }
|
|
|
+ System.out.print("[" + sign + "]");
|
|
|
+ }
|
|
|
+ System.out.println(); //Zeilenumbruch
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+}
|