1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import java.util.Random;
- public class PlayField {
- private final int[] fields = new int[9];
- private final Random move = new Random();
- public void setPos(int pos, int player) {
- fields[pos] = player;
- }
- public boolean isDraw() {
- for(int i = 0; i < 9; i++) {
- if(fields[i] == 0) {
- return false;
- }
- }
- return true;
- }
- public boolean hasWon(int player) {
- // Waagrecht
- for(int i = 0; i < 9; i += 3) {
- if(fields[i] == player && fields[i + 1] == player && fields[i + 2] == player) {
- return true;
- }
- }
- // Senkrecht
- for(int i = 0; i < 3; i++) {
- if(fields[i] == player && fields[i + 3] == player && fields[i + 6] == player) {
- return true;
- }
- }
- // Diagonal
- if(fields[4] == player) {
- if(fields[0] == player && fields[8] == player) {
- return true;
- }
- if(fields[2] == player && fields[6] == player) {
- return true;
- }
- }
- return false;
- }
- public void reset() {
- for(int i = 0; i < 9; i++) {
- fields[i] = 0;
- }
- }
- // the opponent player moves
- // updates the field
- public void oppMove() {
- while(true) {
- int pos = move.nextInt(9);
- if(isFree(pos)) {
- setPos(pos, 2);
- return;
- }
- }
- }
- public boolean isFree(int pos) {
- return fields[pos] == 0;
- }
- private void printSlot(String sign) {
- System.out.print("[" + sign + "]");
- }
- public void print() {
- for(int y = 0; y < 3; y++) {
- for(int x = 0; x < 3; x++) {
- int a = fields[x + 3 * y];
- if(a == 0) {
- printSlot(" ");
- } else if(a == 1) {
- printSlot("x");
- } else {
- printSlot("o");
- }
- }
- System.out.println(); // Zeilenumbruch
- }
- }
- }
|