/* built with Studio Sketchpad:
* https://sketchpad.cc
*
* observe the evolution of this sketch:
* https://studio.sketchpad.cc/sp/pad/view/ro.ByoOXFNmV2N/rev.100
*
* authors:
* Eralp Karaduman
* license (unless otherwise specified):
* creative commons attribution-share alike 3.0 license.
* https://creativecommons.org/licenses/by-sa/3.0/
*/
int[][] game;
char[] turnStr;
color[] colors;
int turnCnt;
int gameWon; // 0 nobody, 1 x, 2 y
int moves;
bool gameDraw;
PFont font;
void setup() {
size(300,300);
font = loadFont("tahoma");
game = new int[3][3];
turnStr = {'X','O'};
turnCnt = 0;
colors = {color(255,0,0),color(0,0,255),color(0,255,0)};
gameWon = 0; // 0 olmalı
moves = 0;
gameDraw = false;
}
void draw() {
background(0,0,0); // clear
/// draw lines ///
stroke(126);
line(100,0,100,300);
line(200,0,200,300);
line(0,100,300,100);
line(0,200,300,200);
// draw cells ///
for(int u=0 ; u<3 ; u++){
for(int v=0 ; v<3 ; v++){
textFont(font,80);
int adjustX = 27;
int adjustY = 18;
int cellData = game[u][v];
cellData = cellData-1;
if(cellData>=0){
fill(colors[cellData]);
text(new String(turnStr[cellData ]),u*100+adjustX,v*100+adjustY,100,100);
}
}
}
///define+display who's turn ///
textFont(font,12);
fill(colors[2]);
text(new String(turnStr[turnCnt]),mouseX-3,mouseY-14,100,100);
if(gameWon == 1){
textFont(font,12);
fill(colors[2]);
text("X WON ! CLICK FOR NEW GAME",5,5,300,300);
}else if(gameWon == 2){
textFont(font,12);
fill(colors[2]);
text("O WON !! CLICK FOR NEW GAME",5,5,300,300);
}else if(gameDraw){
textFont(font,12);
fill(colors[2]);
text("DRAW !! CLICK FOR NEW GAME",5,5,300,300);
}
}
void changeTurn(){
turnCnt++;
turnCnt = (turnCnt>1) ? 0 : turnCnt;
}
void mouseClicked(){
if(gameWon>0){
resetGame();
return;
}
int[] point = getGridIndex(mouseX,mouseY);
if(game[point[0]][point[1]] != 0){
return;
}
game[point[0]][point[1]] = turnCnt+1;
checkGame(point,turnCnt);
changeTurn();
}
int[] getGridIndex(x,y){
int[] point = {};
point[0] = floor(x/100);
point[1] = floor(y/100);
return point;
}
void checkGame(int[] _point,int _turnCnt){
moves++;
//check col
for(int i = 0; i < 3; i++){
if(game[_point[0]][i] != _turnCnt+1)break;
if(i == 3-1){
gameWon = _turnCnt+1;
//println("won1");
}
}
//check row
for(int i = 0; i < 3; i++){
if(game[i][_point[1]] != _turnCnt+1)break;
if(i == 3-1){
gameWon = _turnCnt+1;
//println("won2");
}
}
//check diag
if(int[0] == int[1]){
//we're on a diagonal
for(int i = 0; i < 3; i++){
if(game[i][i] != _turnCnt+1)break;
if(i == 3-1){
gameWon = _turnCnt+1;
//println("won3");
}
}
}
//check anti diag
for(int i = 0;i<3;i++){
if(game[i][(3-1)-i] != _turnCnt+1)break;
if(i == 3-1){
gameWon = _turnCnt+1;
//println("won4");
}
}
// check draw
if(moves == 9 && gameWon==0){
gameDraw = true;
gameWon = 3263; // some number
}
}
void resetGame(){
game = new int[3][3];
turnCnt = 0;
moves = 0;
gameWon = 0; // 0 olmalı
gameDraw = false;
}
void checkWin(int sum){
if(sum == 3)gameWon = 1;
if(sum == 6)checkWin = 2;
}