Java Reference
In-Depth Information
xImage = ImageIO. read (
new
URL(getCodeBase () ,
"images/x.jpg"
));
oImage = ImageIO. read(
new
URL(getCodeBase () ,
"images/o.jpg"
));
}
catch
(Exception exception)
{
initBoard() ;
addMouseListener(
new
MyMouseListener () ) ;
}
public void
paint(Graphics g)
{
super
.paint(g);
Graphics2D g2 = (Graphics2D) g ;
g2 . setColor (Color .RED) ;
for
(Square r : squares)
{
r . draw(g2 , xImage , oImage) ;
}
}
public void
computerMove ()
{
if
(! squares . get(4) .hasValue())
{ // if middle is empty
squares . get(4) . placeCharacter(
'o'
);
return
;
Square bestRectangle = squares . get(0) ;
int
best = computeScore(bestRectangle) ;
for
(Square r : squares)
{
if
(computeScore(r)
>
best)
{
best = computeScore(r) ;
bestRectangle = r ;
}
}
bestRectangle . placeCharacter(
'o'
);
}
public boolean
isLine(
int
i,
int
j,
int
k,
char
c)
{
return
(squares . get( i ) . isCharacter(c)
&& squares . get( j ) . isCharacter(c) && squares . get(k) .
isCharacter(c)) ;
}
public boolean
wins(
char
c)
{
for
(
int
i=0;i
<
3 ;
i ++)
{
if
(isLine(3
i, 3
i+1,3
i+2,c)
||
// horizontal line
∗
∗
∗
(isLine(i , i + 3, i + 6, c)))
{
//vertical line
return true
;
}
if
(isLine(0, 4, 8, c)
||
isLine(2, 4, 6, c))
{
//diagonal
return true
;
return false
;
}
public boolean
winsWithNextMove( Square r ,
char
c)
{
r . placeCharacter(c) ;
if
(wins(c))
{