-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicTacToeAI.java
More file actions
340 lines (287 loc) · 10.5 KB
/
Copy pathTicTacToeAI.java
File metadata and controls
340 lines (287 loc) · 10.5 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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//Christina Chung
//Last Modified: Feb 23/2013
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
//TicTacToe: runs a computer vs player Tic Tac Toe game
public class TicTacToeAI extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//variables
static final char UNCLAIMED= ' ', O= 'O', X='X', DRAW='-';
char winner= ' ';
String result=""; //stores the string notifying the winner to display on frame
private char tiles[]= {//keep track of claimed tiles
UNCLAIMED, UNCLAIMED, UNCLAIMED,
UNCLAIMED,UNCLAIMED,UNCLAIMED,
UNCLAIMED,UNCLAIMED,UNCLAIMED,
};
private Random randint= new Random ();
//this array contains all the possible winning combinations
private int winningCombo[][]={
{0,3,6},//vertical
{1,4,7},
{2,5,8},
{0,1,2}, //horizontal
{3,4,5},
{6,7,8},
{0,4,8}, //diagonal
{2,4,6}};
Font font= new Font ("Calibri",Font.BOLD,100);
public static void main(String[] args) {
new TicTacToeAI();
}
//TicTacToe(): constructor for the TicTacToeAI class, constructs the JFrame
public TicTacToeAI (){
super ("Tic Tac Toe");
setResizable(false);
setSize(500,552);
JPanel pane= (JPanel)getContentPane();
pane.setLayout(new BorderLayout());
JButton restart= new JButton ("Restart");
restart.addActionListener(this);
pane.add(new TicTacToeBoard(),BorderLayout.CENTER);
pane.add(restart,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible (true);
pane.addMouseListener(new ClickHandler());
}
//Parameters: ActionEvent e
//Returns: void
//Method Description: actionPerformed(): called when user clicks the "reset" button
//and starts a new game
public void actionPerformed (ActionEvent e){
for (int j=0; j<9; ++j){
tiles[j]=UNCLAIMED; //clear tiles
}
winner=' ';
result="";
repaint();
}
//Parameters: none
//Returns: void
//Method Description: turnO(): determines if X won or if there's a draw, and if not,
//then the computer will make a move, and then checks if O won.
void turnO(){
if (isWinner(X)){
winner=X;
result= "X WON!";
}else if (isDraw()){
winner=DRAW;
result="TIE!";
}else {
moveO();
if(isWinner(O)){
winner=O;
result="O WON!";
}
}
repaint(); //update the board
}
//Parameters: char holder (the current player)
//Returns: boolean
//Method Description: isWinner(): determines if the given player has won the game and
//if so, the boolean value "true" is returned, otherwise,
//the boolean value "false" is returned.
boolean isWinner(char holder) {
for (int i=0; i<8; ++i){
if (winCombo(holder, winningCombo[i][0], winningCombo[i][1],winningCombo[i][2])){//compares all the winning row combinations to see if player has won
return true;
}
}
return false;
}
//Parameters: char holder, int a, int b, int c (char holder= current holder & a,b,c= integers represeting the winning row combinations)
//Returns: boolean
//Method Description: winCombo(): determines if the holder matches the given winning combination
boolean winCombo(char holder, int a, int b, int c) {
return tiles[a]==holder && tiles[b]==holder
&& tiles[c]==holder;
}
//Parameters: none
//Returns: void
//Method Description: moveO(): determines and executes O's next move.
void moveO() {
int tilePos=checkWinCombo(O); //determine if O has claimed two tiles in any of the winning positions
if (tilePos==-1){ //O has not claimed two tiles in the winning positions
tilePos=checkWinCombo(X); //determine if X has claimed two tiles in any of the winning positions
}if (tilePos==-1) { //X has not claimed two tiles in the winning positions
tilePos=getRandomMove(); //random move
}
tiles[tilePos]=O; //O claims tile
}
//Parameters:none
//Returns: integer (representing a tile)
//Method Description: getRandomMove(): using a do whole loop, it generates a random integer between 0 and 8,
//representing a tile. And if the tile is unclaimed, the do while loop stop iterating and the
//integer is returned.
int getRandomMove(){
int tilePos;
do{
tilePos=randint.nextInt(9);
}while (tiles[tilePos]!=UNCLAIMED);
return tilePos;
}
//Parameters: char holder (the current player)
//Returns: integer
//Method Description: checkWinCombo(): determines if the given holder has claimed
//2 tiles in any winning position and returns the empty, unclaimed tile. If the holder
//has not claimed two tiles, -1 is returned.
int checkWinCombo(char holder){
for (int i=0; i<8; ++i) {
int tilePos= checkRow (holder, winningCombo[i][0], winningCombo[i][1], winningCombo[i][2]);
if (tilePos>=0){
return tilePos;
}
}
return -1;
}
//Parameters: char holder, int x, int y, int z (holder= current player, & x,y,z= a sequence of 3 tiles representing a winning combination
//Returns: integer
//Method Description: checkRow(): determines if there is an unclaimed tile in the
//given sequence of 3 tiles. checkRow () returns the unclaimed tile position as an integer
//or -1 if there is no unclaimed tile
int checkRow (char holder, int x, int y, int z) {
if (tiles[x]==holder && tiles[y]==holder && tiles[z]==UNCLAIMED){
return z;
}else if (tiles[x]==holder && tiles[z]==holder && tiles[y]==UNCLAIMED){
return y;
}else if (tiles[y]==holder && tiles[z]==holder && tiles[x]==UNCLAIMED){
return x;
}else{
return -1;
}
}
//Parameters: none
//Returns: boolean
//Method Description: isDraw(): determines if the game end result is a draw by
//checking if any tiles are currently unclaimed. If there are unclaimed tiles,
//then the game has not ended the boolean expression "false" is returned. Otherwise,
//if all tiles have been claimed, then the game is over and "true" is returned.
boolean isDraw() {
for (int i=0; i<9; ++i){
if (tiles[i]==UNCLAIMED){
return false;
}
}
return true;
}
//ClickHandler: handles user clicks
class ClickHandler extends MouseAdapter{
int size=getWidth(); //length of board
int a= size/3;
int c=size;
int f=size/3*2;
Rectangle A1= new Rectangle (0,0,a,a); //these rectangles represent each tile on the board
Rectangle A2= new Rectangle (a,0,f,a);
Rectangle A3= new Rectangle (f,0,c,a);
Rectangle A4= new Rectangle (0,a,a,f);
Rectangle A5= new Rectangle (a,a,f,f);
Rectangle A6= new Rectangle (f,a,c,f);
Rectangle A7= new Rectangle (0,f,a,c);
Rectangle A8= new Rectangle (a,f,f,c);
Rectangle A9= new Rectangle (f,f,c,c);
//Parameters: MouseEvent e
//Returns: void
//Method Description: mouseReleased(): this method gets called whenever a user
//released the mouse on the JFrame.
public void mouseReleased(MouseEvent e){
int size=getWidth(); //length of the board
int x=e.getX();
int y=e.getY();
int pos=whichTile(x,y,size);//establish which tile mouse is on
//conditions for executing preceding "if" statement: mouse is in the area of a tile,
//the tile is unclaimed, and no one has won yet
if (pos>=0 && tiles[pos]==UNCLAIMED && winner== ' ') {
tiles[pos]=X; //claim current tile by X
repaint(); //update board
turnO(); //computer's turn
}
}
//Parameters: int x, int y, (x,y= mouse coordinate), int size (length of board)
//Returns: and integer (representing a tile)
//Method Description: whichTile(): determines which tile the mouse is on and
//returns that tile number. If the mouse
//is not on a tile, the value -1 is returned.
int whichTile(int x, int y, int size){
if (inArea(A1,x,y)){
return 0;
}else if (inArea(A2,x,y)){
return 1;
}else if (inArea(A3,x,y)){
return 2;
}else if (inArea(A4,x,y)){
return 3;
}else if (inArea(A5,x,y)){
return 4;
}else if (inArea(A6,x,y)){
return 5;
}else if (inArea(A7,x,y)){
return 6;
}else if (inArea(A8,x,y)){
return 7;
}else if (inArea(A9,x,y)){
return 8;
}else {
return -1;
}
}
//Parameters: Rectangle A, int x, int y (x,y= mouse cooordinates, A=the given tile)
//Returns: boolean
//Method Description: inArea(): determines if the mouse coordinates are within
//the given tile.
public boolean inArea (Rectangle A, int x, int y){
return x>A.x && x<A.width && y> A.y && y< A.height;
}
}
//TicTacToeBoard: creates the board for the Tic Tac Toe game
private class TicTacToeBoard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public TicTacToeBoard(){ //constructor
repaint();
}
//Parameters: Graphics g
//Returns: void
//MethodDescription: paint(): paints the board of the TicTacToe game
public void paint(Graphics g){
int size=getWidth();
int h=getHeight();
if (g instanceof Graphics2D){//anti-aliasing
Graphics2D g2= (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); }
g.setColor(Color.black);
g.fillRect(0, 0, size,h); //background
//DRAW TILE SEPARATION
g.setColor(Color.white);
g.drawLine(size/3, 0, size/3, size);
g.drawLine (size/3*2,0,size/3*2,size);
g.drawLine(0, size/3, size, size/3);
g.drawLine (0,size/3*2,size,size/3*2);
((Graphics2D) g).setStroke(new BasicStroke(10)); //adjust thickness in line
//DRAW MARKERS
for (int i=0; i<9;i++){
int x= (int) ((i%3+0.5)*size/3.0); //set position of markers (x and o's)
int y= (int) ((i/3+0.5)*size/3.0);
int x2= (int) (size/10.0);
int y2= (int) (size/8.0);
if (tiles[i]==O) { //if the current tile[i] is O, then an O marker is drawn
g.drawOval(x-x2, y-y2, x2*2, y2*2);
}
else if (tiles[i]==X) {//if the current tile[i] is X, then an X marker is drawn
g.drawLine(x-x2, y-y2, x+x2, y+y2);
g.drawLine(x-x2, y+y2, x+x2, y-y2);
}
}
//DRAW STRING NOTIFTY A WIN/DRAW
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString (result, 10,size); //draws the string notifying the end result of the game.
}
}
}