-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnect4.java
276 lines (209 loc) · 8.45 KB
/
Connect4.java
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.ArrayList;
public class Connect4 extends JPanel implements MouseListener, KeyListener{
// These control the size of the board. The traditional Connect 4 board is
// seven spaces wide by six spaces high
private static final int ROWS = 6;
private static final int COLS = 7;
private boolean winner = false;
private static final int pieceSize = 50; //size of the pieces in pixels
private static final int spacing = 10; //spacing between adjacent pieces in pixels;
private static final int headerHeight = 50; // height of header for messages and column numbers
private String message = "";
private JFrame myFrame;
private Board myBoard;
// this contains the ordered list of players in the game
private ArrayList<Player> players;
private int currentPlayerIndex = 0;
/** creates the connect four interface with the specified number of rows and colonms
* @param rows int
* @param cols int
*/
public Connect4(int rows, int cols ) {
myFrame = new JFrame();
TextField Text = new TextField("Text");
this.myBoard = new Board(rows, cols);
addMouseListener(this);
addKeyListener(this);
// the hard numbers at the end are for the menubar at the top and side handles
myFrame.setSize( myBoard.getCols() * (pieceSize + spacing) + spacing + 10,
myBoard.getRows() * (pieceSize + spacing) + spacing + headerHeight + 35);
myFrame.add(this);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//myFrame.setResizable( false );
myFrame.setTitle( "Connect Four" );
myFrame.setVisible(true);
Text.addKeyListener(this);
Text.setEditable(false);
add(Text);
setVisible(true);
// start a new game
newGame();
}
////// Gameplay
//////
// Note, the main loop in the gameplay (players alternating turns) happens between
// the play() and takeTurn() methods. These call each other, which is a type of
// recursion (called mutual recursion).
// Call newGame() to restart the game, or start it for the first time.
public void newGame() {
myBoard.reset();
players = new ArrayList<Player>();
Player p1 = new Player("Max", Color.black);
StupidComputerPlayer p2 = new StupidComputerPlayer("Robot Robo", Color.red);
players.add(p1);
players.add(p2);
message = "Let's play! " + getCurrentPlayer().getName() + " goes first. ";
repaint();
play();
}
// start the recursion to play the game.
private void play() {
if ( (getCurrentPlayer() instanceof ComputerPlayer ) ) {
// the player is a ComputerPlayer, so can calculate its own move
//delay(1000); // hm, this doesn't work
// only ComputerPlayers have a getMove method, so we have to cast getCurrentPlayer into one.
ComputerPlayer computer = (ComputerPlayer) getCurrentPlayer();
Move move = computer.getMove(myBoard);
while (isColumnFull(move)) { //fixed this, computer would place ghost pieces
//Replace move with new move
move = computer.getMove(myBoard);
}
takeTurn(computer.getMove(myBoard));
}
// otherwise, the player isn't a ComputerPlayer, so we stop, and let the listener invoke takeTurn()
}
public boolean isColumnFull(Move move){
int x = move.getColumn();
if(myBoard.grid[ROWS - 1][x] != null){
return true;
}
return false;
}
private void takeTurn(Move move) {
myBoard.addPiece(move);
//bug is here
message = getCurrentPlayer().getName() + " goes in column " + move.getColumn() + ". ";
if ( myBoard.winner(move) != null ) {
message += getCurrentPlayer().getName() + " wins! " + getCurrentPlayer().getName() + " wins! ";
winner = true;
repaint();
} else if(myBoard.boardFull() == true){
message += " Tie game! No more moves possible.";
winner = true;
repaint();
} else {
advanceToNextPlayer();
message += "It is now " + getCurrentPlayer().getName() + "'s turn. ";
repaint();
play();
}
}
// returns the current player
private Player getCurrentPlayer () {
return players.get(currentPlayerIndex);
}
// advance the next player in line
private void advanceToNextPlayer() {
currentPlayerIndex++;
if (currentPlayerIndex == players.size()) {
currentPlayerIndex = 0;
}
}
//////Listener
//////
public void mouseClicked(MouseEvent e) {
// only process the click if the current player isn't a computer player
if ( ! (getCurrentPlayer() instanceof ComputerPlayer) && !winner) {
// find out which column was clicked on...
int c = myBoard.getCols();
while ( (e.getX() < horizontalPos(c)) && (c > 0) ) {
c--;
}
// and restart the gameplay recursion
takeTurn( new Move(c, getCurrentPlayer()) );
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 81){
System.out.println("You quit!");
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 81){
System.exit(1);
}
}
///// GRAPHICS
/////
public void paint( Graphics g ) {
g.setColor( Color.BLUE );
g.fillRect( 0, 0, myFrame.getWidth(), myFrame.getHeight() );
Player cell;
// draw column header (numbers and message)
g.setColor(Color.white);
g.drawString(message, pieceSize, headerHeight - 25);
for (int c = 0; c < myBoard.getCols(); c++) {
g.drawString(Integer.toString(c), horizontalPos(c) + pieceSize/2 - 4, headerHeight);
}
// draw pieces
for(int r = 0; r < myBoard.getRows(); r++ ) {
for(int c = 0; c < myBoard.getCols(); c++ ) {
cell = myBoard.getCell(r, c);
if (cell != null) {
drawPiece( g, r, c, cell.getColor() );
} else {
drawPiece( g, r, c, Color.gray );
}
}
}
}
//shows a piece at location row r and col c for given color
private void drawPiece(Graphics g, int r, int c, Color color ) {
//System.out.println(c.toString());
g.setColor( color );
g.fillOval( horizontalPos(c), verticalPos(r), pieceSize, pieceSize );
g.setColor( Color.white );
g.drawOval( horizontalPos(c) - 1, verticalPos(r) - 1, pieceSize + 1, pieceSize + 1 );
//g.setColor( new Color( 128, 128, 0 ) );
//g.drawOval( horizontalPos(c), verticalPos(r), pieceSize, pieceSize );
}
// returns the horizontal pixel position of a given 0-based column index
private int horizontalPos(int c) {
return (spacing + c * (pieceSize + spacing));
}
// returns the vertical pixel position of a given 0-based row index
private int verticalPos(int r) {
return (spacing + headerHeight + (myBoard.getRows() - r - 1) * (pieceSize + spacing));
}
// This method causes your program to pause for a certain number of milliseconds
// Don't worry about the details of the class Thread, we won't cover it in this course.
private void delay(int ms) {
try {
Thread.sleep (ms);
} catch (Exception ex) {
ex.printStackTrace();
}
}
////// Main
//////
public static void main( String[] args ){
Connect4 connect4 = new Connect4(ROWS, COLS);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'keyTyped'");
}
}