Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package objectstructures;
- public class TicTacToe {
- char[][] board = new char [3][3];
- private char player;
- public TicTacToe() {
- player = 'x';
- for(int i=0; i<3; i++) {
- for(int k=0; k<3; k++) {
- board[i][k] = ' ';
- }
- }
- }
- public char getCell(int x, int y) {
- return board[x][y];
- }
- public boolean isOccupied(int x, int y) {
- char chr = getCell(x, y);
- if (chr != ' ') {
- return true;
- }
- return false;
- }
- public boolean setCell(char c, int x, int y) {
- if (isOccupied(x, y)) {
- return false;
- }
- board[x][y] = c;
- return true;
- }
- public char getCurrentPlayer() {
- return player;
- }
- public String toString() {
- String s = "";
- s += "\n " + getCell(0,0) + " | " + getCell(0,1) + " | " + getCell(0,2);
- s += "\n-----------";
- s += "\n " + getCell(1,0) + " | " + getCell(1,1) + " | " + getCell(1,2);
- s += "\n-----------";
- s += "\n " + getCell(2,0) + " | " + getCell(2,1) + " | " + getCell(2,2);
- s += "\n";
- if(isWinner('x')) {
- return s + "\n" + "x won!";
- }else if(isWinner('o')){
- return s + "\n"+ "o won!";
- }else if(isFinished()){
- return s + "\n" + "It's a tie";
- }else{
- return s + "\n" + "Spiller =" + player;
- }
- }
- //public static void main(String[] args) {
- //TicTacToe tic = new TicTacToe();
- //System.out.println(tic);
- //}
- public void play(int x, int y) {
- if(setCell(player, x, y)){
- if(player == 'x'){
- player = 'o';
- }else{
- player = 'x';
- }
- }
- }
- public boolean isWinner(char c) {
- if (getCell(0, 0) == c && getCell(0, 1) == c && getCell(0, 2) == c) {
- return true;
- }
- if (getCell(1, 0) == c && getCell(1, 1) == c && getCell(1, 2) == c) {
- return true;
- }
- if (getCell(2, 0) == c && getCell(2, 1) == c && getCell(2, 2) == c) {
- return true;
- }
- // Sjekker om spiller c har vunnet loddrett:
- if (getCell(0, 0) == c && getCell(1, 0) == c && getCell(2, 0) == c) {
- return true;
- }
- if (getCell(0, 1) == c && getCell(1, 1) == c && getCell(2, 1) == c) {
- return true;
- }
- if (getCell(0, 2) == c && getCell(1, 2) == c && getCell(2, 2) == c) {
- return true;
- }
- // Sjekker om spiller c har vunnet diagonalt:
- if (getCell(0, 0) == c && getCell(1, 1) == c && getCell(2, 2) == c) {
- return true;
- }
- if (getCell(0, 2) == c && getCell(1, 1) == c && getCell(2, 0) == c) {
- return true;
- }
- return false;
- }
- public boolean hasWinner() {
- if(isWinner('x') || isWinner('o')) {
- return true;
- }
- return false;
- }
- public boolean isFinished() {
- if(hasWinner()) {
- return true;
- }else{
- for(int i=0; i<3; i++) {
- for(int k=0; k<3; k++) {
- if(board[i][k] == ' ') {
- return false;
- }
- return true;
- }
- } return false;
- }
- }
- public void getInput(String in) {
- int x = Integer.valueOf(in.substring(0,1));
- int y = Integer.valueOf(in.substring(1));
- if(!isFinished()) {
- play(x, y);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement