Browse Source

Made cell change color on click/Player turns

feature_TicTacToe_BasicPlayfield
kfkama 3 years ago
parent
commit
597dffcc60
  1. 33
      src/main/java/TicTacToe/TicTacToeGame.java
  2. 29
      src/main/java/TicTacToe/cell.java

33
src/main/java/TicTacToe/TicTacToeGame.java

@ -4,7 +4,6 @@ import java.awt.Graphics;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.geom.Line2D; import java.awt.geom.Line2D;
import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JPanel; import javax.swing.JPanel;
@ -13,10 +12,13 @@ public class TicTacToeGame extends JPanel {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static int width = 600, height = 600; private static int width = 600, height = 600;
public cell[] field;
public int player = 1;
public TicTacToeGame() { public TicTacToeGame() {
this.setSize(width, height); this.setSize(width, height);
setLayout(null);
initField();
} }
public static void main(String[] args) { public static void main(String[] args) {
@ -29,6 +31,25 @@ public class TicTacToeGame extends JPanel {
f.setVisible(true); f.setVisible(true);
} }
public void initField() {
field = new cell[9];
for(int i = 0; i < field.length; i++) {
field[i] = new cell(this);
add(field[i]);
}
for(int i = 0; i < field.length; i++) {
if(i < 3) {
field[i].setBounds(150 + i*100, 150 , 100, 100);
} else if (i < 6) {
field[i].setBounds(150 + i%3*100, 250 , 100, 100);
} else {
field[i].setBounds(150 + i%3*100, 350 , 100, 100);
}
}
}
@Override @Override
protected void paintComponent(Graphics g) { protected void paintComponent(Graphics g) {
super.paintComponent(g); super.paintComponent(g);
@ -45,5 +66,13 @@ public class TicTacToeGame extends JPanel {
g2.draw(lin4); g2.draw(lin4);
} }
public void endTurn() {
player++;
if(player >= 3) {
player = 1;
}
}
} }

29
src/main/java/TicTacToe/cell.java

@ -1,13 +1,40 @@
package TicTacToe; package TicTacToe;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton; import javax.swing.JButton;
public class cell extends JButton { public class cell extends JButton {
int value = 0; int value = 0;
private TicTacToeGame ttt;
public cell(TicTacToeGame _ttt) {
ttt = _ttt;
public cell() {
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OnMouseClick();
}
});
}
protected void OnMouseClick() {
value = ttt.player;
ttt.endTurn();
switch (value) {
case 1: setBackground(new Color(255,0,0));
break;
case 2: setBackground(new Color(0,0,255));
break;
default: ;
break;
} }
}
} }
Loading…
Cancel
Save