gpt4 book ai didi

java - 随机井字游戏图像翻转

转载 作者:行者123 更新时间:2023-11-30 09:08:38 25 4
gpt4 key购买 nike

我创建了一个基本的 Tic-Tac-Toe 类,它显示 9 个按钮,上面显示随机图像(每次运行时 - 不同的序列)。主要方法在另一个测试类中,它只是一个框架创建者。除此之外,我想添加一些事件处理。我已将“ActionListener”添加到按钮并想在“actionPerformed”方法中添加一些逻辑。每次我点击任何按钮时,它应该按 X -> O -> Blank -> X 的顺序连续更改图像。我不确定哪种逻辑适合这里以按上述顺序翻转图像(例如 for-loop,switch ETC。)。代码如下:

 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TicTacToe extends JFrame {

public JButton[][] labels = new JButton[3][3];
public ImageIcon[] icons = new ImageIcon[3];
public int r, c;

public TicTacToe() {
// TODO Auto-generated constructor stub

setLayout(new GridLayout(3, 3));


for (r = 0; r < labels.length; r++) {
for (c = 0; c < labels.length; c++) {
int random = (int)(Math.random() * 3 + 0);
System.out.println(random);
JButton s = new JButton(this.icons[random]);
this.add(s);
this.labels[r][c] = s;

if (random == 0) {
System.out.println("Cross Image Icon");
labels[r][c].setIcon(new ImageIcon("C:\\Users\\yogesh\\workspace\\hw3pandarey\\src\\hw3pandarey\\cross_symbol.gif"));
add(labels[r][c]);
validate();
} else if (random == 1) {
System.out.println("Not Image Icon");
labels[r][c].setIcon(new ImageIcon("C:\\Users\\yogesh\\workspace\\hw3pandarey\\src\\hw3pandarey\\zero_symbol.gif"));
add(labels[r][c]);
validate();
} else if (random == 2) {
System.out.println("Keep it blank");
labels[r][c].setIcon(new ImageIcon());
add(labels[r][c]);
validate();
}

labels[r][c].addActionListener(new ButtonListener());

}
}


} // end of TicTacToe constructor

public class ButtonListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

} // end of actionPerformed method

} // end of ButtonListener class


} // end of TicTacToe class

import javax.swing.*;

public class TicTacToeTest {

public static void main(String[] args) {
TicTacToe frame = new TicTacToe();
frame.setTitle("Let's play a random tic-tac-toe game !!!!!");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

} //end of main method
} // end of test class

最佳答案

您可以像这样使用 setText 方法在 JButton 上放置 X 或 O。您只需要添加一个变量即可知道它是 X 转弯还是 O 转弯。希望这有帮助

public class ButtonListener implements ActionListener 
{

public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if(src==labels[i][j]&&labels[i][j].getText()==""){
//if X turn
labels[i][j].setText("X");

}
//if O turn
//labels[i][j].setText("O");
}
}

}// end of actionPerformed method

} // end of ButtonListener class

关于java - 随机井字游戏图像翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com