-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoardView.java
More file actions
87 lines (73 loc) · 1.92 KB
/
BoardView.java
File metadata and controls
87 lines (73 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import javax.swing.JPanel;
import javax.swing.JButton;
import java.util.Observer;
import java.util.Observable;
import java.awt.GridLayout;
public class BoardView extends JPanel implements Observer
{
private NoughtsCrossesModel model;
private JButton[][] cell;
public BoardView(NoughtsCrossesModel model)
{
super();
// initialise model
this.model = model;
//create array of buttons
cell = new JButton[3][3];
//set layout of panel
setLayout(new GridLayout(3, 3));
//for each square in grid:create a button; place on panel
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cell[i][j] = new JButton(" ");
final int x = i; final int y = j;
cell[i][j].addActionListener(e-> {
model.turn(x, y);
model.setTurn(((x+1) * 10) + (y+1));
// if the game is over and there is a winner - sets the current user to the winner and prevents him from playing
if(model.whoWon() != 0){
model.setInVisible(false);
model.setUserWinner(true);;
}
});
add(cell[i][j]);
}
}
}
public void update(Observable obs, Object obj)
{
// for each square do the following:
// if it's a NOUGHT, put O on button
// if it's a CROSS, put X on button
// else put on button
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(model.get(i, j) == NoughtsCrosses.CROSS)
{
cell[i][j].setText("X");
cell[i][j].setEnabled(false);
}
else if(model.get(i, j) == NoughtsCrosses.NOUGHT)
{
cell[i][j].setText("O");
cell[i][j].setEnabled(false);
}
else
{
cell[i][j].setText(" ");
boolean notOver = (model.whoWon() ==
NoughtsCrosses.BLANK);
cell[i][j].setEnabled(notOver);
if(notOver){
cell[i][j].setEnabled(model.getIsMyTurn());
}
}
}
}
repaint();
}
}