Peace, mercy and blessings of God ,
I coded the TicTacToe game that is similar to "Introduction to java programming" book's one , but i have mysterious error , see that photo
and this is the code
// importings
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
// end
// applet
public class TicTacToe extends JApplet {
private char turn = ' ';
private TTTCell[][] cells = new TTTCell[3][3];
private JPanel p = new JPanel(new GridLayout(3,3));
// tells who's turn
public char turn(){
if(this.turn == ' ' || this.turn == 'o' ){
this.turn = 'x';
System.out.println("I am now X");
return this.turn;
}
this.turn = 'o';
System.out.println("I am now O");
return this.turn;
}
// end
public void init(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cells[i][j] = new TTTCell();
p.add(cells[i][j]);
}
}
add(p);
}
// game's single cell
public class TTTCell extends JPanel {
// the token on the cell ( can be either X or O )
private char token = ' ';
// tells whether the cell is empty , i didn't use it till now
public boolean tokenIsEmpty(){
if(token == ' '){
return true;
}
return true;
}
// sets the token on the cell and repaints it
public void setToken(char turn){
token=turn;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponents(g);
if(token == 'x'){
g.drawLine(10, 10, getWidth()-10, getHeight()-10);
g.drawLine(getWidth()-10, 10, 10, getHeight()-10);
// indicating what i am drawing
System.out.println("I am X shape");
}else if (token == 'o'){
g.drawOval(10, 10, getWidth()-20, getHeight()-20);
//indicating what i am drawing
System.out.println("I am Oval shape");
}
}
public TTTCell(){
this.setSize(20, 20);
this.setBorder(new LineBorder(Color.RED,1));
addMouseListener(new MouseListener());
}
public class MouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent event){
// set token only if it is not set
if(token == ' '){
setToken(turn());
}
}
}
}
}
Edited by 3m masr, 17 October 2010 - 09:21 AM.
thumbnailing


Sign In
Create Account

Back to top









