From 597dffcc6067df7ffd60e54fc5068a368b2e618f Mon Sep 17 00:00:00 2001 From: kfkama Date: Tue, 15 Feb 2022 00:05:50 +0100 Subject: [PATCH] Made cell change color on click/Player turns --- src/main/java/TicTacToe/TicTacToeGame.java | 35 ++++++++++++++++++++-- src/main/java/TicTacToe/cell.java | 31 +++++++++++++++++-- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/main/java/TicTacToe/TicTacToeGame.java b/src/main/java/TicTacToe/TicTacToeGame.java index db769ff..89fa969 100644 --- a/src/main/java/TicTacToe/TicTacToeGame.java +++ b/src/main/java/TicTacToe/TicTacToeGame.java @@ -4,7 +4,6 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Line2D; -import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; @@ -13,22 +12,44 @@ public class TicTacToeGame extends JPanel { private static final long serialVersionUID = 1L; private static int width = 600, height = 600; - + public cell[] field; + public int player = 1; public TicTacToeGame() { this.setSize(width, height); + setLayout(null); + initField(); } public static void main(String[] args) { JFrame f = new JFrame(); TicTacToeGame ttt = new TicTacToeGame(); - + f.add(ttt); f.setSize(width,height); f.setLayout(null); 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 protected void paintComponent(Graphics g) { super.paintComponent(g); @@ -45,5 +66,13 @@ public class TicTacToeGame extends JPanel { g2.draw(lin4); } + public void endTurn() { + player++; + if(player >= 3) { + player = 1; + } + + } + } \ No newline at end of file diff --git a/src/main/java/TicTacToe/cell.java b/src/main/java/TicTacToe/cell.java index ea76245..b8c4351 100644 --- a/src/main/java/TicTacToe/cell.java +++ b/src/main/java/TicTacToe/cell.java @@ -1,13 +1,40 @@ package TicTacToe; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + import javax.swing.JButton; public class cell extends JButton { int value = 0; + private TicTacToeGame ttt; - public cell() { + public cell(TicTacToeGame _ttt) { + ttt = _ttt; + 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; + } + } + + + + }