我的TicTacToe不改变转向。当我按一个单元格时,它只会标记带有标记“x”的单元格 。换句话说,它只加载'x'图片,而不加载其他'0'。游戏可以识别某人是否赢了,但是在赢钱中没有划出最后一个分数。先谢谢你。TicTacToe不改变转向
public class Frame extends JFrame{
private Cell cell[][] = new Cell[3][3];
private JPanel panel = new JPanel(new GridLayout(3, 3, 0, 0));
Frame(){
setSize(300, 300);
setName("TicTacToe");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
for(int i=0;i<3;i++){
for(int j=0; j<3; j++){
panel.add(cell[i][j] = new Cell());
}
}
add(panel);
}
public boolean CheckWin(char token){
for(int i=0; i<3; i++){
for(int j=0;j<3;j++){
if(cell[i][0].getToken() == token &&
cell[i][1].getToken() == token
&& cell[i][2].getToken() == token){
return true;
}
if(cell[0][j].getToken() == token &&
cell[1][j].getToken() == token
&& cell[2][j].getToken() == token){
return true;
}
}
}
if(cell[0][0].getToken() == token &&
cell[1][1].getToken() == token &&
cell[2][2].getToken() == token){
return true;
}
return false;
}
public boolean IsFull(){
for(int i=0; i<3; i++){
for(int j=0;j<3;j++){
if(cell[i][j].getToken() == ' '){
return false;
}
}
}
return true;
}
public class Cell extends JPanel{
private char whoseTurn = 'x';
private char token = ' ';
Cell(){
setBorder(new LineBorder(Color.red, 1));
addMouseListener(new MyMouseListener());
}
public char getToken() {
return token;
}
public void setToken(char token) {
this.token = token;
MakePictures();
}
public void MakePictures(){
if(getToken() == 'x'){
ImageIcon image = new ImageIcon(getClass().getResource("/Pictures/x.png"));
JLabel label = new JLabel(image);
pack();
add(label);
setVisible(true);
}
else if(getToken() == '0'){
ImageIcon image = new ImageIcon(getClass().getResource("/Pictures/0.png"));
JLabel label = new JLabel(image);
add(label);
pack();
setVisible(true);
}
}
public class MyMouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
if(token == ' ' && whoseTurn != ' ')
setToken(whoseTurn);
if(CheckWin(token)){
whoseTurn = ' ';
System.out.println("Voitit");
}
else if(IsFull()){
System.out.println("Tasapeli");
whoseTurn = ' ';
}
else{
whoseTurn = (whoseTurn == 'x') ? '0' : 'x';
System.out.println(whoseTurn);
}
}
}
}
}
这是主类。
public class TicTacToe {
public static void main(String[] args) {
Frame frame = new Frame();
}
}
你把'token'从'x'切换到'0'的地方? –
个人而言,我会改变我是如何利用令牌成为生产者/消费者信号量的......但我不想编码那个atm ..只是一个建议 –
您是否试图调试您的代码?如果是这样,你发现了什么? – Egl