tic-tac-toe game
in
Programming Questions
•
2 years ago
I'm trying to learn 2D arrays in processing by creating a simple tic-tac-toe game. I tried to write a function that when the mouse is clicked it creates an ellipse. But I don't understand why it is only doing it for the top left square. Can anyone enlighten me? :) thanks in advance. Code is below:
int cols=3;
int rows=3;
Cell[][] board= new Cell[cols][rows];
void setup(){
size(300,300);
smooth();
for(int i=0; i<cols; i++){
for(int j=0; j<rows; j++){
board[i][j]= new Cell(i*100,j*100,100,100);
}
}
}
void draw(){
for(int i=0; i<cols; i++){
for(int j=0; j<rows; j++){
board[i][j].display();
mousePressed(board[i][j]);
}
}
}
void mousePressed(Cell a){
if (mouseButton== LEFT && mouseX > a.x && mouseX < a.w
&& mouseY > a.y && mouseY < a.h){
a.state= 1;
}
else if (mouseButton== RIGHT && mouseX > a.x && mouseX < a.w
&& mouseY > a.y && mouseY < a.h){
a.state= 0;
}
}
//CLASS CELL
class Cell {
float x;
float y;
float w;
float h;
int state;
Cell (float _x, float _y, float _w, float _h){
x= _x;
y= _y;
w= _w;
h= _h;
}
void display(){
stroke(0);
fill(255);
rect(x,y,w,h);
if(state==1){
fill(255);
ellipse(x+w/2, y+h/2,50,50);
}
}
}
int cols=3;
int rows=3;
Cell[][] board= new Cell[cols][rows];
void setup(){
size(300,300);
smooth();
for(int i=0; i<cols; i++){
for(int j=0; j<rows; j++){
board[i][j]= new Cell(i*100,j*100,100,100);
}
}
}
void draw(){
for(int i=0; i<cols; i++){
for(int j=0; j<rows; j++){
board[i][j].display();
mousePressed(board[i][j]);
}
}
}
void mousePressed(Cell a){
if (mouseButton== LEFT && mouseX > a.x && mouseX < a.w
&& mouseY > a.y && mouseY < a.h){
a.state= 1;
}
else if (mouseButton== RIGHT && mouseX > a.x && mouseX < a.w
&& mouseY > a.y && mouseY < a.h){
a.state= 0;
}
}
//CLASS CELL
class Cell {
float x;
float y;
float w;
float h;
int state;
Cell (float _x, float _y, float _w, float _h){
x= _x;
y= _y;
w= _w;
h= _h;
}
void display(){
stroke(0);
fill(255);
rect(x,y,w,h);
if(state==1){
fill(255);
ellipse(x+w/2, y+h/2,50,50);
}
}
}
1