if (checkWin(x, y, currentPlayer)) {
isGameStopped = true;
showMessageDialog(Color.NONE, (currentPlayer == 1) ? "You win!" : "Game Over",
(currentPlayer == 1) ? Color.GREEN : Color.RED, 75);
return;
}
package com.javarush.games.ticktacktoe;
import com.javarush.engine.cell.*;
public class TicTacToeGame extends Game {
private int[][] model = new int[3][3];
private int currentPlayer;
private boolean isGameStopped;
public void initialize(){
setScreenSize(3,3);
startGame();
updateView();
}
public void startGame(){
currentPlayer = 1;
isGameStopped = false;
for (int i=0; i<3;i++) {
for(int j=0; j<3;j++) {
model[i][j] = 0;
}
}
}
public void updateCellView(int x, int y, int value) {
if (value == 2) {
setCellValueEx(x, y, Color.WHITE,"O", Color.BLUE);
} else if (value == 1) {
setCellValueEx(x, y, Color.WHITE, "X", Color.RED);
} else setCellValueEx(x, y, Color.WHITE, " ",Color.GREEN); //or: else setCellValueEx(x, y,Color.GREEN, " ", Color.GREEN);
}
public void updateView(){
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
updateCellView(i, j, model[i][j]);
}
}
}
public void setSignAndCheck(int x, int y){
model[x][y] = currentPlayer;
updateView();
if (checkWin(x, y, currentPlayer)) {
isGameStopped = true;
showMessageDialog(Color.NONE, (currentPlayer == 1) ? "You win!" : "Game over!",
(currentPlayer == 1) ? Color.GREEN : Color.RED, 75);
return;
}
if(!hasEmptyCell()){
isGameStopped = true;
showMessageDialog(Color.NONE, " Draw!", Color.BLUE, 75);
return;
}
}
public boolean hasEmptyCell(){
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
if(model[i][j] == 0)
return true;
return false;
}
public void onMouseLeftClick(int x, int y) {
if (isGameStopped) return;
if(model[x][y] != 0) return;
setSignAndCheck(x,y);
currentPlayer = 3 - currentPlayer;
}
public boolean checkWin(int x, int y, int n){
if (model[x][0] == n && model[x][1] == n && model[x][2] == n ||
model[0][y] == n && model[1][y] == n && model[2][y] == n ||
model[0][0] == n && model[1][1] == n && model[2][2] == n ||
model[2][0] == n && model[1][1] == n && model[0][2] == n)
return true;
return false;
}
public void onKeyPress(Key key) {
if(isGameStopped && key == Key.SPACE) {
startGame();
updateView();
}
if (key == Key.ESCAPE) {
startGame();
updateView();
}
}
}